1 /***************************************************************************
2 
3   ym2610.c
4 
5   Software emulation for YAMAHA YM-2610 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   Comming from NJ pspmvs emu comming from Mame
13 
14 ***************************************************************************/
15 
16 /*--------------------------------------------------------------------------
17 
18  History:
19 
20  03-08-2003 Jarek Burczynski:
21   - fixed YM2608 initial values (after the reset)
22   - fixed flag and irqmask handling (YM2608)
23   - fixed BUFRDY flag handling (YM2608)
24 
25  14-06-2003 Jarek Burczynski:
26   - implemented all of the YM2608 status register flags
27   - implemented support for external memory read/write via YM2608
28   - implemented support for deltat memory limit register in YM2608 emulation
29 
30  22-05-2003 Jarek Burczynski:
31   - fixed LFO PM calculations (copy&paste bugfix)
32 
33  08-05-2003 Jarek Burczynski:
34   - fixed SSG support
35 
36  22-04-2003 Jarek Burczynski:
37   - implemented 100% correct LFO generator (verified on real YM2610 and YM2608)
38 
39  15-04-2003 Jarek Burczynski:
40   - added support for YM2608's register 0x110 - status mask
41 
42  01-12-2002 Jarek Burczynski:
43   - fixed register addressing in YM2608, YM2610, YM2610B chips. (verified on real YM2608)
44     The addressing patch used for early Neo-Geo games can be removed now.
45 
46  26-11-2002 Jarek Burczynski, Nicola Salmoria:
47   - recreated YM2608 ADPCM ROM using data from real YM2608's output which leads to:
48   - added emulation of YM2608 drums.
49   - output of YM2608 is two times lower now - same as YM2610 (verified on real YM2608)
50 
51  16-08-2002 Jarek Burczynski:
52   - binary exact Envelope Generator (verified on real YM2203);
53     identical to YM2151
54   - corrected 'off by one' error in feedback calculations (when feedback is off)
55   - corrected connection (algorithm) calculation (verified on real YM2203 and YM2610)
56 
57  18-12-2001 Jarek Burczynski:
58   - added SSG-EG support (verified on real chip)
59 
60  12-08-2001 Jarek Burczynski:
61   - corrected sin_tab and tl_tab data (verified on real chip)
62   - corrected feedback calculations (verified on real chip)
63   - corrected phase generator calculations (verified on real chip)
64   - corrected envelope generator calculations (verified on real chip)
65   - corrected volume level.
66   - changed YM2610Update() function:
67     this was needed to calculate YM2610 FM channels output correctly.
68     (Each FM channel is calculated as in other chips, but the output of the
69     channel gets shifted right by one *before* sending to accumulator.
70     That was impossible to do with previous implementation).
71 
72  23-07-2001 Jarek Burczynski, Nicola Salmoria:
73   - corrected ADPCM type A algorithm and tables (verified on real chip)
74 
75  11-06-2001 Jarek Burczynski:
76   - corrected end of sample bug in OPNB_ADPCM_CALC_CH.
77     Real YM2610 checks for equality between current and end addresses
78     (only 20 LSB bits).
79 
80  08-12-1998 hiro-shi:
81   - rename ADPCMA -> ADPCMB, ADPCMB -> DELTAT
82   - move ROM limit check.(CALC_CH? -> 2610Write1/2)
83   - test program (ADPCMB_TEST)
84   - move ADPCM A/B end check.
85   - ADPCMB repeat flag(no check)
86   - change ADPCM volume rate (8->16) (32->48).
87 
88  09-12-1998 hiro-shi:
89   - change ADPCM volume. (8->16, 48->64)
90   - replace ym2610 ch0/3 (YM-2610B)
91   - init cur_chip (restart bug fix)
92   - change ADPCM_SHIFT (10->8) missing bank change 0x4000-0xffff.
93   - add ADPCM_SHIFT_MASK
94   - change ADPCMA_DECODE_MIN/MAX.
95 
96 ----------------------------------------------------------------------------
97 
98   comment of hiro-shi(Hiromitsu Shioya):
99     YM2610 = OPN-B
100     YM2610 : PSG:3ch FM:4ch ADPCM(18.5KHz):6ch DeltaT ADPCM:1ch
101 
102 --------------------------------------------------------------------------*/
103 
104 #ifdef HAVE_CONFIG_H
105 #include "config.h"
106 #endif
107 
108 
109 #include <stdio.h>
110 #include <stdlib.h>
111 #include <string.h>
112 #include <stdarg.h>
113 #include <math.h>
114 
115 #include "mvs.h"
116 #include "../state.h"
117 #include "2610intf.h"
118 #include "ym2610.h"
119 
120 
121 #ifndef PI
122 #define PI 3.14159265358979323846
123 #endif
124 
125 
126 /* select timer system internal or external */
127 #define FM_INTERNAL_TIMER 0
128 
129 /* --- speedup optimize --- */
130 /* busy flag enulation , The definition of FM_GET_TIME_NOW() is necessary. */
131 #define FM_BUSY_FLAG_SUPPORT 1
132 
133 
134 /*------------------------------------------------------------------------*/
135 
136 #define FREQ_SH			16  /* 16.16 fixed point (frequency calculations) */
137 #define EG_SH			16  /* 16.16 fixed point (envelope generator timing) */
138 #define LFO_SH			24  /*  8.24 fixed point (LFO calculations)       */
139 #define TIMER_SH		16  /* 16.16 fixed point (timers calculations)    */
140 
141 #define FREQ_MASK		((1<<FREQ_SH)-1)
142 
143 #define ENV_BITS		10
144 #define ENV_LEN			(1<<ENV_BITS)
145 #define ENV_STEP		(128.0/ENV_LEN)
146 
147 #define MAX_ATT_INDEX	(ENV_LEN-1) /* 1023 */
148 #define MIN_ATT_INDEX	(0)			/* 0 */
149 
150 #define EG_ATT			4
151 #define EG_DEC			3
152 #define EG_SUS			2
153 #define EG_REL			1
154 #define EG_OFF			0
155 
156 #define SIN_BITS		10
157 #define SIN_LEN			(1<<SIN_BITS)
158 #define SIN_MASK		(SIN_LEN-1)
159 
160 #define TL_RES_LEN		(256) /* 8 bits addressing (real chip) */
161 
162 
163 #define FINAL_SH	(0)
164 #define MAXOUT		(+32767)
165 #define MINOUT		(-32768)
166 
167 
168 /*  TL_TAB_LEN is calculated as:
169 *   13 - sinus amplitude bits     (Y axis)
170 *   2  - sinus sign bit           (Y axis)
171 *   TL_RES_LEN - sinus resolution (X axis)
172 */
173 #define TL_TAB_LEN (13*2*TL_RES_LEN)
174 static signed int ALIGN_DATA tl_tab[TL_TAB_LEN];
175 
176 
177 #define ENV_QUIET		(TL_TAB_LEN>>3)
178 
179 /* sin waveform table in 'decibel' scale */
180 static unsigned int ALIGN_DATA sin_tab[SIN_LEN];
181 
182 /* sustain level table (3dB per step) */
183 /* bit0, bit1, bit2, bit3, bit4, bit5, bit6 */
184 /* 1,    2,    4,    8,    16,   32,   64   (value)*/
185 /* 0.75, 1.5,  3,    6,    12,   24,   48   (dB)*/
186 
187 /* 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,93 (dB)*/
188 #define SC(db) (u32) ( db * (4.0/ENV_STEP) )
189 static const u32 ALIGN_DATA sl_table[16]={
190  SC( 0),SC( 1),SC( 2),SC(3 ),SC(4 ),SC(5 ),SC(6 ),SC( 7),
191  SC( 8),SC( 9),SC(10),SC(11),SC(12),SC(13),SC(14),SC(31)
192 };
193 #undef SC
194 
195 
196 #define RATE_STEPS (8)
197 static const u8 ALIGN_DATA eg_inc[19*RATE_STEPS]={
198 
199 /*cycle:0 1  2 3  4 5  6 7*/
200 
201 /* 0 */ 0,1, 0,1, 0,1, 0,1, /* rates 00..11 0 (increment by 0 or 1) */
202 /* 1 */ 0,1, 0,1, 1,1, 0,1, /* rates 00..11 1 */
203 /* 2 */ 0,1, 1,1, 0,1, 1,1, /* rates 00..11 2 */
204 /* 3 */ 0,1, 1,1, 1,1, 1,1, /* rates 00..11 3 */
205 
206 /* 4 */ 1,1, 1,1, 1,1, 1,1, /* rate 12 0 (increment by 1) */
207 /* 5 */ 1,1, 1,2, 1,1, 1,2, /* rate 12 1 */
208 /* 6 */ 1,2, 1,2, 1,2, 1,2, /* rate 12 2 */
209 /* 7 */ 1,2, 2,2, 1,2, 2,2, /* rate 12 3 */
210 
211 /* 8 */ 2,2, 2,2, 2,2, 2,2, /* rate 13 0 (increment by 2) */
212 /* 9 */ 2,2, 2,4, 2,2, 2,4, /* rate 13 1 */
213 /*10 */ 2,4, 2,4, 2,4, 2,4, /* rate 13 2 */
214 /*11 */ 2,4, 4,4, 2,4, 4,4, /* rate 13 3 */
215 
216 /*12 */ 4,4, 4,4, 4,4, 4,4, /* rate 14 0 (increment by 4) */
217 /*13 */ 4,4, 4,8, 4,4, 4,8, /* rate 14 1 */
218 /*14 */ 4,8, 4,8, 4,8, 4,8, /* rate 14 2 */
219 /*15 */ 4,8, 8,8, 4,8, 8,8, /* rate 14 3 */
220 
221 /*16 */ 8,8, 8,8, 8,8, 8,8, /* rates 15 0, 15 1, 15 2, 15 3 (increment by 8) */
222 /*17 */ 16,16,16,16,16,16,16,16, /* rates 15 2, 15 3 for attack */
223 /*18 */ 0,0, 0,0, 0,0, 0,0, /* infinity rates for attack and decay(s) */
224 };
225 
226 
227 #define O(a) (a*RATE_STEPS)
228 
229 /*note that there is no O(17) in this table - it's directly in the code */
230 static const u8 ALIGN_DATA eg_rate_select[32+64+32]={	/* Envelope Generator rates (32 + 64 rates + 32 RKS) */
231 /* 32 infinite time rates */
232 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
233 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
234 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
235 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
236 
237 /* rates 00-11 */
238 O( 0),O( 1),O( 2),O( 3),
239 O( 0),O( 1),O( 2),O( 3),
240 O( 0),O( 1),O( 2),O( 3),
241 O( 0),O( 1),O( 2),O( 3),
242 O( 0),O( 1),O( 2),O( 3),
243 O( 0),O( 1),O( 2),O( 3),
244 O( 0),O( 1),O( 2),O( 3),
245 O( 0),O( 1),O( 2),O( 3),
246 O( 0),O( 1),O( 2),O( 3),
247 O( 0),O( 1),O( 2),O( 3),
248 O( 0),O( 1),O( 2),O( 3),
249 O( 0),O( 1),O( 2),O( 3),
250 
251 /* rate 12 */
252 O( 4),O( 5),O( 6),O( 7),
253 
254 /* rate 13 */
255 O( 8),O( 9),O(10),O(11),
256 
257 /* rate 14 */
258 O(12),O(13),O(14),O(15),
259 
260 /* rate 15 */
261 O(16),O(16),O(16),O(16),
262 
263 /* 32 dummy rates (same as 15 3) */
264 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
265 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
266 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
267 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16)
268 
269 };
270 #undef O
271 
272 /*rate  0,    1,    2,   3,   4,   5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15*/
273 /*shift 11,   10,   9,   8,   7,   6,  5,  4,  3,  2, 1,  0,  0,  0,  0,  0 */
274 /*mask  2047, 1023, 511, 255, 127, 63, 31, 15, 7,  3, 1,  0,  0,  0,  0,  0 */
275 
276 #define O(a) (a*1)
277 static const u8 ALIGN_DATA eg_rate_shift[32+64+32]={	/* Envelope Generator counter shifts (32 + 64 rates + 32 RKS) */
278 /* 32 infinite time rates */
279 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
280 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
281 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
282 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
283 
284 /* rates 00-11 */
285 O(11),O(11),O(11),O(11),
286 O(10),O(10),O(10),O(10),
287 O( 9),O( 9),O( 9),O( 9),
288 O( 8),O( 8),O( 8),O( 8),
289 O( 7),O( 7),O( 7),O( 7),
290 O( 6),O( 6),O( 6),O( 6),
291 O( 5),O( 5),O( 5),O( 5),
292 O( 4),O( 4),O( 4),O( 4),
293 O( 3),O( 3),O( 3),O( 3),
294 O( 2),O( 2),O( 2),O( 2),
295 O( 1),O( 1),O( 1),O( 1),
296 O( 0),O( 0),O( 0),O( 0),
297 
298 /* rate 12 */
299 O( 0),O( 0),O( 0),O( 0),
300 
301 /* rate 13 */
302 O( 0),O( 0),O( 0),O( 0),
303 
304 /* rate 14 */
305 O( 0),O( 0),O( 0),O( 0),
306 
307 /* rate 15 */
308 O( 0),O( 0),O( 0),O( 0),
309 
310 /* 32 dummy rates (same as 15 3) */
311 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
312 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
313 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
314 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0)
315 
316 };
317 #undef O
318 
319 static const u8 ALIGN_DATA dt_tab[4 * 32]={
320 /* this is YM2151 and YM2612 phase increment data (in 10.10 fixed point format)*/
321 /* FD=0 */
322 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
323 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
324 /* FD=1 */
325 	0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
326 	2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
327 /* FD=2 */
328 	1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5,
329 	5, 6, 6, 7, 8, 8, 9,10,11,12,13,14,16,16,16,16,
330 /* FD=3 */
331 	2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7,
332 	8 , 8, 9,10,11,12,13,14,16,17,19,20,22,22,22,22
333 };
334 
335 
336 /* OPN key frequency number -> key code follow table */
337 /* fnum higher 4bit -> keycode lower 2bit */
338 static const u8 ALIGN_DATA opn_fktable[16] = {0,0,0,0,0,0,0,1,2,3,3,3,3,3,3,3};
339 
340 
341 /* 8 LFO speed parameters */
342 /* each value represents number of samples that one LFO level will last for */
343 static const u32 ALIGN_DATA lfo_samples_per_step[8] = {108, 77, 71, 67, 62, 44, 8, 5};
344 
345 
346 
347 /*There are 4 different LFO AM depths available, they are:
348   0 dB, 1.4 dB, 5.9 dB, 11.8 dB
349   Here is how it is generated (in EG steps):
350 
351   11.8 dB = 0, 2, 4, 6, 8, 10,12,14,16...126,126,124,122,120,118,....4,2,0
352    5.9 dB = 0, 1, 2, 3, 4, 5, 6, 7, 8....63, 63, 62, 61, 60, 59,.....2,1,0
353    1.4 dB = 0, 0, 0, 0, 1, 1, 1, 1, 2,...15, 15, 15, 15, 14, 14,.....0,0,0
354 
355   (1.4 dB is loosing precision as you can see)
356 
357   It's implemented as generator from 0..126 with step 2 then a shift
358   right N times, where N is:
359     8 for 0 dB
360     3 for 1.4 dB
361     1 for 5.9 dB
362     0 for 11.8 dB
363 */
364 static const u8 lfo_ams_depth_shift[4] = {8, 3, 1, 0};
365 
366 
367 
368 /*There are 8 different LFO PM depths available, they are:
369   0, 3.4, 6.7, 10, 14, 20, 40, 80 (cents)
370 
371   Modulation level at each depth depends on F-NUMBER bits: 4,5,6,7,8,9,10
372   (bits 8,9,10 = FNUM MSB from OCT/FNUM register)
373 
374   Here we store only first quarter (positive one) of full waveform.
375   Full table (lfo_pm_table) containing all 128 waveforms is build
376   at run (init) time.
377 
378   One value in table below represents 4 (four) basic LFO steps
379   (1 PM step = 4 AM steps).
380 
381   For example:
382    at LFO SPEED=0 (which is 108 samples per basic LFO step)
383    one value from "lfo_pm_output" table lasts for 432 consecutive
384    samples (4*108=432) and one full LFO waveform cycle lasts for 13824
385    samples (32*432=13824; 32 because we store only a quarter of whole
386             waveform in the table below)
387 */
388 static const u8 ALIGN_DATA 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 */
389 /* FNUM BIT 4: 000 0001xxxx */
390 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
391 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
392 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   0,   0},
393 /* DEPTH 3 */ {0,   0,   0,   0,   0,   0,   0,   0},
394 /* DEPTH 4 */ {0,   0,   0,   0,   0,   0,   0,   0},
395 /* DEPTH 5 */ {0,   0,   0,   0,   0,   0,   0,   0},
396 /* DEPTH 6 */ {0,   0,   0,   0,   0,   0,   0,   0},
397 /* DEPTH 7 */ {0,   0,   0,   0,   1,   1,   1,   1},
398 
399 /* FNUM BIT 5: 000 0010xxxx */
400 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
401 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
402 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   0,   0},
403 /* DEPTH 3 */ {0,   0,   0,   0,   0,   0,   0,   0},
404 /* DEPTH 4 */ {0,   0,   0,   0,   0,   0,   0,   0},
405 /* DEPTH 5 */ {0,   0,   0,   0,   0,   0,   0,   0},
406 /* DEPTH 6 */ {0,   0,   0,   0,   1,   1,   1,   1},
407 /* DEPTH 7 */ {0,   0,   1,   1,   2,   2,   2,   3},
408 
409 /* FNUM BIT 6: 000 0100xxxx */
410 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
411 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
412 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   0,   0},
413 /* DEPTH 3 */ {0,   0,   0,   0,   0,   0,   0,   0},
414 /* DEPTH 4 */ {0,   0,   0,   0,   0,   0,   0,   1},
415 /* DEPTH 5 */ {0,   0,   0,   0,   1,   1,   1,   1},
416 /* DEPTH 6 */ {0,   0,   1,   1,   2,   2,   2,   3},
417 /* DEPTH 7 */ {0,   0,   2,   3,   4,   4,   5,   6},
418 
419 /* FNUM BIT 7: 000 1000xxxx */
420 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
421 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
422 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   1,   1},
423 /* DEPTH 3 */ {0,   0,   0,   0,   1,   1,   1,   1},
424 /* DEPTH 4 */ {0,   0,   0,   1,   1,   1,   1,   2},
425 /* DEPTH 5 */ {0,   0,   1,   1,   2,   2,   2,   3},
426 /* DEPTH 6 */ {0,   0,   2,   3,   4,   4,   5,   6},
427 /* DEPTH 7 */ {0,   0,   4,   6,   8,   8, 0xa, 0xc},
428 
429 /* FNUM BIT 8: 001 0000xxxx */
430 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
431 /* DEPTH 1 */ {0,   0,   0,   0,   1,   1,   1,   1},
432 /* DEPTH 2 */ {0,   0,   0,   1,   1,   1,   2,   2},
433 /* DEPTH 3 */ {0,   0,   1,   1,   2,   2,   3,   3},
434 /* DEPTH 4 */ {0,   0,   1,   2,   2,   2,   3,   4},
435 /* DEPTH 5 */ {0,   0,   2,   3,   4,   4,   5,   6},
436 /* DEPTH 6 */ {0,   0,   4,   6,   8,   8, 0xa, 0xc},
437 /* DEPTH 7 */ {0,   0,   8, 0xc,0x10,0x10,0x14,0x18},
438 
439 /* FNUM BIT 9: 010 0000xxxx */
440 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
441 /* DEPTH 1 */ {0,   0,   0,   0,   2,   2,   2,   2},
442 /* DEPTH 2 */ {0,   0,   0,   2,   2,   2,   4,   4},
443 /* DEPTH 3 */ {0,   0,   2,   2,   4,   4,   6,   6},
444 /* DEPTH 4 */ {0,   0,   2,   4,   4,   4,   6,   8},
445 /* DEPTH 5 */ {0,   0,   4,   6,   8,   8, 0xa, 0xc},
446 /* DEPTH 6 */ {0,   0,   8, 0xc,0x10,0x10,0x14,0x18},
447 /* DEPTH 7 */ {0,   0,0x10,0x18,0x20,0x20,0x28,0x30},
448 
449 /* FNUM BIT10: 100 0000xxxx */
450 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
451 /* DEPTH 1 */ {0,   0,   0,   0,   4,   4,   4,   4},
452 /* DEPTH 2 */ {0,   0,   0,   4,   4,   4,   8,   8},
453 /* DEPTH 3 */ {0,   0,   4,   4,   8,   8, 0xc, 0xc},
454 /* DEPTH 4 */ {0,   0,   4,   8,   8,   8, 0xc,0x10},
455 /* DEPTH 5 */ {0,   0,   8, 0xc,0x10,0x10,0x14,0x18},
456 /* DEPTH 6 */ {0,   0,0x10,0x18,0x20,0x20,0x28,0x30},
457 /* DEPTH 7 */ {0,   0,0x20,0x30,0x40,0x40,0x50,0x60},
458 
459 };
460 
461 /* all 128 LFO PM waveforms */
462 static s32 ALIGN_DATA 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 */
463 
464 
465 /*----------------------------------
466 	for SSG emulator
467 -----------------------------------*/
468 
469 #define SSG_MAX_OUTPUT 0x7fff
470 #define SSG_STEP 0x8000
471 
472 /* SSG register ID */
473 #define SSG_AFINE		(0)
474 #define SSG_ACOARSE		(1)
475 #define SSG_BFINE		(2)
476 #define SSG_BCOARSE		(3)
477 #define SSG_CFINE		(4)
478 #define SSG_CCOARSE		(5)
479 #define SSG_NOISEPER	(6)
480 #define SSG_ENABLE		(7)
481 #define SSG_AVOL		(8)
482 #define SSG_BVOL		(9)
483 #define SSG_CVOL		(10)
484 #define SSG_EFINE		(11)
485 #define SSG_ECOARSE		(12)
486 #define SSG_ESHAPE		(13)
487 
488 #define SSG_PORTA		(14)
489 #define SSG_PORTB		(15)
490 
491 
492 /* register number to channel number , slot offset */
493 #define OPN_CHAN(N) (N&3)
494 #define OPN_SLOT(N) ((N>>2)&3)
495 
496 /* slot number */
497 #define SLOT1 0
498 #define SLOT2 2
499 #define SLOT3 1
500 #define SLOT4 3
501 
502 /* bit0 = Right enable , bit1 = Left enable */
503 #define OUTD_RIGHT  1
504 #define OUTD_LEFT   2
505 #define OUTD_CENTER 3
506 
507 
508 /* struct describing a single operator (SLOT) */
509 typedef struct
510 {
511 	s32	*DT;		/* detune          :dt_tab[DT] */
512 	u8	KSR;		/* key scale rate  :3-KSR */
513 	u32	ar;			/* attack rate  */
514 	u32	d1r;		/* decay rate   */
515 	u32	d2r;		/* sustain rate */
516 	u32	rr;			/* release rate */
517 	u8	ksr;		/* key scale rate  :kcode>>(3-KSR) */
518 	u32	mul;		/* multiple        :ML_TABLE[ML] */
519 
520 	/* Phase Generator */
521 	u32	phase;		/* phase counter */
522 	u32	Incr;		/* phase step */
523 
524 	/* Envelope Generator */
525 	u8	state;		/* phase type */
526 	u32	tl;			/* total level: TL << 3 */
527 	s32	volume;		/* envelope counter */
528 	u32	sl;			/* sustain level:sl_table[SL] */
529 	u32	vol_out;	/* current output from EG circuit (without AM from LFO) */
530 
531 	u8	eg_sh_ar;	/*  (attack state) */
532 	u8	eg_sel_ar;	/*  (attack state) */
533 	u8	eg_sh_d1r;	/*  (decay state) */
534 	u8	eg_sel_d1r;	/*  (decay state) */
535 	u8	eg_sh_d2r;	/*  (sustain state) */
536 	u8	eg_sel_d2r;	/*  (sustain state) */
537 	u8	eg_sh_rr;	/*  (release state) */
538 	u8	eg_sel_rr;	/*  (release state) */
539 
540 	u8	ssg;		/* SSG-EG waveform */
541 	u8	ssgn;		/* SSG-EG negated output */
542 
543 	u32	key;		/* 0=last key was KEY OFF, 1=KEY ON */
544 
545 	/* LFO */
546 	u32	AMmask;		/* AM enable flag */
547 
548 } FM_SLOT;
549 
550 typedef struct
551 {
552 	FM_SLOT	SLOT[4];	/* four SLOTs (operators) */
553 
554 	u8	ALGO;		/* algorithm */
555 	u8	FB;			/* feedback shift */
556 	s32	op1_out[2];	/* op1 output for feedback */
557 
558 	s32	*connect1;	/* SLOT1 output pointer */
559 	s32	*connect3;	/* SLOT3 output pointer */
560 	s32	*connect2;	/* SLOT2 output pointer */
561 	s32	*connect4;	/* SLOT4 output pointer */
562 
563 	s32	*mem_connect;/* where to put the delayed sample (MEM) */
564 	s32	mem_value;	/* delayed sample (MEM) value */
565 
566 	s32	pms;		/* channel PMS */
567 	u8	ams;		/* channel AMS */
568 
569 	u32	fc;			/* fnum,blk:adjusted to sample rate */
570 	u8	kcode;		/* key code:                        */
571 	u32	block_fnum;	/* current blk/fnum value for this slot (can be different betweeen slots of one channel in 3slot mode) */
572 } FM_CH;
573 
574 
575 typedef struct
576 {
577 	int		clock;		/* master clock  (Hz)   */
578 	int		rate;		/* sampling rate (Hz)   */
579 	double	freqbase;	/* frequency base       */
580 	double	TimerBase;	/* Timer base time      */
581 #if FM_BUSY_FLAG_SUPPORT
582 	double	BusyExpire;	/* ExpireTime of Busy clear */
583 #endif
584 	u8	address;	/* address register     */
585 	u8	irq;		/* interrupt level      */
586 	u8	irqmask;	/* irq mask             */
587 	u8	status;		/* status flag          */
588 	u32	mode;		/* mode  CSM / 3SLOT    */
589 	u8	prescaler_sel;/* prescaler selector */
590 	u8	fn_h;		/* freq latch           */
591 	s32	TA;			/* timer a              */
592 	s32	TAC;		/* timer a counter      */
593 	u8	TB;			/* timer b              */
594 	s32	TBC;		/* timer b counter      */
595 	/* local time tables */
596 	s32	dt_tab[8][32];/* DeTune table       */
597 	/* Extention Timer and IRQ handler */
598 	FM_TIMERHANDLER	Timer_Handler;
599 	FM_IRQHANDLER	IRQ_Handler;
600 } FM_ST;
601 
602 
603 /* OPN 3slot struct */
604 typedef struct
605 {
606 	u32  fc[3];			/* fnum3,blk3: calculated */
607 	u8	fn_h;			/* freq3 latch */
608 	u8	kcode[3];		/* key code */
609 	u32	block_fnum[3];	/* current fnum value for this slot (can be different betweeen slots of one channel in 3slot mode) */
610 } FM_3SLOT;
611 
612 /* OPN/A/B common state */
613 typedef struct
614 {
615 	FM_ST	ST;				/* general state */
616 	FM_3SLOT SL3;			/* 3 slot mode state */
617 	FM_CH	*P_CH;			/* pointer of CH */
618 	unsigned int pan[6*2];	/* fm channels output masks (0xffffffff = enable) */
619 
620 	u32	eg_cnt;			/* global envelope generator counter */
621 	u32	eg_timer;		/* global envelope generator counter works at frequency = chipclock/64/3 */
622 	u32	eg_timer_add;	/* step of eg_timer */
623 	u32	eg_timer_overflow;/* envelope generator timer overlfows every 3 samples (on real chip) */
624 
625 
626 	/* there are 2048 FNUMs that can be generated using FNUM/BLK registers
627         but LFO works with one more bit of a precision so we really need 4096 elements */
628 
629 	u32	fn_table[4096];	/* fnumber->increment counter */
630 
631 
632 	/* LFO */
633 	u32	lfo_cnt;
634 	u32	lfo_inc;
635 
636 	u32	lfo_freq[8];	/* LFO FREQ table */
637 } FM_OPN;
638 
639 
640 /* SSG struct */
641 static struct SSG_t
642 {
643 	int		lastEnable;
644 	u32		step;
645 	int		period[3];
646 	int		PeriodN;
647 	int		PeriodE;
648 	int		count[3];
649 	int		CountN;
650 	int		CountE;
651 	u32		vol[3];
652 	u32		VolE;
653 	u8		envelope[3];
654 	u8		output[3];
655 	u8		OutputN;
656 	s8		count_env;
657 	u8		hold;
658 	u8		alternate;
659 	u8		attack;
660 	u8		holding;
661 	int		RNG;
662 	u32		vol_table[32];
663 } SSG;
664 
665 
666 /* ADPCM type A channel struct */
667 typedef struct
668 {
669 	u8		flag;			/* port state				*/
670 	u8		flagMask;		/* arrived flag mask		*/
671 	u8		now_data;		/* current ROM data			*/
672 	u32		now_addr;		/* current ROM address		*/
673 	u32		now_step;
674 	u32		step;
675 	u32		start;			/* sample data start address*/
676 	u32		end;			/* sample data end address	*/
677 	u8		IL;				/* Instrument Level			*/
678 	s32		adpcma_acc;		/* accumulator				*/
679 	s32		adpcma_step;	/* step						*/
680 	s32		adpcma_out;		/* (speedup) hiro-shi!!		*/
681 	s8		vol_mul;		/* volume in "0.75dB" steps	*/
682 	u8		vol_shift;		/* volume in "-6dB" steps	*/
683 	s32		*pan;			/* &out_adpcma[OPN_xxxx] 	*/
684 } ADPCMA;
685 
686 
687 /* ADPCM type B struct */
688 typedef struct adpcmb_state
689 {
690 	s32		*pan;			/* pan : &output_pointer[pan]   */
691 	double	freqbase;
692 	int		output_range;
693 	u32		now_addr;		/* current address      */
694 	u32		now_step;		/* currect step         */
695 	u32		step;			/* step                 */
696 	u32		start;			/* start address        */
697 	u32		limit;			/* limit address        */
698 	u32		end;			/* end address          */
699 	u32		delta;			/* delta scale          */
700 	s32		volume;			/* current volume       */
701 	s32		acc;			/* shift Measurement value*/
702 	s32		adpcmd;			/* next Forecast        */
703 	s32		adpcml;			/* current value        */
704 	s32		prev_acc;		/* leveling value       */
705 	u8		now_data;		/* current rom data     */
706 	u8		CPU_data;		/* current data from reg 08 */
707 	u8		portstate;		/* port status          */
708 	u8		control2;		/* control reg: SAMPLE, DA/AD, RAM TYPE (x8bit / x1bit), ROM/RAM */
709 	u8		portshift;		/* address bits shift-left:
710                             ** 8 for YM2610,
711                             ** 5 for Y8950 and YM2608 */
712 
713 	u8		DRAMportshift;	/* address bits shift-right:
714                             ** 0 for ROM and x8bit DRAMs,
715                             ** 3 for x1 DRAMs */
716 
717 	u8		memread;		/* needed for reading/writing external memory */
718 
719 	/* note that different chips have these flags on different
720     ** bits of the status register
721     */
722 	u8		status_change_EOS_bit;		/* 1 on End Of Sample (record/playback/cycle time of AD/DA converting has passed)*/
723 	u8		status_change_BRDY_bit;		/* 1 after recording 2 datas (2x4bits) or after reading/writing 1 data */
724 
725 	/* neither Y8950 nor YM2608 can generate IRQ when PCMBSY bit changes, so instead of above,
726     ** the statusflag gets ORed with PCM_BSY (below) (on each read of statusflag of Y8950 and YM2608)
727     */
728 	u8		PCM_BSY;		/* 1 when ADPCM is playing; Y8950/YM2608 only */
729 
730 } ADPCMB;
731 
732 
733 /* here's the virtual YM2610 */
734 static struct ym2610_t
735 {
736 	u8		regs[512];			/* registers            */
737 	FM_OPN	OPN;				/* OPN state            */
738 	FM_CH	CH[6];				/* channel state        */
739 	u8		addr_A1;			/* address line A1      */
740 
741 	/* ADPCM-A unit */
742 	u8		adpcmaTL;			/* adpcmA total level   */
743 	ADPCMA	adpcma[6];			/* adpcm channels       */
744 	u8		adpcm_arrivedEndAddress;
745 
746 	/* ADPCM-B unit */
747 	ADPCMB	adpcmb;				/* Delta-T ADPCM unit   */
748 
749 } ALIGN_DATA YM2610;
750 
751 
752 /* current chip state */
753 static s32	m2,c1,c2;		/* Phase Modulation input for operators 2,3,4 */
754 static s32	mem;			/* one sample delay memory */
755 
756 static s32	ALIGN_DATA out_fm[8];		/* outputs of working channels */
757 static s32	out_ssg;					/* channel output CHENTER only for SSG */
758 static s32	ALIGN_DATA out_adpcma[4];	/* channel output NONE,LEFT,RIGHT or CENTER for YM2608/YM2610 ADPCM */
759 static s32	ALIGN_DATA out_delta[4];	/* channel output NONE,LEFT,RIGHT or CENTER for YM2608/YM2610 DELTAT*/
760 
761 static u32	LFO_AM;			/* runtime LFO calculations helper */
762 static s32	LFO_PM;			/* runtime LFO calculations helper */
763 
764 
765 /* log output level */
766 #define LOG_ERR  3      /* ERROR       */
767 #define LOG_WAR  2      /* WARNING     */
768 #define LOG_INF  1      /* INFORMATION */
769 #define LOG_LEVEL LOG_INF
770 
771 #define LOG(n,x) if( (n)>=LOG_LEVEL ) logerror x
772 
773 /*********************************************************************************************/
774 
775 /* status set and IRQ handling */
FM_STATUS_SET(FM_ST * ST,int flag)776 INLINE void FM_STATUS_SET(FM_ST *ST,int flag)
777 {
778 	/* set status flag */
779 	ST->status |= flag;
780 	if ( !(ST->irq) && (ST->status & ST->irqmask) )
781 	{
782 		ST->irq = 1;
783 		/* callback user interrupt handler (IRQ is OFF to ON) */
784 		(ST->IRQ_Handler)(1);
785 	}
786 }
787 
788 /* status reset and IRQ handling */
FM_STATUS_RESET(FM_ST * ST,int flag)789 INLINE void FM_STATUS_RESET(FM_ST *ST,int flag)
790 {
791 	/* reset status flag */
792 	ST->status &=~flag;
793 	if ( (ST->irq) && !(ST->status & ST->irqmask) )
794 	{
795 		ST->irq = 0;
796 		/* callback user interrupt handler (IRQ is ON to OFF) */
797 		(ST->IRQ_Handler)(0);
798 	}
799 }
800 
801 /* IRQ mask set */
FM_IRQMASK_SET(FM_ST * ST,int flag)802 INLINE void FM_IRQMASK_SET(FM_ST *ST,int flag)
803 {
804 	ST->irqmask = flag;
805 	/* IRQ handling check */
806 	FM_STATUS_SET(ST,0);
807 	FM_STATUS_RESET(ST,0);
808 }
809 
810 /* OPN Mode Register Write */
set_timers(FM_ST * ST,int v)811 INLINE void set_timers( FM_ST *ST, int v )
812 {
813 	/* b7 = CSM MODE */
814 	/* b6 = 3 slot mode */
815 	/* b5 = reset b */
816 	/* b4 = reset a */
817 	/* b3 = timer enable b */
818 	/* b2 = timer enable a */
819 	/* b1 = load b */
820 	/* b0 = load a */
821 	ST->mode = v;
822 
823 	/* reset Timer b flag */
824 	if( v & 0x20 )
825 		FM_STATUS_RESET(ST,0x02);
826 	/* reset Timer a flag */
827 	if( v & 0x10 )
828 		FM_STATUS_RESET(ST,0x01);
829 	/* load b */
830 	if( v & 0x02 )
831 	{
832 		if( ST->TBC == 0 )
833 		{
834 			ST->TBC = ( 256-ST->TB)<<4;
835 			/* External timer handler */
836 #if FM_INTERNAL_TIMER==0
837 			(ST->Timer_Handler)(1,ST->TBC,ST->TimerBase);
838 #endif
839 		}
840 	}
841 	else
842 	{	/* stop timer b */
843 		if( ST->TBC != 0 )
844 		{
845 			ST->TBC = 0;
846 #if FM_INTERNAL_TIMER==0
847 			(ST->Timer_Handler)(1,0,ST->TimerBase);
848 #endif
849 		}
850 	}
851 	/* load a */
852 	if( v & 0x01 )
853 	{
854 		if( ST->TAC == 0 )
855 		{
856 			ST->TAC = (1024-ST->TA);
857 			/* External timer handler */
858 #if FM_INTERNAL_TIMER==0
859 			(ST->Timer_Handler)(0,ST->TAC,ST->TimerBase);
860 #endif
861 		}
862 	}
863 	else
864 	{	/* stop timer a */
865 		if( ST->TAC != 0 )
866 		{
867 			ST->TAC = 0;
868 #if FM_INTERNAL_TIMER==0
869 			(ST->Timer_Handler)(0,0,ST->TimerBase);
870 #endif
871 		}
872 	}
873 }
874 
875 
876 /* Timer A Overflow */
TimerAOver(FM_ST * ST)877 INLINE void TimerAOver(FM_ST *ST)
878 {
879 	/* set status (if enabled) */
880 	if(ST->mode & 0x04) FM_STATUS_SET(ST,0x01);
881 	/* clear or reload the counter */
882 	ST->TAC = (1024-ST->TA);
883 #if FM_INTERNAL_TIMER==0
884 	(ST->Timer_Handler)(0,ST->TAC,ST->TimerBase);
885 #endif
886 }
887 /* Timer B Overflow */
TimerBOver(FM_ST * ST)888 INLINE void TimerBOver(FM_ST *ST)
889 {
890 	/* set status (if enabled) */
891 	if(ST->mode & 0x08) FM_STATUS_SET(ST,0x02);
892 	/* clear or reload the counter */
893 	ST->TBC = ( 256-ST->TB)<<4;
894 #if FM_INTERNAL_TIMER==0
895 	(ST->Timer_Handler)(1,ST->TBC,ST->TimerBase);
896 #endif
897 }
898 
899 
900 #if FM_INTERNAL_TIMER
901 /* ----- internal timer mode , update timer */
902 
903 /* ---------- calculate timer A ---------- */
904 #define INTERNAL_TIMER_A(ST,CSM_CH)					\
905 	{													\
906 		if( ST.TAC /*&&  (ST.Timer_Handler==0) */)		\
907 			/*if( (ST.TAC -= (int)(ST.freqbase*4096)) <= 0 )*/	\
908 			if( (ST.TAC -= (int)((1000.0/ST.rate)*4096)) <= 0 )	\
909 			{											\
910 				TimerAOver( &ST );						\
911 				/* CSM mode total level latch and auto key on */	\
912 				if( ST.mode & 0x80 )					\
913 					CSMKeyControll( CSM_CH );			\
914 			}											\
915 	}
916 /* ---------- calculate timer B ---------- */
917 #define INTERNAL_TIMER_B(ST,step)						\
918 	{														\
919 		if( ST.TBC /*&& (ST.Timer_Handler==0) */)				\
920 			/*if( (ST.TBC -= (int)(ST.freqbase*4096*step)) <= 0 )*/	\
921 			if( (ST.TBC -= (int)((1000.0/ST.rate)*4096*step)) <= 0 )	\
922 				TimerBOver( &ST );							\
923 	}
924 #else /* FM_INTERNAL_TIMER */
925 /* external timer mode */
926 #define INTERNAL_TIMER_A(ST,CSM_CH)
927 #define INTERNAL_TIMER_B(ST,step)
928 #endif /* FM_INTERNAL_TIMER */
929 
930 
931 
932 #if FM_BUSY_FLAG_SUPPORT
FM_STATUS_FLAG(FM_ST * ST)933 INLINE u8 FM_STATUS_FLAG(FM_ST *ST)
934 {
935 	if( ST->BusyExpire )
936 	{
937 		if( (ST->BusyExpire - FM_GET_TIME_NOW()) > 0)
938 			return ST->status | 0x80;	/* with busy */
939 		/* expire */
940 		ST->BusyExpire = 0;
941 	}
942 	return ST->status;
943 }
FM_BUSY_SET(FM_ST * ST,int busyclock)944 INLINE void FM_BUSY_SET(FM_ST *ST,int busyclock )
945 {
946 	ST->BusyExpire = FM_GET_TIME_NOW() + (ST->TimerBase * busyclock);
947 }
948 #define FM_BUSY_CLEAR(ST) ((ST)->BusyExpire = 0)
949 #else
950 #define FM_STATUS_FLAG(ST) ((ST)->status)
951 #define FM_BUSY_SET(ST,bclock) {}
952 #define FM_BUSY_CLEAR(ST) {}
953 #endif
954 
955 
956 
957 
FM_KEYON(FM_CH * CH,int s)958 INLINE void FM_KEYON(FM_CH *CH , int s )
959 {
960 	FM_SLOT *SLOT = &CH->SLOT[s];
961 	if( !SLOT->key )
962 	{
963 		SLOT->key = 1;
964 		SLOT->phase = 0;		/* restart Phase Generator */
965 		SLOT->state = EG_ATT;	/* phase -> Attack */
966 	}
967 }
968 
FM_KEYOFF(FM_CH * CH,int s)969 INLINE void FM_KEYOFF(FM_CH *CH , int s )
970 {
971 	FM_SLOT *SLOT = &CH->SLOT[s];
972 	if( SLOT->key )
973 	{
974 		SLOT->key = 0;
975 		if (SLOT->state>EG_REL)
976 			SLOT->state = EG_REL;/* phase -> Release */
977 	}
978 }
979 
980 /* set algorithm connection */
setup_connection(FM_CH * CH,int ch)981 static void setup_connection( FM_CH *CH, int ch )
982 {
983 	s32 *carrier = &out_fm[ch];
984 
985 	s32 **om1 = &CH->connect1;
986 	s32 **om2 = &CH->connect3;
987 	s32 **oc1 = &CH->connect2;
988 
989 	s32 **memc = &CH->mem_connect;
990 
991 	switch( CH->ALGO ){
992 	case 0:
993 		/* M1---C1---MEM---M2---C2---OUT */
994 		*om1 = &c1;
995 		*oc1 = &mem;
996 		*om2 = &c2;
997 		*memc= &m2;
998 		break;
999 	case 1:
1000 		/* M1------+-MEM---M2---C2---OUT */
1001 		/*      C1-+                     */
1002 		*om1 = &mem;
1003 		*oc1 = &mem;
1004 		*om2 = &c2;
1005 		*memc= &m2;
1006 		break;
1007 	case 2:
1008 		/* M1-----------------+-C2---OUT */
1009 		/*      C1---MEM---M2-+          */
1010 		*om1 = &c2;
1011 		*oc1 = &mem;
1012 		*om2 = &c2;
1013 		*memc= &m2;
1014 		break;
1015 	case 3:
1016 		/* M1---C1---MEM------+-C2---OUT */
1017 		/*                 M2-+          */
1018 		*om1 = &c1;
1019 		*oc1 = &mem;
1020 		*om2 = &c2;
1021 		*memc= &c2;
1022 		break;
1023 	case 4:
1024 		/* M1---C1-+-OUT */
1025 		/* M2---C2-+     */
1026 		/* MEM: not used */
1027 		*om1 = &c1;
1028 		*oc1 = carrier;
1029 		*om2 = &c2;
1030 		*memc= &mem;	/* store it anywhere where it will not be used */
1031 		break;
1032 	case 5:
1033 		/*    +----C1----+     */
1034 		/* M1-+-MEM---M2-+-OUT */
1035 		/*    +----C2----+     */
1036 		*om1 = 0;	/* special mark */
1037 		*oc1 = carrier;
1038 		*om2 = carrier;
1039 		*memc= &m2;
1040 		break;
1041 	case 6:
1042 		/* M1---C1-+     */
1043 		/*      M2-+-OUT */
1044 		/*      C2-+     */
1045 		/* MEM: not used */
1046 		*om1 = &c1;
1047 		*oc1 = carrier;
1048 		*om2 = carrier;
1049 		*memc= &mem;	/* store it anywhere where it will not be used */
1050 		break;
1051 	case 7:
1052 		/* M1-+     */
1053 		/* C1-+-OUT */
1054 		/* M2-+     */
1055 		/* C2-+     */
1056 		/* MEM: not used*/
1057 		*om1 = carrier;
1058 		*oc1 = carrier;
1059 		*om2 = carrier;
1060 		*memc= &mem;	/* store it anywhere where it will not be used */
1061 		break;
1062 	}
1063 
1064 	CH->connect4 = carrier;
1065 }
1066 
1067 /* set detune & multiple */
set_det_mul(FM_ST * ST,FM_CH * CH,FM_SLOT * SLOT,int v)1068 INLINE void set_det_mul(FM_ST *ST,FM_CH *CH,FM_SLOT *SLOT,int v)
1069 {
1070 	SLOT->mul = (v&0x0f)? (v&0x0f)*2 : 1;
1071 	SLOT->DT  = ST->dt_tab[(v>>4)&7];
1072 	CH->SLOT[SLOT1].Incr=-1;
1073 }
1074 
1075 /* set total level */
set_tl(FM_CH * CH,FM_SLOT * SLOT,int v)1076 INLINE void set_tl(FM_CH *CH,FM_SLOT *SLOT , int v)
1077 {
1078 	SLOT->tl = (v&0x7f)<<(ENV_BITS-7); /* 7bit TL */
1079 }
1080 
1081 /* set attack rate & key scale  */
set_ar_ksr(FM_CH * CH,FM_SLOT * SLOT,int v)1082 INLINE void set_ar_ksr(FM_CH *CH,FM_SLOT *SLOT,int v)
1083 {
1084 	u8 old_KSR = SLOT->KSR;
1085 
1086 	SLOT->ar = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1087 
1088 	SLOT->KSR = 3-(v>>6);
1089 	if (SLOT->KSR != old_KSR)
1090 	{
1091 		CH->SLOT[SLOT1].Incr=-1;
1092 	}
1093 	else
1094 	{
1095 		/* refresh Attack rate */
1096 		if ((SLOT->ar + SLOT->ksr) < 32+62)
1097 		{
1098 			SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar  + SLOT->ksr ];
1099 			SLOT->eg_sel_ar = eg_rate_select[SLOT->ar  + SLOT->ksr ];
1100 		}
1101 		else
1102 		{
1103 			SLOT->eg_sh_ar  = 0;
1104 			SLOT->eg_sel_ar = 17*RATE_STEPS;
1105 		}
1106 	}
1107 }
1108 
1109 /* set decay rate */
set_dr(FM_SLOT * SLOT,int v)1110 INLINE void set_dr(FM_SLOT *SLOT,int v)
1111 {
1112 	SLOT->d1r = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1113 
1114 	SLOT->eg_sh_d1r = eg_rate_shift [SLOT->d1r + SLOT->ksr];
1115 	SLOT->eg_sel_d1r= eg_rate_select[SLOT->d1r + SLOT->ksr];
1116 
1117 }
1118 
1119 /* set sustain rate */
set_sr(FM_SLOT * SLOT,int v)1120 INLINE void set_sr(FM_SLOT *SLOT,int v)
1121 {
1122 	SLOT->d2r = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1123 
1124 	SLOT->eg_sh_d2r = eg_rate_shift [SLOT->d2r + SLOT->ksr];
1125 	SLOT->eg_sel_d2r= eg_rate_select[SLOT->d2r + SLOT->ksr];
1126 }
1127 
1128 /* set release rate */
set_sl_rr(FM_SLOT * SLOT,int v)1129 INLINE void set_sl_rr(FM_SLOT *SLOT,int v)
1130 {
1131 	SLOT->sl = sl_table[ v>>4 ];
1132 
1133 	SLOT->rr  = 34 + ((v&0x0f)<<2);
1134 
1135 	SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr  + SLOT->ksr];
1136 	SLOT->eg_sel_rr = eg_rate_select[SLOT->rr  + SLOT->ksr];
1137 }
1138 
1139 
1140 
op_calc(u32 phase,unsigned int env,signed int pm)1141 INLINE signed int op_calc(u32 phase, unsigned int env, signed int pm)
1142 {
1143 	u32 p;
1144 
1145 	p = (env<<3) + sin_tab[ ( ((signed int)((phase & ~FREQ_MASK) + (pm<<15))) >> FREQ_SH ) & SIN_MASK ];
1146 
1147 	if (p >= TL_TAB_LEN)
1148 		return 0;
1149 	return tl_tab[p];
1150 }
1151 
op_calc1(u32 phase,unsigned int env,signed int pm)1152 INLINE signed int op_calc1(u32 phase, unsigned int env, signed int pm)
1153 {
1154 	u32 p;
1155 
1156 	p = (env<<3) + sin_tab[ ( ((signed int)((phase & ~FREQ_MASK) + pm      )) >> FREQ_SH ) & SIN_MASK ];
1157 
1158 	if (p >= TL_TAB_LEN)
1159 		return 0;
1160 	return tl_tab[p];
1161 }
1162 
1163 /* advance LFO to next sample */
advance_lfo(FM_OPN * OPN)1164 INLINE void advance_lfo(FM_OPN *OPN)
1165 {
1166 	u8 pos;
1167 	u8 prev_pos;
1168 
1169 	if (OPN->lfo_inc)	/* LFO enabled ? */
1170 	{
1171 		prev_pos = OPN->lfo_cnt>>LFO_SH & 127;
1172 
1173 		OPN->lfo_cnt += OPN->lfo_inc;
1174 
1175 		pos = (OPN->lfo_cnt >> LFO_SH) & 127;
1176 
1177 
1178 		/* update AM when LFO output changes */
1179 
1180 		/*if (prev_pos != pos)*/
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 		prev_pos >>= 2;
1195 		pos >>= 2;
1196 		/* update PM when LFO output changes */
1197 		/*if (prev_pos != pos)*/ /* can't use global lfo_pm for this optimization, must be chip->lfo_pm instead*/
1198 		{
1199 			LFO_PM = pos;
1200 		}
1201 
1202 	}
1203 	else
1204 	{
1205 		LFO_AM = 0;
1206 		LFO_PM = 0;
1207 	}
1208 }
1209 
advance_eg_channel(FM_OPN * OPN,FM_SLOT * SLOT)1210 INLINE void advance_eg_channel(FM_OPN *OPN, FM_SLOT *SLOT)
1211 {
1212 	unsigned int out;
1213 	unsigned int swap_flag = 0;
1214 	unsigned int i;
1215 
1216 
1217 	i = 4; /* four operators per channel */
1218 	do
1219 	{
1220 		switch(SLOT->state)
1221 		{
1222 		case EG_ATT:		/* attack phase */
1223 			if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_ar)-1) ) )
1224 			{
1225 				SLOT->volume += (~SLOT->volume *
1226                                   (eg_inc[SLOT->eg_sel_ar + ((OPN->eg_cnt>>SLOT->eg_sh_ar)&7)])
1227                                 ) >>4;
1228 				if (SLOT->volume <= MIN_ATT_INDEX)
1229 				{
1230 					SLOT->volume = MIN_ATT_INDEX;
1231 					SLOT->state = EG_DEC;
1232 				}
1233 			}
1234 
1235 		break;
1236 
1237 		case EG_DEC:	/* decay phase */
1238 			if (SLOT->ssg&0x08)	/* SSG EG type envelope selected */
1239 			{
1240 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d1r)-1) ) )
1241 				{
1242 					SLOT->volume += (eg_inc[SLOT->eg_sel_d1r + ((OPN->eg_cnt>>SLOT->eg_sh_d1r)&7)]<<2);
1243 
1244 					if ( SLOT->volume >= SLOT->sl )
1245 						SLOT->state = EG_SUS;
1246 				}
1247 			}
1248 			else
1249 			{
1250 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d1r)-1) ) )
1251 				{
1252 					SLOT->volume += eg_inc[SLOT->eg_sel_d1r + ((OPN->eg_cnt>>SLOT->eg_sh_d1r)&7)];
1253 
1254 					if ( SLOT->volume >= SLOT->sl )
1255 						SLOT->state = EG_SUS;
1256 				}
1257 			}
1258 		break;
1259 
1260 		case EG_SUS:	/* sustain phase */
1261 			if (SLOT->ssg&0x08)	/* SSG EG type envelope selected */
1262 			{
1263 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d2r)-1) ) )
1264 				{
1265 					SLOT->volume += (eg_inc[SLOT->eg_sel_d2r + ((OPN->eg_cnt>>SLOT->eg_sh_d2r)&7)]<<2);
1266 
1267 					if ( SLOT->volume >= MAX_ATT_INDEX )
1268 					{
1269 						SLOT->volume = MAX_ATT_INDEX;
1270 
1271 						if (SLOT->ssg&0x01)	/* bit 0 = hold */
1272 						{
1273 							if (SLOT->ssgn&1)	/* have we swapped once ??? */
1274 							{
1275 								/* yes, so do nothing, just hold current level */
1276 							}
1277 							else
1278 								swap_flag = (SLOT->ssg&0x02) | 1 ; /* bit 1 = alternate */
1279 
1280 						}
1281 						else
1282 						{
1283 							/* same as KEY-ON operation */
1284 
1285 							/* restart of the Phase Generator should be here,
1286                                 only if AR is not maximum ??? */
1287 							/*SLOT->phase = 0;*/
1288 
1289 							/* phase -> Attack */
1290 							SLOT->state = EG_ATT;
1291 
1292 							swap_flag = (SLOT->ssg&0x02); /* bit 1 = alternate */
1293 						}
1294 					}
1295 				}
1296 			}
1297 			else
1298 			{
1299 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d2r)-1) ) )
1300 				{
1301 					SLOT->volume += eg_inc[SLOT->eg_sel_d2r + ((OPN->eg_cnt>>SLOT->eg_sh_d2r)&7)];
1302 
1303 					if ( SLOT->volume >= MAX_ATT_INDEX )
1304 					{
1305 						SLOT->volume = MAX_ATT_INDEX;
1306 						/* do not change SLOT->state (verified on real chip) */
1307 					}
1308 				}
1309 
1310 			}
1311 		break;
1312 
1313 		case EG_REL:	/* release phase */
1314 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_rr)-1) ) )
1315 				{
1316 					SLOT->volume += eg_inc[SLOT->eg_sel_rr + ((OPN->eg_cnt>>SLOT->eg_sh_rr)&7)];
1317 
1318 					if ( SLOT->volume >= MAX_ATT_INDEX )
1319 					{
1320 						SLOT->volume = MAX_ATT_INDEX;
1321 						SLOT->state = EG_OFF;
1322 					}
1323 				}
1324 		break;
1325 
1326 		}
1327 
1328 		out = SLOT->tl + ((u32)SLOT->volume);
1329 
1330 		if ((SLOT->ssg&0x08) && (SLOT->ssgn&2))	/* negate output (changes come from alternate bit, init comes from attack bit) */
1331 			out ^= ((1<<ENV_BITS)-1); /* 1023 */
1332 
1333 		/* we need to store the result here because we are going to change ssgn
1334             in next instruction */
1335 		SLOT->vol_out = out;
1336 
1337 		SLOT->ssgn ^= swap_flag;
1338 
1339 		SLOT++;
1340 		i--;
1341 	}while (i);
1342 
1343 }
1344 
1345 
1346 
1347 #define volume_calc(OP) ((OP)->vol_out + (AM & (OP)->AMmask))
1348 
chan_calc(FM_OPN * OPN,FM_CH * CH)1349 INLINE void chan_calc(FM_OPN *OPN, FM_CH *CH)
1350 {
1351 	unsigned int eg_out;
1352 
1353 	u32 AM = LFO_AM >> CH->ams;
1354 
1355 
1356 	m2 = c1 = c2 = mem = 0;
1357 
1358 	*CH->mem_connect = CH->mem_value;	/* restore delayed sample (MEM) value to m2 or c2 */
1359 
1360 	eg_out = volume_calc(&CH->SLOT[SLOT1]);
1361 	{
1362 		s32 out = CH->op1_out[0] + CH->op1_out[1];
1363 		CH->op1_out[0] = CH->op1_out[1];
1364 
1365 		if( !CH->connect1 ){
1366 			/* algorithm 5  */
1367 			mem = c1 = c2 = CH->op1_out[0];
1368 		}else{
1369 			/* other algorithms */
1370 			*CH->connect1 += CH->op1_out[0];
1371 		}
1372 
1373 		CH->op1_out[1] = 0;
1374 		if( eg_out < ENV_QUIET )	/* SLOT 1 */
1375 		{
1376 			if (!CH->FB)
1377 				out=0;
1378 
1379 			CH->op1_out[1] = op_calc1(CH->SLOT[SLOT1].phase, eg_out, (out<<CH->FB) );
1380 		}
1381 	}
1382 
1383 	eg_out = volume_calc(&CH->SLOT[SLOT3]);
1384 	if( eg_out < ENV_QUIET )		/* SLOT 3 */
1385 		*CH->connect3 += op_calc(CH->SLOT[SLOT3].phase, eg_out, m2);
1386 
1387 	eg_out = volume_calc(&CH->SLOT[SLOT2]);
1388 	if( eg_out < ENV_QUIET )		/* SLOT 2 */
1389 		*CH->connect2 += op_calc(CH->SLOT[SLOT2].phase, eg_out, c1);
1390 
1391 	eg_out = volume_calc(&CH->SLOT[SLOT4]);
1392 	if( eg_out < ENV_QUIET )		/* SLOT 4 */
1393 		*CH->connect4 += op_calc(CH->SLOT[SLOT4].phase, eg_out, c2);
1394 
1395 
1396 	/* store current MEM */
1397 	CH->mem_value = mem;
1398 
1399 	/* update phase counters AFTER output calculations */
1400 	if(CH->pms)
1401 	{
1402 
1403 
1404 	/* add support for 3 slot mode */
1405 
1406 
1407 		u32 block_fnum = CH->block_fnum;
1408 
1409 		u32 fnum_lfo   = ((block_fnum & 0x7f0) >> 4) * 32 * 8;
1410 		s32  lfo_fn_table_index_offset = lfo_pm_table[ fnum_lfo + CH->pms + LFO_PM ];
1411 
1412 		if (lfo_fn_table_index_offset)	/* LFO phase modulation active */
1413 		{
1414 			u8  blk;
1415 			u32 fn;
1416 			int kc,fc;
1417 
1418 			block_fnum = block_fnum*2 + lfo_fn_table_index_offset;
1419 
1420 			blk = (block_fnum&0x7000) >> 12;
1421 			fn  = block_fnum & 0xfff;
1422 
1423 			/* keyscale code */
1424 			kc = (blk<<2) | opn_fktable[fn >> 8];
1425  			/* phase increment counter */
1426 			fc = OPN->fn_table[fn]>>(7-blk);
1427 
1428 			CH->SLOT[SLOT1].phase += ((fc+CH->SLOT[SLOT1].DT[kc])*CH->SLOT[SLOT1].mul) >> 1;
1429 			CH->SLOT[SLOT2].phase += ((fc+CH->SLOT[SLOT2].DT[kc])*CH->SLOT[SLOT2].mul) >> 1;
1430 			CH->SLOT[SLOT3].phase += ((fc+CH->SLOT[SLOT3].DT[kc])*CH->SLOT[SLOT3].mul) >> 1;
1431 			CH->SLOT[SLOT4].phase += ((fc+CH->SLOT[SLOT4].DT[kc])*CH->SLOT[SLOT4].mul) >> 1;
1432 		}
1433 		else	/* LFO phase modulation  = zero */
1434 		{
1435 			CH->SLOT[SLOT1].phase += CH->SLOT[SLOT1].Incr;
1436 			CH->SLOT[SLOT2].phase += CH->SLOT[SLOT2].Incr;
1437 			CH->SLOT[SLOT3].phase += CH->SLOT[SLOT3].Incr;
1438 			CH->SLOT[SLOT4].phase += CH->SLOT[SLOT4].Incr;
1439 		}
1440 	}
1441 	else	/* no LFO phase modulation */
1442 	{
1443 		CH->SLOT[SLOT1].phase += CH->SLOT[SLOT1].Incr;
1444 		CH->SLOT[SLOT2].phase += CH->SLOT[SLOT2].Incr;
1445 		CH->SLOT[SLOT3].phase += CH->SLOT[SLOT3].Incr;
1446 		CH->SLOT[SLOT4].phase += CH->SLOT[SLOT4].Incr;
1447 	}
1448 }
1449 
1450 /* update phase increment and envelope generator */
refresh_fc_eg_slot(FM_SLOT * SLOT,int fc,int kc)1451 INLINE void refresh_fc_eg_slot(FM_SLOT *SLOT , int fc , int kc )
1452 {
1453 	int ksr;
1454 
1455 	/* (frequency) phase increment counter */
1456 	SLOT->Incr = ((fc+SLOT->DT[kc])*SLOT->mul) >> 1;
1457 
1458 	ksr = kc >> SLOT->KSR;
1459 	if( SLOT->ksr != ksr )
1460 	{
1461 		SLOT->ksr = ksr;
1462 
1463 		/* calculate envelope generator rates */
1464 		if ((SLOT->ar + SLOT->ksr) < 32+62)
1465 		{
1466 			SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar  + SLOT->ksr ];
1467 			SLOT->eg_sel_ar = eg_rate_select[SLOT->ar  + SLOT->ksr ];
1468 		}
1469 		else
1470 		{
1471 			SLOT->eg_sh_ar  = 0;
1472 			SLOT->eg_sel_ar = 17*RATE_STEPS;
1473 		}
1474 
1475 		SLOT->eg_sh_d1r = eg_rate_shift [SLOT->d1r + SLOT->ksr];
1476 		SLOT->eg_sel_d1r= eg_rate_select[SLOT->d1r + SLOT->ksr];
1477 
1478 		SLOT->eg_sh_d2r = eg_rate_shift [SLOT->d2r + SLOT->ksr];
1479 		SLOT->eg_sel_d2r= eg_rate_select[SLOT->d2r + SLOT->ksr];
1480 
1481 		SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr  + SLOT->ksr];
1482 		SLOT->eg_sel_rr = eg_rate_select[SLOT->rr  + SLOT->ksr];
1483 	}
1484 }
1485 
1486 /* update phase increment counters */
refresh_fc_eg_chan(FM_CH * CH)1487 INLINE void refresh_fc_eg_chan(FM_CH *CH )
1488 {
1489 	if( CH->SLOT[SLOT1].Incr==-1){
1490 		int fc = CH->fc;
1491 		int kc = CH->kcode;
1492 		refresh_fc_eg_slot(&CH->SLOT[SLOT1] , fc , kc );
1493 		refresh_fc_eg_slot(&CH->SLOT[SLOT2] , fc , kc );
1494 		refresh_fc_eg_slot(&CH->SLOT[SLOT3] , fc , kc );
1495 		refresh_fc_eg_slot(&CH->SLOT[SLOT4] , fc , kc );
1496 	}
1497 }
1498 
1499 /* initialize time tables */
init_timetables(FM_ST * ST,const u8 * dttable)1500 static void init_timetables( FM_ST *ST , const u8 *dttable )
1501 {
1502 	int i,d;
1503 	double rate;
1504 
1505 #if 0
1506 	logerror("FM.C: samplerate=%8i chip clock=%8i  freqbase=%f  \n",
1507 			 ST->rate, ST->clock, ST->freqbase );
1508 #endif
1509 
1510 	/* DeTune table */
1511 	for (d = 0;d <= 3;d++){
1512 		for (i = 0;i <= 31;i++){
1513 			rate = ((double)dttable[d*32 + i]) * SIN_LEN  * ST->freqbase  * (1<<FREQ_SH) / ((double)(1<<20));
1514 			ST->dt_tab[d][i]   = (s32) rate;
1515 			ST->dt_tab[d+4][i] = -ST->dt_tab[d][i];
1516 #if 0
1517 			logerror("FM.C: DT [%2i %2i] = %8x  \n", d, i, ST->dt_tab[d][i] );
1518 #endif
1519 		}
1520 	}
1521 
1522 }
1523 
1524 
reset_channels(FM_ST * ST,FM_CH * CH,int num)1525 static void reset_channels( FM_ST *ST , FM_CH *CH , int num )
1526 {
1527 	int c,s;
1528 
1529 	ST->mode   = 0;	/* normal mode */
1530 	ST->TA     = 0;
1531 	ST->TAC    = 0;
1532 	ST->TB     = 0;
1533 	ST->TBC    = 0;
1534 
1535 	for( c = 0 ; c < num ; c++ )
1536 	{
1537 		CH[c].fc = 0;
1538 		for(s = 0 ; s < 4 ; s++ )
1539 		{
1540 			CH[c].SLOT[s].ssg = 0;
1541 			CH[c].SLOT[s].ssgn = 0;
1542 			CH[c].SLOT[s].state= EG_OFF;
1543 			CH[c].SLOT[s].volume = MAX_ATT_INDEX;
1544 			CH[c].SLOT[s].vol_out= MAX_ATT_INDEX;
1545 		}
1546 	}
1547 }
1548 
1549 /* initialize generic tables */
OPNInitTable(void)1550 static void OPNInitTable(void)
1551 {
1552 	signed int i,x;
1553 	signed int n;
1554 	double o,m;
1555 
1556 	for (x=0; x<TL_RES_LEN; x++)
1557 	{
1558 		m = (1<<16) / pow(2, (x+1) * (ENV_STEP/4.0) / 8.0);
1559 		m = floor(m);
1560 
1561 		/* we never reach (1<<16) here due to the (x+1) */
1562 		/* result fits within 16 bits at maximum */
1563 
1564 		n = (int)m;		/* 16 bits here */
1565 		n >>= 4;		/* 12 bits here */
1566 		if (n&1)		/* round to nearest */
1567 			n = (n>>1)+1;
1568 		else
1569 			n = n>>1;
1570 						/* 11 bits here (rounded) */
1571 		n <<= 2;		/* 13 bits here (as in real chip) */
1572 		tl_tab[ x*2 + 0 ] = n;
1573 		tl_tab[ x*2 + 1 ] = -tl_tab[ x*2 + 0 ];
1574 
1575 		for (i=1; i<13; i++)
1576 		{
1577 			tl_tab[ x*2+0 + i*2*TL_RES_LEN ] =  tl_tab[ x*2+0 ]>>i;
1578 			tl_tab[ x*2+1 + i*2*TL_RES_LEN ] = -tl_tab[ x*2+0 + i*2*TL_RES_LEN ];
1579 		}
1580 	#if 0
1581 			logerror("tl %04i", x);
1582 			for (i=0; i<13; i++)
1583 				logerror(", [%02i] %4x", i*2, tl_tab[ x*2 /*+1*/ + i*2*TL_RES_LEN ]);
1584 			logerror("\n");
1585 		}
1586 	#endif
1587 	}
1588 	/*logerror("FM.C: TL_TAB_LEN = %i elements (%i bytes)\n",TL_TAB_LEN, (int)sizeof(tl_tab));*/
1589 
1590 
1591 	for (i=0; i<SIN_LEN; i++)
1592 	{
1593 		/* non-standard sinus */
1594 		m = sin( ((i*2)+1) * M_PI / SIN_LEN ); /* checked against the real chip */
1595 
1596 		/* we never reach zero here due to ((i*2)+1) */
1597 
1598 		if (m>0.0)
1599 			o = 8*log(1.0/m)/log(2);	/* convert to 'decibels' */
1600 		else
1601 			o = 8*log(-1.0/m)/log(2);	/* convert to 'decibels' */
1602 
1603 		o = o / (ENV_STEP/4);
1604 
1605 		n = (int)(2.0*o);
1606 		if (n&1)						/* round to nearest */
1607 			n = (n>>1)+1;
1608 		else
1609 			n = n>>1;
1610 
1611 		sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
1612 		/*logerror("FM.C: sin [%4i]= %4i (tl_tab value=%5i)\n", i, sin_tab[i],tl_tab[sin_tab[i]]);*/
1613 	}
1614 
1615 	/*logerror("FM.C: ENV_QUIET= %08x\n",ENV_QUIET );*/
1616 
1617 
1618 	/* build LFO PM modulation table */
1619 	for(i = 0; i < 8; i++) /* 8 PM depths */
1620 	{
1621 		u8 fnum;
1622 		for (fnum=0; fnum<128; fnum++) /* 7 bits meaningful of F-NUMBER */
1623 		{
1624 			u8 value;
1625 			u8 step;
1626 			u32 offset_depth = i;
1627 			u32 offset_fnum_bit;
1628 			u32 bit_tmp;
1629 
1630 			for (step=0; step<8; step++)
1631 			{
1632 				value = 0;
1633 				for (bit_tmp=0; bit_tmp<7; bit_tmp++) /* 7 bits */
1634 				{
1635 					if (fnum & (1<<bit_tmp)) /* only if bit "bit_tmp" is set */
1636 					{
1637 						offset_fnum_bit = bit_tmp * 8;
1638 						value += lfo_pm_output[offset_fnum_bit + offset_depth][step];
1639 					}
1640 				}
1641 				lfo_pm_table[(fnum*32*8) + (i*32) + step   + 0] = value;
1642 				lfo_pm_table[(fnum*32*8) + (i*32) +(step^7)+ 8] = value;
1643 				lfo_pm_table[(fnum*32*8) + (i*32) + step   +16] = -value;
1644 				lfo_pm_table[(fnum*32*8) + (i*32) +(step^7)+24] = -value;
1645 			}
1646 #if 0
1647 			logerror("LFO depth=%1x FNUM=%04x (<<4=%4x): ", i, fnum, fnum<<4);
1648 			for (step=0; step<16; step++) /* dump only positive part of waveforms */
1649 				logerror("%02x ", lfo_pm_table[(fnum*32*8) + (i*32) + step] );
1650 			logerror("\n");
1651 #endif
1652 
1653 		}
1654 	}
1655 }
1656 
1657 
1658 
1659 /* CSM Key Controll */
CSMKeyControll(FM_CH * CH)1660 INLINE void CSMKeyControll(FM_CH *CH)
1661 {
1662 	/* this is wrong, atm */
1663 
1664 	/* all key on */
1665 	FM_KEYON(CH,SLOT1);
1666 	FM_KEYON(CH,SLOT2);
1667 	FM_KEYON(CH,SLOT3);
1668 	FM_KEYON(CH,SLOT4);
1669 }
1670 
1671 
1672 
1673 
1674 /* prescaler set (and make time tables) */
OPNSetPres(FM_OPN * OPN,int pres,int TimerPres,int SSGpres)1675 static void OPNSetPres(FM_OPN *OPN , int pres , int TimerPres, int SSGpres)
1676 {
1677 	int i;
1678 
1679 	/* frequency base */
1680 	OPN->ST.freqbase = (OPN->ST.rate) ? ((double)OPN->ST.clock / OPN->ST.rate) / pres : 0;
1681 
1682 #if 0
1683 	OPN->ST.rate = (double)OPN->ST.clock / pres;
1684 	OPN->ST.freqbase = 1.0;
1685 #endif
1686 
1687 	OPN->eg_timer_add  = (1<<EG_SH)  *  OPN->ST.freqbase;
1688 	OPN->eg_timer_overflow = ( 3 ) * (1<<EG_SH);
1689 
1690 
1691 	/* Timer base time */
1692 	OPN->ST.TimerBase = 1.0/((double)OPN->ST.clock / (double)TimerPres);
1693 
1694 	/* SSG part  prescaler set */
1695 	if (SSGpres) SSG.step = ((double)SSG_STEP * OPN->ST.rate * 8) / (OPN->ST.clock * 2 / SSGpres);
1696 
1697 	/* make time tables */
1698 	init_timetables( &OPN->ST, dt_tab );
1699 
1700 	/* there are 2048 FNUMs that can be generated using FNUM/BLK registers
1701         but LFO works with one more bit of a precision so we really need 4096 elements */
1702 	/* calculate fnumber -> increment counter table */
1703 	for(i = 0; i < 4096; i++)
1704 	{
1705 		/* freq table for octave 7 */
1706 		/* OPN phase increment counter = 20bit */
1707 		OPN->fn_table[i] = (u32)( (double)i * 32 * OPN->ST.freqbase * (1<<(FREQ_SH-10)) ); /* -10 because chip works with 10.10 fixed point, while we use 16.16 */
1708 #if 0
1709 		logerror("FM.C: fn_table[%4i] = %08x (dec=%8i)\n",
1710 				 i, OPN->fn_table[i]>>6,OPN->fn_table[i]>>6 );
1711 #endif
1712 	}
1713 
1714 	/* LFO freq. table */
1715 	for(i = 0; i < 8; i++)
1716 	{
1717 		/* Amplitude modulation: 64 output levels (triangle waveform); 1 level lasts for one of "lfo_samples_per_step" samples */
1718 		/* Phase modulation: one entry from lfo_pm_output lasts for one of 4 * "lfo_samples_per_step" samples  */
1719 		OPN->lfo_freq[i] = (1.0 / lfo_samples_per_step[i]) * (1<<LFO_SH) * OPN->ST.freqbase;
1720 #if 0
1721 		logerror("FM.C: lfo_freq[%i] = %08x (dec=%8i)\n",
1722 				 i, OPN->lfo_freq[i],OPN->lfo_freq[i] );
1723 #endif
1724 	}
1725 }
1726 
1727 
1728 
1729 /* write a OPN mode register 0x20-0x2f */
OPNWriteMode(FM_OPN * OPN,int r,int v)1730 static void OPNWriteMode(FM_OPN *OPN, int r, int v)
1731 {
1732 	u8 c;
1733 	FM_CH *CH;
1734 
1735 	switch(r){
1736 	case 0x21:	/* Test */
1737 		break;
1738 	case 0x22:	/* LFO FREQ (YM2608/YM2610/YM2610B/YM2612) */
1739 		if (v&0x08) /* LFO enabled ? */
1740 		{
1741 			OPN->lfo_inc = OPN->lfo_freq[v&7];
1742 		}
1743 		else
1744 		{
1745 			OPN->lfo_inc = 0;
1746 		}
1747 		break;
1748 	case 0x24:	/* timer A High 8*/
1749 		OPN->ST.TA = (OPN->ST.TA & 0x03)|(((int)v)<<2);
1750 		break;
1751 	case 0x25:	/* timer A Low 2*/
1752 		OPN->ST.TA = (OPN->ST.TA & 0x3fc)|(v&3);
1753 		break;
1754 	case 0x26:	/* timer B */
1755 		OPN->ST.TB = v;
1756 		break;
1757 	case 0x27:	/* mode, timer control */
1758 		set_timers( &(OPN->ST),v );
1759 		break;
1760 	case 0x28:	/* key on / off */
1761 		c = v & 0x03;
1762 		if( c == 3 ) break;
1763 		if( v&0x04 ) c+=3;
1764 		CH = OPN->P_CH;
1765 		CH = &CH[c];
1766 		if(v&0x10) FM_KEYON(CH,SLOT1); else FM_KEYOFF(CH,SLOT1);
1767 		if(v&0x20) FM_KEYON(CH,SLOT2); else FM_KEYOFF(CH,SLOT2);
1768 		if(v&0x40) FM_KEYON(CH,SLOT3); else FM_KEYOFF(CH,SLOT3);
1769 		if(v&0x80) FM_KEYON(CH,SLOT4); else FM_KEYOFF(CH,SLOT4);
1770 		break;
1771 	}
1772 }
1773 
1774 /* write a OPN register (0x30-0xff) */
OPNWriteReg(FM_OPN * OPN,int r,int v)1775 static void OPNWriteReg(FM_OPN *OPN, int r, int v)
1776 {
1777 	FM_CH *CH;
1778 	FM_SLOT *SLOT;
1779 
1780 	u8 c = OPN_CHAN(r);
1781 
1782 	if (c == 3) return; /* 0xX3,0xX7,0xXB,0xXF */
1783 
1784 	if (r >= 0x100) c+=3;
1785 
1786 	CH = OPN->P_CH;
1787 	CH = &CH[c];
1788 
1789 	SLOT = &(CH->SLOT[OPN_SLOT(r)]);
1790 
1791 	switch( r & 0xf0 ) {
1792 	case 0x30:	/* DET , MUL */
1793 		set_det_mul(&OPN->ST,CH,SLOT,v);
1794 		break;
1795 
1796 	case 0x40:	/* TL */
1797 		set_tl(CH,SLOT,v);
1798 		break;
1799 
1800 	case 0x50:	/* KS, AR */
1801 		set_ar_ksr(CH,SLOT,v);
1802 		break;
1803 
1804 	case 0x60:	/* bit7 = AM ENABLE, DR */
1805 		set_dr(SLOT,v);
1806 		SLOT->AMmask = (v&0x80) ? ~0 : 0;
1807 		break;
1808 
1809 	case 0x70:	/*     SR */
1810 		set_sr(SLOT,v);
1811 		break;
1812 
1813 	case 0x80:	/* SL, RR */
1814 		set_sl_rr(SLOT,v);
1815 		break;
1816 
1817 	case 0x90:	/* SSG-EG */
1818 
1819 		SLOT->ssg  =  v&0x0f;
1820 		SLOT->ssgn = (v&0x04)>>1; /* bit 1 in ssgn = attack */
1821 
1822 		/* SSG-EG envelope shapes :
1823 
1824         E AtAlH
1825         1 0 0 0  \\\\
1826 
1827         1 0 0 1  \___
1828 
1829         1 0 1 0  \/\/
1830                   ___
1831         1 0 1 1  \
1832 
1833         1 1 0 0  ////
1834                   ___
1835         1 1 0 1  /
1836 
1837         1 1 1 0  /\/\
1838 
1839         1 1 1 1  /___
1840 
1841 
1842         E = SSG-EG enable
1843 
1844 
1845         The shapes are generated using Attack, Decay and Sustain phases.
1846 
1847         Each single character in the diagrams above represents this whole
1848         sequence:
1849 
1850         - when KEY-ON = 1, normal Attack phase is generated (*without* any
1851           difference when compared to normal mode),
1852 
1853         - later, when envelope level reaches minimum level (max volume),
1854           the EG switches to Decay phase (which works with bigger steps
1855           when compared to normal mode - see below),
1856 
1857         - later when envelope level passes the SL level,
1858           the EG swithes to Sustain phase (which works with bigger steps
1859           when compared to normal mode - see below),
1860 
1861         - finally when envelope level reaches maximum level (min volume),
1862           the EG switches to Attack phase again (depends on actual waveform).
1863 
1864         Important is that when switch to Attack phase occurs, the phase counter
1865         of that operator will be zeroed-out (as in normal KEY-ON) but not always.
1866         (I havent found the rule for that - perhaps only when the output level is low)
1867 
1868         The difference (when compared to normal Envelope Generator mode) is
1869         that the resolution in Decay and Sustain phases is 4 times lower;
1870         this results in only 256 steps instead of normal 1024.
1871         In other words:
1872         when SSG-EG is disabled, the step inside of the EG is one,
1873         when SSG-EG is enabled, the step is four (in Decay and Sustain phases).
1874 
1875         Times between the level changes are the same in both modes.
1876 
1877 
1878         Important:
1879         Decay 1 Level (so called SL) is compared to actual SSG-EG output, so
1880         it is the same in both SSG and no-SSG modes, with this exception:
1881 
1882         when the SSG-EG is enabled and is generating raising levels
1883         (when the EG output is inverted) the SL will be found at wrong level !!!
1884         For example, when SL=02:
1885             0 -6 = -6dB in non-inverted EG output
1886             96-6 = -90dB in inverted EG output
1887         Which means that EG compares its level to SL as usual, and that the
1888         output is simply inverted afterall.
1889 
1890 
1891         The Yamaha's manuals say that AR should be set to 0x1f (max speed).
1892         That is not necessary, but then EG will be generating Attack phase.
1893 
1894         */
1895 
1896 
1897 		break;
1898 
1899 	case 0xa0:
1900 		switch( OPN_SLOT(r) ){
1901 		case 0:		/* 0xa0-0xa2 : FNUM1 */
1902 			{
1903 				u32 fn = (((u32)( (OPN->ST.fn_h)&7))<<8) + v;
1904 				u8 blk = OPN->ST.fn_h>>3;
1905 				/* keyscale code */
1906 				CH->kcode = (blk<<2) | opn_fktable[fn >> 7];
1907 				/* phase increment counter */
1908 				CH->fc = OPN->fn_table[fn*2]>>(7-blk);
1909 
1910 				/* store fnum in clear form for LFO PM calculations */
1911 				CH->block_fnum = (blk<<11) | fn;
1912 
1913 				CH->SLOT[SLOT1].Incr=-1;
1914 			}
1915 			break;
1916 		case 1:		/* 0xa4-0xa6 : FNUM2,BLK */
1917 			OPN->ST.fn_h = v&0x3f;
1918 			break;
1919 		case 2:		/* 0xa8-0xaa : 3CH FNUM1 */
1920 			if(r < 0x100)
1921 			{
1922 				u32 fn = (((u32)(OPN->SL3.fn_h&7))<<8) + v;
1923 				u8 blk = OPN->SL3.fn_h>>3;
1924 				/* keyscale code */
1925 				OPN->SL3.kcode[c]= (blk<<2) | opn_fktable[fn >> 7];
1926 				/* phase increment counter */
1927 				OPN->SL3.fc[c] = OPN->fn_table[fn*2]>>(7-blk);
1928 				OPN->SL3.block_fnum[c] = fn;
1929 				(OPN->P_CH)[2].SLOT[SLOT1].Incr=-1;
1930 			}
1931 			break;
1932 		case 3:		/* 0xac-0xae : 3CH FNUM2,BLK */
1933 			if(r < 0x100)
1934 				OPN->SL3.fn_h = v&0x3f;
1935 			break;
1936 		}
1937 		break;
1938 
1939 	case 0xb0:
1940 		switch( OPN_SLOT(r) ){
1941 		case 0:		/* 0xb0-0xb2 : FB,ALGO */
1942 			{
1943 				int feedback = (v>>3)&7;
1944 				CH->ALGO = v&7;
1945 				CH->FB   = feedback ? feedback+6 : 0;
1946 				setup_connection( CH, c );
1947 			}
1948 			break;
1949 		case 1:		/* 0xb4-0xb6 : L , R , AMS , PMS (YM2612/YM2610B/YM2610/YM2608) */
1950 			{
1951 				/* b0-2 PMS */
1952 				CH->pms = (v & 7) * 32; /* CH->pms = PM depth * 32 (index in lfo_pm_table) */
1953 
1954 				/* b4-5 AMS */
1955 				CH->ams = lfo_ams_depth_shift[(v>>4) & 0x03];
1956 
1957 				/* PAN :  b7 = L, b6 = R */
1958 				OPN->pan[ c*2   ] = (v & 0x80) ? ~0 : 0;
1959 				OPN->pan[ c*2+1 ] = (v & 0x40) ? ~0 : 0;
1960 
1961 			}
1962 			break;
1963 		}
1964 		break;
1965 	}
1966 }
1967 
1968 
1969 
1970 /*********************************************************************************************/
1971 
1972 /* SSG */
1973 
SSGWriteReg(int r,int v)1974 static void SSGWriteReg(int r, int v)
1975 {
1976 	int old;
1977 
1978 	YM2610.regs[r] = v;
1979 
1980 	switch (r)
1981 	{
1982 	case 0x00: case 0x02: case 0x04: /* Channel A/B/C Fine Tune */
1983 	case 0x01: case 0x03: case 0x05: /* Channel A/B/C Coarse */
1984 		{
1985 			int ch = r >> 1;
1986 
1987 			r &= ~1;
1988 			YM2610.regs[r + 1] &= 0x0f;
1989 			old = SSG.period[ch];
1990 			SSG.period[ch] = (YM2610.regs[r] + 256 * YM2610.regs[r + 1]) * SSG.step;
1991 			if (SSG.period[ch] == 0) SSG.period[ch] = SSG.step;
1992 			SSG.count[ch] += SSG.period[ch] - old;
1993 			if (SSG.count[ch] <= 0) SSG.count[ch] = 1;
1994 		}
1995 		break;
1996 
1997 	case 0x06:	/* Noise percent */
1998 		YM2610.regs[SSG_NOISEPER] &= 0x1f;
1999 		old = SSG.PeriodN;
2000 		SSG.PeriodN = YM2610.regs[SSG_NOISEPER] * SSG.step;
2001 		if (SSG.PeriodN == 0) SSG.PeriodN = SSG.step;
2002 		SSG.CountN += SSG.PeriodN - old;
2003 		if (SSG.CountN <= 0) SSG.CountN = 1;
2004 		break;
2005 
2006 	case 0x07:	/* Enable */
2007 		SSG.lastEnable = YM2610.regs[SSG_ENABLE];
2008 		break;
2009 
2010 	case 0x08: case 0x09: case 0x0a: /* Channel A/B/C Volume */
2011 		{
2012 			int ch = r & 3;
2013 
2014 			YM2610.regs[r] &= 0x1f;
2015 			SSG.envelope[ch] = YM2610.regs[r] & 0x10;
2016 			SSG.vol[ch] = SSG.envelope[ch] ? SSG.VolE : SSG.vol_table[YM2610.regs[r] ? YM2610.regs[r] * 2 + 1 : 0];
2017 		}
2018 		break;
2019 
2020 	case SSG_EFINE:		// Envelope Fine
2021 	case SSG_ECOARSE:	// Envelope Coarse
2022 		old = SSG.PeriodE;
2023 		SSG.PeriodE = (YM2610.regs[SSG_EFINE] + 256 * YM2610.regs[SSG_ECOARSE]) * SSG.step;
2024 		if (SSG.PeriodE == 0) SSG.PeriodE = SSG.step / 2;
2025 		SSG.CountE += SSG.PeriodE - old;
2026 		if (SSG.CountE <= 0) SSG.CountE = 1;
2027 		break;
2028 
2029 	case SSG_ESHAPE:	// Envelope Shapes
2030 		YM2610.regs[SSG_ESHAPE] &= 0x0f;
2031 		SSG.attack = (YM2610.regs[SSG_ESHAPE] & 0x04) ? 0x1f : 0x00;
2032 		if ((YM2610.regs[SSG_ESHAPE] & 0x08) == 0)
2033 		{
2034 			/* if Continue = 0, map the shape to the equivalent one which has Continue = 1 */
2035 			SSG.hold = 1;
2036 			SSG.alternate = SSG.attack;
2037 		}
2038 		else
2039 		{
2040 			SSG.hold = YM2610.regs[SSG_ESHAPE] & 0x01;
2041 			SSG.alternate = YM2610.regs[SSG_ESHAPE] & 0x02;
2042 		}
2043 		SSG.CountE = SSG.PeriodE;
2044 		SSG.count_env = 0x1f;
2045 		SSG.holding = 0;
2046 		SSG.VolE = SSG.vol_table[SSG.count_env ^ SSG.attack];
2047 		if (SSG.envelope[0]) SSG.vol[0] = SSG.VolE;
2048 		if (SSG.envelope[1]) SSG.vol[1] = SSG.VolE;
2049 		if (SSG.envelope[2]) SSG.vol[2] = SSG.VolE;
2050 		break;
2051 
2052 	case SSG_PORTA:	// Port A
2053 	case SSG_PORTB:	// Port B
2054 		break;
2055 	}
2056 }
2057 
SSG_calc_count(int length)2058 static int SSG_calc_count(int length)
2059 {
2060 	int i;
2061 
2062 	/* calc SSG count */
2063 	for (i = 0; i < 3; i++)
2064 	{
2065 		if (YM2610.regs[SSG_ENABLE] & (0x01 << i))
2066 		{
2067 			if (SSG.count[i] <= length * SSG_STEP)
2068 				SSG.count[i] += length * SSG_STEP;
2069 			SSG.output[i] = 1;
2070 		}
2071 		else if (YM2610.regs[0x08 + i] == 0)
2072 		{
2073 			if (SSG.count[i] <= length * SSG_STEP)
2074 				SSG.count[i] += length * SSG_STEP;
2075 		}
2076 	}
2077 
2078 	/* for the noise channel we must not touch OutputN - it's also not necessary */
2079 	/* since we use outn. */
2080 	if ((YM2610.regs[SSG_ENABLE] & 0x38) == 0x38)	/* all off */
2081 	{
2082 		if (SSG.CountN <= length * SSG_STEP)
2083 			SSG.CountN += length * SSG_STEP;
2084 	}
2085 
2086 	return (SSG.OutputN | YM2610.regs[SSG_ENABLE]);
2087 }
2088 
SSG_CALC(int outn)2089 static int SSG_CALC(int outn)
2090 {
2091 	int ch;
2092 	int vol[3];
2093 	int left;
2094 
2095 	/* vola, volb and volc keep track of how long each square wave stays */
2096 	/* in the 1 position during the sample period. */
2097 	vol[0] = vol[1] = vol[2] = 0;
2098 
2099 	left = SSG_STEP;
2100 
2101 	do
2102 	{
2103 		int nextevent;
2104 
2105 		nextevent = (SSG.CountN < left) ? SSG.CountN : left;
2106 
2107 		for (ch = 0; ch < 3; ch++)
2108 		{
2109 			if (outn & (0x08 << ch))
2110 			{
2111 				if (SSG.output[ch]) vol[ch] += SSG.count[ch];
2112 				SSG.count[ch] -= nextevent;
2113 
2114 				while (SSG.count[ch] <= 0)
2115 				{
2116 					SSG.count[ch] += SSG.period[ch];
2117 					if (SSG.count[ch] > 0)
2118 					{
2119 						SSG.output[ch] ^= 1;
2120 						if (SSG.output[ch]) vol[ch] += SSG.period[ch];
2121 						break;
2122 					}
2123 					SSG.count[ch] += SSG.period[ch];
2124 					vol[ch] += SSG.period[ch];
2125 				}
2126 				if (SSG.output[ch]) vol[ch] -= SSG.count[ch];
2127 			}
2128 			else
2129 			{
2130 				SSG.count[ch] -= nextevent;
2131 				while (SSG.count[ch] <= 0)
2132 				{
2133 					SSG.count[ch] += SSG.period[ch];
2134 					if (SSG.count[ch] > 0)
2135 					{
2136 						SSG.output[ch] ^= 1;
2137 						break;
2138 					}
2139 					SSG.count[ch] += SSG.period[ch];
2140 				}
2141 			}
2142 		}
2143 
2144 		SSG.CountN -= nextevent;
2145 		if (SSG.CountN <= 0)
2146 		{
2147 			/* Is noise output going to change? */
2148 			if ((SSG.RNG + 1) & 2)	/* (bit0^bit1)? */
2149 			{
2150 				SSG.OutputN = ~SSG.OutputN;
2151 				outn = (SSG.OutputN | YM2610.regs[SSG_ENABLE]);
2152 			}
2153 
2154 			if (SSG.RNG & 1) SSG.RNG ^= 0x24000;
2155 			SSG.RNG >>= 1;
2156 			SSG.CountN += SSG.PeriodN;
2157 		}
2158 
2159 		left -= nextevent;
2160 	} while (left > 0);
2161 
2162 	/* update envelope */
2163 	if (SSG.holding == 0)
2164 	{
2165 		SSG.CountE -= SSG_STEP;
2166 		if (SSG.CountE <= 0)
2167 		{
2168 			do
2169 			{
2170 				SSG.count_env--;
2171 				SSG.CountE += SSG.PeriodE;
2172 			} while (SSG.CountE <= 0);
2173 
2174 			/* check envelope current position */
2175 			if (SSG.count_env < 0)
2176 			{
2177 				if (SSG.hold)
2178 				{
2179 					if (SSG.alternate)
2180 						SSG.attack ^= 0x1f;
2181 					SSG.holding = 1;
2182 					SSG.count_env = 0;
2183 				}
2184 				else
2185 				{
2186 					/* if count_env has looped an odd number of times (usually 1), */
2187 					/* invert the output. */
2188 					if (SSG.alternate && (SSG.count_env & 0x20))
2189 						SSG.attack ^= 0x1f;
2190 
2191 					SSG.count_env &= 0x1f;
2192 				}
2193 			}
2194 
2195 			SSG.VolE = SSG.vol_table[SSG.count_env ^ SSG.attack];
2196 			/* reload volume */
2197 			if (SSG.envelope[0]) SSG.vol[0] = SSG.VolE;
2198 			if (SSG.envelope[1]) SSG.vol[1] = SSG.VolE;
2199 			if (SSG.envelope[2]) SSG.vol[2] = SSG.VolE;
2200 		}
2201 	}
2202 
2203 	out_ssg = (((vol[0] * SSG.vol[0]) + (vol[1] * SSG.vol[1]) + (vol[2] * SSG.vol[2])) / SSG_STEP) / 3;
2204 
2205 	return outn;
2206 }
2207 
2208 
SSG_init_table(void)2209 static void SSG_init_table(void)
2210 {
2211 	int i;
2212 	double out;
2213 
2214 	/* calculate the volume->voltage conversion table */
2215 	/* The AY-3-8910 has 16 levels, in a logarithmic scale (3dB per step) */
2216 	/* The YM2149 still has 16 levels for the tone generators, but 32 for */
2217 	/* the envelope generator (1.5dB per step). */
2218 	out = SSG_MAX_OUTPUT;
2219 	for (i = 31; i > 0; i--)
2220 	{
2221 		SSG.vol_table[i] = out + 0.5;	/* round to nearest */
2222 
2223 		out /= 1.188502227;	/* = 10 ^ (1.5/20) = 1.5dB */
2224 	}
2225 	SSG.vol_table[0] = 0;
2226 }
2227 
2228 
SSG_reset(void)2229 static void SSG_reset(void)
2230 {
2231 	int i;
2232 
2233 	SSG.RNG = 1;
2234 	SSG.output[0] = 0;
2235 	SSG.output[1] = 0;
2236 	SSG.output[2] = 0;
2237 	SSG.OutputN = 0xff;
2238 	SSG.lastEnable = -1;
2239 	for (i = 0; i < SSG_PORTA; i++)
2240 	{
2241 		YM2610.regs[i] = 0x00;
2242 		SSGWriteReg(i, 0x00);
2243 	}
2244 }
2245 
2246 
SSG_write(int r,int v)2247 static void SSG_write(int r, int v)
2248 {
2249 	SSGWriteReg(r, v);
2250 }
2251 
2252 
2253 /*********************************************************************************************/
2254 
2255 /**** YM2610 ADPCM-A defines ****/
2256 #define ADPCM_SHIFT    (16)      /* frequency step rate   */
2257 #define ADPCMA_ADDRESS_SHIFT 8   /* adpcm A address shift */
2258 
2259 static u8 *pcmbufA;
2260 static u32 pcmsizeA;
2261 
2262 
2263 /* Algorithm and tables verified on real YM2610 */
2264 
2265 /* usual ADPCM table (16 * 1.1^N) */
2266 static int steps[49] =
2267 {
2268 	 16,  17,   19,   21,   23,   25,   28,
2269 	 31,  34,   37,   41,   45,   50,   55,
2270 	 60,  66,   73,   80,   88,   97,  107,
2271 	118, 130,  143,  157,  173,  190,  209,
2272 	230, 253,  279,  307,  337,  371,  408,
2273 	449, 494,  544,  598,  658,  724,  796,
2274 	876, 963, 1060, 1166, 1282, 1411, 1552
2275 };
2276 
2277 /* different from the usual ADPCM table */
2278 static int step_inc[8] = { -1*16, -1*16, -1*16, -1*16, 2*16, 5*16, 7*16, 9*16 };
2279 
2280 /* speedup purposes only */
2281 static int jedi_table[ 49*16 ];
2282 
2283 
OPNB_ADPCMA_init_table(void)2284 static void OPNB_ADPCMA_init_table(void)
2285 {
2286 	int step, nib;
2287 
2288 	for (step = 0; step < 49; step++)
2289 	{
2290 		/* loop over all nibbles and compute the difference */
2291 		for (nib = 0; nib < 16; nib++)
2292 		{
2293 			int value = (2 * (nib & 0x07) + 1) * steps[step] / 8;
2294 			jedi_table[step * 16 + nib] = (nib & 0x08) ? -value : value;
2295 		}
2296 	}
2297 
2298 }
2299 
2300 /* ADPCM A (Non control type) : calculate one channel output */
OPNB_ADPCMA_calc_chan(ADPCMA * ch)2301 INLINE void OPNB_ADPCMA_calc_chan(ADPCMA *ch)
2302 {
2303 	u32 step;
2304 	u8  data;
2305 
2306 
2307 	ch->now_step += ch->step;
2308 	if (ch->now_step >= (1 << ADPCM_SHIFT))
2309 	{
2310 		step = ch->now_step >> ADPCM_SHIFT;
2311 		ch->now_step &= (1 << ADPCM_SHIFT) - 1;
2312 
2313 		do
2314 		{
2315 			/* end check */
2316 			/* 11-06-2001 JB: corrected comparison. Was > instead of == */
2317 			/* YM2610 checks lower 20 bits only, the 4 MSB bits are sample bank */
2318 			/* Here we use 1<<21 to compensate for nibble calculations */
2319 
2320 			if ((ch->now_addr & ((1 << 21) - 1)) == ((ch->end << 1) & ((1 << 21) - 1)))
2321 			{
2322 				ch->flag = 0;
2323 				YM2610.adpcm_arrivedEndAddress |= ch->flagMask;
2324 				return;
2325 			}
2326 
2327 			if (ch->now_addr & 1)
2328 				data = ch->now_data & 0x0f;
2329 			else
2330 			{
2331 				ch->now_data = *(pcmbufA + (ch->now_addr >> 1));
2332 				data = (ch->now_data >> 4) & 0x0f;
2333 			}
2334 
2335 			ch->now_addr++;
2336 
2337 			ch->adpcma_acc += jedi_table[ch->adpcma_step + data];
2338 			/* extend 12-bit signed int */
2339 
2340 			if (ch->adpcma_acc & 0x800)
2341 				ch->adpcma_acc |= ~0xfff;
2342 			else
2343 				ch->adpcma_acc &= 0xfff;
2344 
2345 			ch->adpcma_step += step_inc[data & 7];
2346 			Limit(ch->adpcma_step, 48*16, 0*16);
2347 
2348 		} while (--step);
2349 
2350 		/* calc pcm * volume data */
2351 		ch->adpcma_out = (((Sint16)ch->adpcma_acc * ch->vol_mul) >> ch->vol_shift) & ~3;	/* multiply, shift and mask out 2 LSB bits */
2352 	}
2353 
2354 	/* output for work of output channels (out_adpcma[OPNxxxx]) */
2355 	*ch->pan += ch->adpcma_out;
2356 }
2357 
2358 /* ADPCM type A Write */
OPNB_ADPCMA_write(int r,int v)2359 static void OPNB_ADPCMA_write(int r, int v)
2360 {
2361 	ADPCMA *adpcma = YM2610.adpcma;
2362 	u8 c = r & 0x07;
2363 
2364 	YM2610.regs[r] = v & 0xff; /* stock data */
2365 
2366 	switch (r)
2367 	{
2368 	case 0x100: /* DM,--,C5,C4,C3,C2,C1,C0 */
2369 		if (!(v & 0x80))
2370 		{
2371 			/* KEY ON */
2372 			for (c = 0; c < 6; c++)
2373 			{
2374 				if ((v >> c) & 1)
2375 				{
2376 					/**** start adpcm ****/
2377 					adpcma[c].step        = (u32)((float)(1 << ADPCM_SHIFT) * ((float)YM2610.OPN.ST.freqbase) / 3.0);
2378 					adpcma[c].now_addr    = adpcma[c].start << 1;
2379 					adpcma[c].now_step    = 0;
2380 					adpcma[c].adpcma_acc  = 0;
2381 					adpcma[c].adpcma_step = 0;
2382 					adpcma[c].adpcma_out  = 0;
2383 					adpcma[c].flag        = 1;
2384 
2385 					if (pcmbufA == NULL)
2386 					{
2387 						/* Check ROM Mapped */
2388 //						logerror("YM2610: ADPCM-A rom not mapped\n");
2389 						adpcma[c].flag = 0;
2390 					}
2391 					else
2392 					{
2393 						if (adpcma[c].end >= pcmsizeA)
2394 						{
2395 							/* Check End in Range */
2396 //							logerror("YM2610: ADPCM-A end out of range: $%08x\n", adpcma[c].end);
2397 							/* adpcma[c].end = pcmsizeA - 1; */ /* JB: DO NOT uncomment this, otherwise you will break the comparison in the ADPCM_CALC_CHA() */
2398 						}
2399 						if (adpcma[c].start >= pcmsizeA)	/* Check Start in Range */
2400 						{
2401 //							logerror("YM2610: ADPCM-A start out of range: $%08x\n", adpcma[c].start);
2402 							adpcma[c].flag = 0;
2403 						}
2404 					}
2405 				}
2406 			}
2407 		}
2408 		else
2409 		{
2410 			/* KEY OFF */
2411 			for (c = 0; c < 6; c++)
2412 				if ((v >> c) & 1)
2413 					adpcma[c].flag = 0;
2414 		}
2415 		break;
2416 
2417 	case 0x101:	/* B0-5 = TL */
2418 		YM2610.adpcmaTL = (v & 0x3f) ^ 0x3f;
2419 		for (c = 0; c < 6; c++)
2420 		{
2421 			int volume = YM2610.adpcmaTL + adpcma[c].IL;
2422 
2423 			if (volume >= 63)	/* This is correct, 63 = quiet */
2424 			{
2425 				adpcma[c].vol_mul   = 0;
2426 				adpcma[c].vol_shift = 0;
2427 			}
2428 			else
2429 			{
2430 				adpcma[c].vol_mul   = 15 - (volume & 7);	/* so called 0.75 dB */
2431 				adpcma[c].vol_shift =  1 + (volume >> 3);	/* Yamaha engineers used the approximation: each -6 dB is close to divide by two (shift right) */
2432 			}
2433 
2434 			/* calc pcm * volume data */
2435 			adpcma[c].adpcma_out = ((adpcma[c].adpcma_acc * adpcma[c].vol_mul) >> adpcma[c].vol_shift) & ~3;	/* multiply, shift and mask out low 2 bits */
2436 		}
2437 		break;
2438 
2439 	default:
2440 		c = r & 0x07;
2441 		if (c >= 0x06) return;
2442 		switch (r & 0x138)
2443 		{
2444 		case 0x108:	/* B7=L,B6=R,B4-0=IL */
2445 			{
2446 				int volume;
2447 
2448 				adpcma[c].IL = (v & 0x1f) ^ 0x1f;
2449 
2450 				volume = YM2610.adpcmaTL + adpcma[c].IL;
2451 
2452 				if (volume >= 63)	/* This is correct, 63 = quiet */
2453 				{
2454 					adpcma[c].vol_mul   = 0;
2455 					adpcma[c].vol_shift = 0;
2456 				}
2457 				else
2458 				{
2459 					adpcma[c].vol_mul   = 15 - (volume & 7);		/* so called 0.75 dB */
2460 					adpcma[c].vol_shift =  1 + (volume >> 3);	/* Yamaha engineers used the approximation: each -6 dB is close to divide by two (shift right) */
2461 				}
2462 
2463 				adpcma[c].pan = &out_adpcma[(v >> 6) & 0x03];
2464 
2465 				/* calc pcm * volume data */
2466 				adpcma[c].adpcma_out = ((adpcma[c].adpcma_acc * adpcma[c].vol_mul) >> adpcma[c].vol_shift) & ~3;	/* multiply, shift and mask out low 2 bits */
2467 			}
2468 			break;
2469 
2470 		case 0x110:
2471 		case 0x118:
2472 			adpcma[c].start = ((YM2610.regs[0x118 + c] << 8) | YM2610.regs[0x110 + c]) << ADPCMA_ADDRESS_SHIFT;
2473 			break;
2474 
2475 		case 0x120:
2476 		case 0x128:
2477 			adpcma[c].end  = ((YM2610.regs[0x128 + c] << 8) | YM2610.regs[0x120 + c]) << ADPCMA_ADDRESS_SHIFT;
2478 			adpcma[c].end += (1 << ADPCMA_ADDRESS_SHIFT) - 1;
2479 			break;
2480 		}
2481 	}
2482 }
2483 
2484 
2485 /*********************************************************************************************/
2486 
2487 /* DELTA-T particle adjuster */
2488 #define ADPCMB_DELTA_MAX (24576)
2489 #define ADPCMB_DELTA_MIN (127)
2490 #define ADPCMB_DELTA_DEF (127)
2491 
2492 #define ADPCMB_DECODE_RANGE 32768
2493 #define ADPCMB_DECODE_MIN (-(ADPCMB_DECODE_RANGE))
2494 #define ADPCMB_DECODE_MAX ((ADPCMB_DECODE_RANGE)-1)
2495 
2496 static u8 *pcmbufB;
2497 static u32 pcmsizeB;
2498 
2499 /* Forecast to next Forecast (rate = *8) */
2500 /* 1/8 , 3/8 , 5/8 , 7/8 , 9/8 , 11/8 , 13/8 , 15/8 */
2501 static const s32 adpcmb_decode_table1[16] =
2502 {
2503   1,   3,   5,   7,   9,  11,  13,  15,
2504   -1,  -3,  -5,  -7,  -9, -11, -13, -15,
2505 };
2506 /* delta to next delta (rate= *64) */
2507 /* 0.9 , 0.9 , 0.9 , 0.9 , 1.2 , 1.6 , 2.0 , 2.4 */
2508 static const s32 adpcmb_decode_table2[16] =
2509 {
2510   57,  57,  57,  57, 77, 102, 128, 153,
2511   57,  57,  57,  57, 77, 102, 128, 153
2512 };
2513 
2514 /* 0-DRAM x1, 1-ROM, 2-DRAM x8, 3-ROM (3 is bad setting - not allowed by the manual) */
2515 static u8 dram_rightshift[4]={3,0,0,0};
2516 
2517 /* DELTA-T-ADPCM write register */
OPNB_ADPCMB_write(ADPCMB * adpcmb,int r,int v)2518 static void OPNB_ADPCMB_write(ADPCMB *adpcmb, int r, int v)
2519 {
2520 	if (r >= 0x20) return;
2521 
2522 	YM2610.regs[r] = v; /* stock data */
2523 
2524 	switch (r)
2525 	{
2526 	case 0x10:
2527 /*
2528 START:
2529     Accessing *external* memory is started when START bit (D7) is set to "1", so
2530     you must set all conditions needed for recording/playback before starting.
2531     If you access *CPU-managed* memory, recording/playback starts after
2532     read/write of ADPCM data register $08.
2533 
2534 REC:
2535     0 = ADPCM synthesis (playback)
2536     1 = ADPCM analysis (record)
2537 
2538 MEMDATA:
2539     0 = processor (*CPU-managed*) memory (means: using register $08)
2540     1 = external memory (using start/end/limit registers to access memory: RAM or ROM)
2541 
2542 
2543 SPOFF:
2544     controls output pin that should disable the speaker while ADPCM analysis
2545 
2546 RESET and REPEAT only work with external memory.
2547 
2548 
2549 some examples:
2550 value:   START, REC, MEMDAT, REPEAT, SPOFF, x,x,RESET   meaning:
2551   C8     1      1    0       0       1      0 0 0       Analysis (recording) from AUDIO to CPU (to reg $08), sample rate in PRESCALER register
2552   E8     1      1    1       0       1      0 0 0       Analysis (recording) from AUDIO to EXT.MEMORY,       sample rate in PRESCALER register
2553   80     1      0    0       0       0      0 0 0       Synthesis (playing) from CPU (from reg $08) to AUDIO,sample rate in DELTA-N register
2554   a0     1      0    1       0       0      0 0 0       Synthesis (playing) from EXT.MEMORY to AUDIO,        sample rate in DELTA-N register
2555 
2556   60     0      1    1       0       0      0 0 0       External memory write via ADPCM data register $08
2557   20     0      0    1       0       0      0 0 0       External memory read via ADPCM data register $08
2558 
2559 */
2560 		v |= 0x20;		/*  YM2610 always uses external memory and doesn't even have memory flag bit. */
2561 		adpcmb->portstate = v & (0x80|0x40|0x20|0x10|0x01); /* start, rec, memory mode, repeat flag copy, reset(bit0) */
2562 
2563 		if (adpcmb->portstate & 0x80)	/* START,REC,MEMDATA,REPEAT,SPOFF,--,--,RESET */
2564 		{
2565 			/* set PCM BUSY bit */
2566 			adpcmb->PCM_BSY = 1;
2567 
2568 			/* start ADPCM */
2569 			adpcmb->now_step      = 0;
2570 			adpcmb->acc           = 0;
2571 			adpcmb->prev_acc      = 0;
2572 			adpcmb->adpcml        = 0;
2573 			adpcmb->adpcmd        = ADPCMB_DELTA_DEF;
2574 			adpcmb->now_data      = 0;
2575 		}
2576 
2577 //		if (adpcmb->portstate & 0x20) /* do we access external memory? */
2578 		{
2579 			adpcmb->now_addr = adpcmb->start << 1;
2580 			adpcmb->memread = 2;	/* two dummy reads needed before accesing external memory via register $08*/
2581 
2582 			/* if yes, then let's check if ADPCM memory is mapped and big enough */
2583 			if (!pcmbufB)
2584 			{
2585 //				logerror("YM2610: Delta-T ADPCM rom not mapped\n");
2586 				adpcmb->portstate = 0x00;
2587 				adpcmb->PCM_BSY = 0;
2588 			}
2589 			else
2590 			{
2591 				if (adpcmb->end >= pcmsizeB)	/* Check End in Range */
2592 				{
2593 //					logerror("YM2610: Delta-T ADPCM end out of range: $%08x\n", adpcmb->end);
2594 					adpcmb->end = pcmsizeB - 1;
2595 				}
2596 				if (adpcmb->start >= pcmsizeB)	/* Check Start in Range */
2597 				{
2598 //					logerror("YM2610: Delta-T ADPCM start out of range: $%08x\n", adpcmb->start);
2599 					adpcmb->portstate = 0x00;
2600 					adpcmb->PCM_BSY = 0;
2601 				}
2602 			}
2603 		}
2604 #if 0
2605 		else	/* we access CPU memory (ADPCM data register $08) so we only reset now_addr here */
2606 		{
2607 			adpcmb->now_addr = 0;
2608 		}
2609 #endif
2610 
2611 		if (adpcmb->portstate & 0x01)
2612 		{
2613 			adpcmb->portstate = 0x00;
2614 
2615 			/* clear PCM BUSY bit (in status register) */
2616 			adpcmb->PCM_BSY = 0;
2617 
2618 			/* set BRDY flag */
2619 			if (adpcmb->status_change_BRDY_bit)
2620 				YM2610.adpcm_arrivedEndAddress |= adpcmb->status_change_BRDY_bit;
2621 		}
2622 		break;
2623 
2624 	case 0x11:	/* L,R,-,-,SAMPLE,DA/AD,RAMTYPE,ROM */
2625 		v |= 0x01;		/*  YM2610 always uses ROM as an external memory and doesn't tave ROM/RAM memory flag bit. */
2626 		adpcmb->pan = &out_delta[(v >> 6) & 0x03];
2627 		if ((adpcmb->control2 & 3) != (v & 3))
2628 		{
2629 			/*0-DRAM x1, 1-ROM, 2-DRAM x8, 3-ROM (3 is bad setting - not allowed by the manual) */
2630 			if (adpcmb->DRAMportshift != dram_rightshift[v & 3])
2631 			{
2632 				adpcmb->DRAMportshift = dram_rightshift[v & 3];
2633 
2634 				/* final shift value depends on chip type and memory type selected:
2635                         8 for YM2610 (ROM only),
2636                         5 for ROM for Y8950 and YM2608,
2637                         5 for x8bit DRAMs for Y8950 and YM2608,
2638                         2 for x1bit DRAMs for Y8950 and YM2608.
2639                 */
2640 
2641 				/* refresh addresses */
2642 				adpcmb->start  = ((YM2610.regs[0x13] << 8) | YM2610.regs[0x12]) << adpcmb->portshift;
2643 				adpcmb->end    = ((YM2610.regs[0x15] << 8) | YM2610.regs[0x14]) << adpcmb->portshift;
2644 				adpcmb->end   += (1 << adpcmb->portshift) - 1;
2645 				adpcmb->limit  = ((YM2610.regs[0x1d] << 8) | YM2610.regs[0x1c]) << adpcmb->portshift;
2646 			}
2647 		}
2648 		adpcmb->control2 = v;
2649 		break;
2650 
2651 	case 0x12:	/* Start Address L */
2652 	case 0x13:	/* Start Address H */
2653 		adpcmb->start = ((YM2610.regs[0x13] << 8) | YM2610.regs[0x12]) << adpcmb->portshift;
2654 		/*logerror("DELTAT start: 02=%2x 03=%2x addr=%8x\n", YM2610.regs[0x12], YM2610.regs[0x13], adpcmb->start);*/
2655 		break;
2656 
2657 	case 0x14:	/* Stop Address L */
2658 	case 0x15:	/* Stop Address H */
2659 		adpcmb->end   = ((YM2610.regs[0x15] << 8) | YM2610.regs[0x14]) << adpcmb->portshift;
2660 		adpcmb->end  += (1 << adpcmb->portshift) - 1;
2661 		/*logerror("DELTAT end  : 04=%2x 05=%2x addr=%8x\n", YM2610.regs[0x14], YM2610.reg[0x15], adpcmb->end);*/
2662 		break;
2663 
2664 	case 0x19:	/* DELTA-N L (ADPCM Playback Prescaler) */
2665 	case 0x1a:	/* DELTA-N H */
2666 		adpcmb->delta = (YM2610.regs[0x1a] << 8) | YM2610.regs[0x19];
2667 		adpcmb->step  = (u32)((double)(adpcmb->delta /* * (1 << (ADPCMb_SHIFT - 16)) */) * (adpcmb->freqbase));
2668 		/*logerror("DELTAT deltan:09=%2x 0a=%2x\n", YM2610.regs[0x19], YM2610.regs[0x1a]);*/
2669 		break;
2670 
2671 	case 0x1b:	/* Output level control (volume, linear) */
2672 		{
2673 			s32 oldvol = adpcmb->volume;
2674 			adpcmb->volume = (v & 0xff) * (adpcmb->output_range / 256) / ADPCMB_DECODE_RANGE;
2675 //								v	  *		((1<<16)>>8)		>>	15;
2676 //						thus:	v	  *		(1<<8)				>>	15;
2677 //						thus: output_range must be (1 << (15+8)) at least
2678 //								v     *		((1<<23)>>8)		>>	15;
2679 //								v	  *		(1<<15)				>>	15;
2680 			/*logerror("DELTAT vol = %2x\n", v & 0xff);*/
2681 			if (oldvol != 0)
2682 			{
2683 				adpcmb->adpcml = (int)((double)adpcmb->adpcml / (double)oldvol * (double)adpcmb->volume);
2684 			}
2685 		}
2686 		break;
2687 	}
2688 }
2689 
2690 
OPNB_ADPCMB_CALC(ADPCMB * adpcmb)2691 INLINE void OPNB_ADPCMB_CALC(ADPCMB *adpcmb)
2692 {
2693 	u32 step;
2694 	int data;
2695 
2696 	adpcmb->now_step += adpcmb->step;
2697 	if (adpcmb->now_step >= (1 << ADPCM_SHIFT))
2698 	{
2699 		step = adpcmb->now_step >> ADPCM_SHIFT;
2700 		adpcmb->now_step &= (1 << ADPCM_SHIFT) - 1;
2701 		do
2702 		{
2703 			if (adpcmb->now_addr == (adpcmb->limit << 1))
2704 				adpcmb->now_addr = 0;
2705 
2706 			if (adpcmb->now_addr == (adpcmb->end << 1))
2707 			{
2708 				/* 12-06-2001 JB: corrected comparison. Was > instead of == */
2709 				if (adpcmb->portstate & 0x10)
2710 				{
2711 					/* repeat start */
2712 					adpcmb->now_addr = adpcmb->start << 1;
2713 					adpcmb->acc      = 0;
2714 					adpcmb->adpcmd   = ADPCMB_DELTA_DEF;
2715 					adpcmb->prev_acc = 0;
2716 				}
2717 				else
2718 				{
2719 					/* set EOS bit in status register */
2720 					if (adpcmb->status_change_EOS_bit)
2721 						YM2610.adpcm_arrivedEndAddress |= adpcmb->status_change_EOS_bit;
2722 
2723 					/* clear PCM BUSY bit (reflected in status register) */
2724 					adpcmb->PCM_BSY = 0;
2725 
2726 					adpcmb->portstate = 0;
2727 					adpcmb->adpcml = 0;
2728 					adpcmb->prev_acc = 0;
2729 					return;
2730 				}
2731 			}
2732 			if (adpcmb->now_addr & 1)
2733 			{
2734 				data = adpcmb->now_data & 0x0f;
2735 			}
2736 			else
2737 			{
2738 				adpcmb->now_data = *(pcmbufB + (adpcmb->now_addr >> 1));
2739 				data = adpcmb->now_data >> 4;
2740 			}
2741 
2742 			adpcmb->now_addr++;
2743 			/* 12-06-2001 JB: */
2744 			/* YM2610 address register is 24 bits wide.*/
2745 			/* The "+1" is there because we use 1 bit more for nibble calculations.*/
2746 			/* WARNING: */
2747 			/* Side effect: we should take the size of the mapped ROM into account */
2748 			adpcmb->now_addr &= ((1 << (24 + 1)) - 1);
2749 
2750 			/* store accumulator value */
2751 			adpcmb->prev_acc = adpcmb->acc;
2752 
2753 			/* Forecast to next Forecast */
2754 			adpcmb->acc += (adpcmb_decode_table1[data] * adpcmb->adpcmd / 8);
2755 			Limit(adpcmb->acc, ADPCMB_DECODE_MAX, ADPCMB_DECODE_MIN);
2756 
2757 			/* delta to next delta */
2758 			adpcmb->adpcmd = (adpcmb->adpcmd * adpcmb_decode_table2[data]) / 64;
2759 			Limit(adpcmb->adpcmd, ADPCMB_DELTA_MAX, ADPCMB_DELTA_MIN);
2760 
2761 			/* ElSemi: Fix interpolator. */
2762 			/*adpcmb->prev_acc = prev_acc + ((adpcmb->acc - prev_acc) / 2);*/
2763 
2764 		} while (--step);
2765 
2766 	}
2767 
2768 	/* ElSemi: Fix interpolator. */
2769 #if 1
2770 	adpcmb->adpcml = adpcmb->prev_acc * (int)((1 << ADPCM_SHIFT) - adpcmb->now_step);
2771 	adpcmb->adpcml += (adpcmb->acc * (int)adpcmb->now_step);
2772 	adpcmb->adpcml = (adpcmb->adpcml >> ADPCM_SHIFT) * (int)adpcmb->volume;
2773 #else
2774 	adpcmb->adpcml = ((adpcmb->acc * (int)adpcmb->now_step) >> ADPCM_SHIFT)* (int)adpcmb->volume;;
2775 #endif
2776 
2777 	/* output for work of output channels (outd[OPNxxxx])*/
2778 	*adpcmb->pan += adpcmb->adpcml;
2779 }
2780 
2781 
2782 /*********************************************************************************************/
2783 
2784 /* YM2610(OPNB) */
2785 
2786 #ifdef SOUND_TEST
2787 static int stream_pos;
2788 static int samples_left;
2789 #endif
2790 
YM2610Init(int clock,int rate,void * pcmroma,int pcmsizea,void * pcmromb,int pcmsizeb,FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)2791 void YM2610Init(int clock, int rate,
2792 				void *pcmroma, int pcmsizea,
2793 				void *pcmromb, int pcmsizeb,
2794 				FM_TIMERHANDLER TimerHandler, FM_IRQHANDLER IRQHandler)
2795 {
2796 /*
2797 	sound->stack    = 0x10000;
2798 	sound->stereo   = 1;
2799 #ifdef SOUND_TEST
2800 	if (sound_test)
2801 		sound->callback = YM2610Update_SoundTest;
2802 	else
2803 #endif
2804 		sound->callback = YM2610Update;
2805 */
2806 
2807 	/* clear */
2808 	memset(&YM2610, 0, sizeof(YM2610));
2809 	memset(&SSG, 0, sizeof(SSG));
2810 
2811 	OPNInitTable();
2812 	SSG_init_table();
2813 	OPNB_ADPCMA_init_table();
2814 
2815 	/* FM */
2816 	YM2610.OPN.P_CH = YM2610.CH;
2817 	YM2610.OPN.ST.clock = clock;
2818 	YM2610.OPN.ST.rate = rate;
2819 	/* Extend handler */
2820 	YM2610.OPN.ST.Timer_Handler = TimerHandler;
2821 	YM2610.OPN.ST.IRQ_Handler   = IRQHandler;
2822 	/* SSG */
2823 	SSG.step = ((double)SSG_STEP * rate * 8) / clock;
2824 	/* ADPCM-A */
2825 	pcmbufA = (u8 *)pcmroma;
2826 	pcmsizeA = pcmsizea;
2827 	/* ADPCM-B */
2828 	pcmbufB = (u8 *)pcmromb;
2829 	pcmsizeB = pcmsizeb;
2830 
2831 	YM2610.adpcmb.status_change_EOS_bit = 0x80;	/* status flag: set bit7 on End Of Sample */
2832 
2833 	YM2610Reset();
2834 }
2835 
YM2610ChangeSamplerate(int rate)2836 void YM2610ChangeSamplerate(int rate) {
2837 	int i;
2838 	YM2610.OPN.ST.rate = rate;
2839 	SSG.step = ((double)SSG_STEP * rate * 8) / YM2610.OPN.ST.clock;
2840 	OPNSetPres(&YM2610.OPN, 6*24, 6*24, 4*2); /* OPN 1/6, SSG 1/4 */
2841 	for (i = 0; i < 6; i++) {
2842 		YM2610.adpcma[i].step = (u32) ((float) (1 << ADPCM_SHIFT) * ((float) YM2610.OPN.ST.freqbase) / 3.0);
2843 	}
2844 	YM2610.adpcmb.freqbase = YM2610.OPN.ST.freqbase;
2845 }
2846 /* reset one of chip */
YM2610Reset(void)2847 void YM2610Reset(void)
2848 {
2849 	int i;
2850 	FM_OPN *OPN = &YM2610.OPN;
2851 
2852 	/* Reset Prescaler */
2853 	OPNSetPres(OPN, 6*24, 6*24, 4*2); /* OPN 1/6, SSG 1/4 */
2854 	/* reset SSG section */
2855 	SSG_reset();
2856 	/* status clear */
2857 	FM_IRQMASK_SET(&OPN->ST, 0x03);
2858 	FM_BUSY_CLEAR(&OPN->ST);
2859 	OPNWriteMode(OPN, 0x27, 0x30);	/* mode 0, timer reset */
2860 
2861 	OPN->eg_timer = 0;
2862 	OPN->eg_cnt   = 0;
2863 
2864 	FM_STATUS_RESET(&OPN->ST, 0xff);
2865 
2866 	reset_channels(&OPN->ST, YM2610.CH, 6);
2867 	/* reset OPerator paramater */
2868 	for (i = 0xb6; i >= 0xb4; i--)
2869 	{
2870 		OPNWriteReg(OPN, i      , 0xc0);
2871 		OPNWriteReg(OPN, i|0x100, 0xc0);
2872 	}
2873 	for (i = 0xb2; i >= 0x30; i--)
2874 	{
2875 		OPNWriteReg(OPN, i      , 0x00);
2876 		OPNWriteReg(OPN, i|0x100, 0x00);
2877 	}
2878 	for (i = 0x26; i >= 0x20; i--)
2879 	{
2880 		OPNWriteReg(OPN, i, 0x00);
2881 	}
2882 	/**** ADPCM work initial ****/
2883 	for (i = 0; i < 6; i++)
2884 	{
2885 		YM2610.adpcma[i].step        = (u32)((float)(1 << ADPCM_SHIFT) * ((float)YM2610.OPN.ST.freqbase) / 3.0);
2886 		YM2610.adpcma[i].now_addr    = 0;
2887 		YM2610.adpcma[i].now_step    = 0;
2888 		YM2610.adpcma[i].start       = 0;
2889 		YM2610.adpcma[i].end         = 0;
2890 		YM2610.adpcma[i].vol_mul     = 0;
2891 		YM2610.adpcma[i].pan         = &out_adpcma[OUTD_CENTER]; /* default center */
2892 		YM2610.adpcma[i].flagMask    = 1 << i;
2893 		YM2610.adpcma[i].flag        = 0;
2894 		YM2610.adpcma[i].adpcma_acc  = 0;
2895 		YM2610.adpcma[i].adpcma_step = 0;
2896 		YM2610.adpcma[i].adpcma_out  = 0;
2897 	}
2898 	YM2610.adpcmaTL = 0x3f;
2899 
2900 	YM2610.adpcm_arrivedEndAddress = 0;
2901 
2902 	/* ADPCM-B unit */
2903 	YM2610.adpcmb.freqbase     = OPN->ST.freqbase;
2904 	YM2610.adpcmb.portshift    = 8;		/* allways 8bits shift */
2905 	YM2610.adpcmb.output_range = 1 << 23;
2906 
2907 	YM2610.adpcmb.now_addr     = 0;
2908 	YM2610.adpcmb.now_step     = 0;
2909 	YM2610.adpcmb.step         = 0;
2910 	YM2610.adpcmb.start        = 0;
2911 	YM2610.adpcmb.end          = 0;
2912 	YM2610.adpcmb.limit        = ~0; /* this way YM2610 and Y8950 (both of which don't have limit address reg) will still work */
2913 	YM2610.adpcmb.volume       = 0;
2914 	YM2610.adpcmb.pan          = &out_delta[OUTD_CENTER];
2915 	YM2610.adpcmb.acc          = 0;
2916 	YM2610.adpcmb.prev_acc     = 0;
2917 	YM2610.adpcmb.adpcmd       = 127;
2918 	YM2610.adpcmb.adpcml       = 0;
2919 	YM2610.adpcmb.portstate    = 0x20;
2920 	YM2610.adpcmb.control2     = 0x01;
2921 
2922 	/* The flag mask register disables the BRDY after the reset, however
2923     ** as soon as the mask is enabled the flag needs to be set. */
2924 
2925 	/* set BRDY bit in status register */
2926 	if (YM2610.adpcmb.status_change_BRDY_bit)
2927 		YM2610.adpcm_arrivedEndAddress |= YM2610.adpcmb.status_change_BRDY_bit;
2928 
2929 #ifdef SOUND_TEST
2930 	stream_pos = 0;
2931 	samples_left = 0;
2932 #endif
2933 }
2934 
2935 /* YM2610 write */
2936 /* a = address */
2937 /* v = value   */
YM2610Write(int a,u8 v)2938 int YM2610Write(int a, u8 v)
2939 {
2940 	FM_OPN *OPN = &YM2610.OPN;
2941 	int addr;
2942 	int ch;
2943 
2944 	v &= 0xff;	/* adjust to 8 bit bus */
2945 
2946 	switch (a & 3)
2947 	{
2948 	case 0:	/* address port 0 */
2949 		OPN->ST.address = v;
2950 		YM2610.addr_A1 = 0;
2951 
2952 		/* Write register to SSG emulator */
2953 //		if (v < 16) SSG_write(0, v);
2954 		break;
2955 
2956 	case 1:	/* data port 0    */
2957 		if (YM2610.addr_A1 != 0)
2958 			break;	/* verified on real YM2608 */
2959 
2960 		YM2610UpdateRequest();
2961 		addr = OPN->ST.address;
2962 		YM2610.regs[addr] = v;
2963 		switch (addr & 0xf0)
2964 		{
2965 		case 0x00:	/* SSG section */
2966 			/* Write data to SSG emulator */
2967 			SSG_write(addr, v);
2968 			break;
2969 
2970 		case 0x10: /* DeltaT ADPCM */
2971 			switch (addr)
2972 			{
2973 			case 0x10:	/* control 1 */
2974 			case 0x11:	/* control 2 */
2975 			case 0x12:	/* start address L */
2976 			case 0x13:	/* start address H */
2977 			case 0x14:	/* stop address L */
2978 			case 0x15:	/* stop address H */
2979 
2980 			case 0x19:	/* delta-n L */
2981 			case 0x1a:	/* delta-n H */
2982 			case 0x1b:	/* volume */
2983 				OPNB_ADPCMB_write(&YM2610.adpcmb, addr, v);
2984 				break;
2985 
2986 			case 0x1c: /*  FLAG CONTROL : Extend Status Clear/Mask */
2987 				{
2988 					u8 statusmask = ~v;
2989 					/* set arrived flag mask */
2990 					for (ch = 0; ch < 6; ch++)
2991 						YM2610.adpcma[ch].flagMask = statusmask & (1 << ch);
2992 
2993 					YM2610.adpcmb.status_change_EOS_bit = statusmask & 0x80;	/* status flag: set bit7 on End Of Sample */
2994 
2995 					/* clear arrived flag */
2996 					YM2610.adpcm_arrivedEndAddress &= statusmask;
2997 				}
2998 				break;
2999 			}
3000 			break;
3001 
3002 		case 0x20:	/* Mode Register */
3003 			OPNWriteMode(OPN, addr, v);
3004 			break;
3005 
3006 		default:	/* OPN section */
3007 			/* write register */
3008 			OPNWriteReg(OPN, addr, v);
3009 			break;
3010 		}
3011 		break;
3012 
3013 	case 2:	/* address port 1 */
3014 		OPN->ST.address = v;
3015 		YM2610.addr_A1 = 1;
3016 		break;
3017 
3018 	case 3:	/* data port 1    */
3019 		if (YM2610.addr_A1 != 1)
3020 			break;	/* verified on real YM2608 */
3021 
3022 		YM2610UpdateRequest();
3023 		addr = YM2610.OPN.ST.address | 0x100;
3024 		YM2610.regs[addr | 0x100] = v;
3025 		if (addr < 0x130)
3026 			/* 100-12f : ADPCM A section */
3027 			OPNB_ADPCMA_write(addr, v);
3028 		else
3029 			OPNWriteReg(OPN, addr, v);
3030 		break;
3031 	}
3032 
3033 	return OPN->ST.irq;
3034 }
3035 
3036 
YM2610Read(int a)3037 u8 YM2610Read(int a)
3038 {
3039 	int addr = YM2610.OPN.ST.address;
3040 
3041 	switch (a & 3)
3042 	{
3043 	case 0:	/* status 0 : YM2203 compatible */
3044 		return FM_STATUS_FLAG(&YM2610.OPN.ST) & 0x83;
3045 
3046 	case 1:	/* data 0 */
3047 		if (addr < SSG_PORTA) return YM2610.regs[addr];
3048 		if (addr == 0xff) return 0x01;
3049 		break;
3050 
3051 	case 2:	/* status 1 : ADPCM status */
3052 		/* ADPCM STATUS (arrived End Address) */
3053 		/* B, --, A5, A4, A3, A2, A1, A0 */
3054 		/* B     = ADPCM-B(DELTA-T) arrived end address */
3055 		/* A0-A5 = ADPCM-A          arrived end address */
3056 		return YM2610.adpcm_arrivedEndAddress;
3057 	}
3058 	return 0;
3059 }
3060 
3061 
YM2610TimerOver(int ch)3062 int YM2610TimerOver(int ch)
3063 {
3064 	FM_ST *ST = &YM2610.OPN.ST;
3065 
3066 	if (ch)
3067 	{
3068 		/* Timer B */
3069 		TimerBOver(ST);
3070 	}
3071 	else
3072 	{
3073 		/* Timer A */
3074 
3075 		YM2610UpdateRequest();
3076 
3077 		/* timer update */
3078 		TimerAOver(ST);
3079 
3080 		/* CSM mode key, TL controll */
3081 		if (ST->mode & 0x80)
3082 		{
3083 			/* CSM mode total level latch and auto key on */
3084 			CSMKeyControll(&YM2610.CH[2]);
3085 		}
3086 	}
3087 
3088 	return ST->irq;
3089 }
3090 
3091 
3092 s16 mixing_buffer[2][16384];
3093 extern Uint16 play_buffer[16384];
3094 //static Uint32 buf_pos;
3095 
3096 /* Generate samples for one of the YM2610s */
YM2610Update_stream(int length)3097 void YM2610Update_stream(int length)
3098 {
3099 	FM_OPN *OPN = &YM2610.OPN;
3100 	int i, j, outn;
3101 	FMSAMPLE_MIX lt, rt;
3102 	FM_CH *cch[6];
3103 	Uint16 *pl = play_buffer;
3104 
3105     //printf("AAA %d\n",length);
3106 	cch[0] = &YM2610.CH[1];
3107 	cch[1] = &YM2610.CH[2];
3108 	cch[2] = &YM2610.CH[4];
3109 	cch[3] = &YM2610.CH[5];
3110 
3111 	/* update frequency counter */
3112 	refresh_fc_eg_chan(cch[0]);
3113 	if (OPN->ST.mode & 0xc0)
3114 	{
3115 		/* 3SLOT MODE */
3116 		if (cch[1]->SLOT[SLOT1].Incr == -1)
3117 		{
3118 			/* 3 slot mode */
3119 			refresh_fc_eg_slot(&cch[1]->SLOT[SLOT1], OPN->SL3.fc[1], OPN->SL3.kcode[1]);
3120 			refresh_fc_eg_slot(&cch[1]->SLOT[SLOT2], OPN->SL3.fc[2], OPN->SL3.kcode[2]);
3121 			refresh_fc_eg_slot(&cch[1]->SLOT[SLOT3], OPN->SL3.fc[0], OPN->SL3.kcode[0]);
3122 			refresh_fc_eg_slot(&cch[1]->SLOT[SLOT4], cch[1]->fc,     cch[1]->kcode);
3123 		}
3124 	}
3125 	else
3126 		refresh_fc_eg_chan(cch[1]);
3127 	refresh_fc_eg_chan(cch[2]);
3128 	refresh_fc_eg_chan(cch[3]);
3129 
3130 	/* calc SSG count */
3131 	outn = SSG_calc_count(length);
3132 
3133 	/* buffering */
3134 	for (i = 0; i < length; i++)
3135 	{
3136 
3137 		advance_lfo(OPN);
3138 
3139 		/* clear output acc. */
3140 		out_adpcma[OUTD_LEFT] = out_adpcma[OUTD_RIGHT]= out_adpcma[OUTD_CENTER] = 0;
3141 		out_delta[OUTD_LEFT] = out_delta[OUTD_RIGHT]= out_delta[OUTD_CENTER] = 0;
3142 
3143 		/* clear outputs */
3144 		out_fm[1] = 0;
3145 		out_fm[2] = 0;
3146 		out_fm[4] = 0;
3147 		out_fm[5] = 0;
3148 
3149 		/* clear outputs SSG */
3150 		out_ssg = 0;
3151 
3152 		/* advance envelope generator */
3153 		OPN->eg_timer += OPN->eg_timer_add;
3154 		while (OPN->eg_timer >= OPN->eg_timer_overflow)
3155 		{
3156 			OPN->eg_timer -= OPN->eg_timer_overflow;
3157 			OPN->eg_cnt++;
3158             //printf("%d\n",OPN->eg_cnt);
3159 			advance_eg_channel(OPN, &cch[0]->SLOT[SLOT1]);
3160 			advance_eg_channel(OPN, &cch[1]->SLOT[SLOT1]);
3161 			advance_eg_channel(OPN, &cch[2]->SLOT[SLOT1]);
3162 			advance_eg_channel(OPN, &cch[3]->SLOT[SLOT1]);
3163 		}
3164 
3165 		/* calculate FM */
3166 		chan_calc(OPN, cch[0]);	/*remapped to 1*/
3167 		chan_calc(OPN, cch[1]);	/*remapped to 2*/
3168 		chan_calc(OPN, cch[2]);	/*remapped to 4*/
3169 		chan_calc(OPN, cch[3]);	/*remapped to 5*/
3170 
3171 		/* calculate SSG */
3172 		outn = SSG_CALC(outn);
3173 		/* deltaT ADPCM */
3174 		if (YM2610.adpcmb.portstate & 0x80)
3175 			OPNB_ADPCMB_CALC(&YM2610.adpcmb);
3176 
3177 		for (j = 0; j < 6; j++)
3178 		{
3179 			/* ADPCM */
3180 			if (YM2610.adpcma[j].flag)
3181 				OPNB_ADPCMA_calc_chan(&YM2610.adpcma[j]);
3182 		}
3183 		/* buffering */
3184 		lt =  out_adpcma[OUTD_LEFT]  + out_adpcma[OUTD_CENTER];
3185 		rt =  out_adpcma[OUTD_RIGHT] + out_adpcma[OUTD_CENTER];
3186 
3187 		lt += (out_delta[OUTD_LEFT]  + out_delta[OUTD_CENTER])>>9;
3188 		rt += (out_delta[OUTD_RIGHT] + out_delta[OUTD_CENTER])>>9;
3189 
3190 		lt += out_ssg;
3191 		rt += out_ssg;
3192 
3193 		lt += ((out_fm[1]>>1) & OPN->pan[2]);	/* the shift right was verified on real chip */
3194 		rt += ((out_fm[1]>>1) & OPN->pan[3]);
3195 		lt += ((out_fm[2]>>1) & OPN->pan[4]);
3196 		rt += ((out_fm[2]>>1) & OPN->pan[5]);
3197 
3198 		lt += ((out_fm[4]>>1) & OPN->pan[8]);
3199 		rt += ((out_fm[4]>>1) & OPN->pan[9]);
3200 		lt += ((out_fm[5]>>1) & OPN->pan[10]);
3201 		rt += ((out_fm[5]>>1) & OPN->pan[11]);
3202 
3203 		lt <<= 1;
3204 		rt <<= 1;
3205 
3206 		Limit(lt, MAXOUT, MINOUT);
3207 		Limit(rt, MAXOUT, MINOUT);
3208 /*
3209 		mixing_buffer[0][i] = lt;
3210 		mixing_buffer[1][i] = rt;
3211 */
3212 		*pl++ = lt;
3213 		*pl++ = rt;
3214 
3215 		//my_timer();
3216 
3217 		INTERNAL_TIMER_A( OPN->ST , cch[1] );
3218 	}
3219 	INTERNAL_TIMER_B(OPN->ST,length);
3220 
3221 }
3222 
3223 
YM2610Update(int * p)3224 void YM2610Update(int *p)
3225 {
3226 	int i;
3227 	s16 *buffer = (s16 *)p;
3228 	s16 lt, rt;
3229 
3230 	switch (/*option_samplerate*/0)
3231 	{
3232 	case 0:
3233 		YM2610Update_stream(SOUND_SAMPLES >> 2);
3234 		for (i = 0; i < SOUND_SAMPLES >> 2; i++)
3235 		{
3236 			lt = mixing_buffer[0][i];
3237 			rt = mixing_buffer[1][i];
3238 			*buffer++ = lt;
3239 			*buffer++ = rt;
3240 			*buffer++ = lt;
3241 			*buffer++ = rt;
3242 			*buffer++ = lt;
3243 			*buffer++ = rt;
3244 			*buffer++ = lt;
3245 			*buffer++ = rt;
3246 		}
3247 		break;
3248 
3249 	case 1:
3250 		YM2610Update_stream(SOUND_SAMPLES >> 1);
3251 		for (i = 0; i < SOUND_SAMPLES >> 1; i++)
3252 		{
3253 			lt = mixing_buffer[0][i];
3254 			rt = mixing_buffer[1][i];
3255 			*buffer++ = lt;
3256 			*buffer++ = rt;
3257 			*buffer++ = lt;
3258 			*buffer++ = rt;
3259 		}
3260 		break;
3261 
3262 	case 2:
3263 		YM2610Update_stream(SOUND_SAMPLES);
3264 		for (i = 0; i < SOUND_SAMPLES; i++)
3265 		{
3266 			*buffer++ = mixing_buffer[0][i];
3267 			*buffer++ = mixing_buffer[1][i];
3268 		}
3269 		break;
3270 	}
3271 }
3272 
3273 #ifdef SOUND_TEST
3274 static int stream_pos;
3275 static int samples_left;
3276 
YM2610Update_SoundTest(int p)3277 void YM2610Update_SoundTest(int p)
3278 {
3279 	int i, length;
3280 	s16 *buffer = (s16 *)p;
3281 
3282 	length = SOUND_SAMPLES;
3283 
3284 	if (samples_left)
3285 	{
3286 		for (i = 0; i < samples_left; i++)
3287 		{
3288 			*buffer++ = mixing_buffer[0][stream_pos];
3289 			*buffer++ = mixing_buffer[1][stream_pos];
3290 			stream_pos++;
3291 			length--;
3292 		}
3293 	}
3294 
3295 next_frame:
3296 	timer_update_subcpu();
3297 	YM2610Update_stream(736);
3298 	samples_left = 736;
3299 	stream_pos = 0;
3300 
3301 	for (i = 0; i < 736; i++)
3302 	{
3303 		*buffer++ = mixing_buffer[0][stream_pos];
3304 		*buffer++ = mixing_buffer[1][stream_pos];
3305 		stream_pos++;
3306 		samples_left--;
3307 
3308 		if (--length == 0) break;
3309 	}
3310 	if (length) goto next_frame;
3311 }
3312 #endif
3313 
3314 
ym2610_mkstate(gzFile * gzf,int mode)3315 void ym2610_mkstate(gzFile *gzf,int mode) {
3316 	mkstate_data(gzf, &YM2610, sizeof (YM2610), mode);
3317 }
3318 
3319 #ifdef SAVE_STATE
3320 
STATE_SAVE(ym2610)3321 STATE_SAVE( ym2610 )
3322 {
3323 	int slot, ch;
3324 
3325 	state_save_byte(YM2610.regs, 512);
3326 
3327 	state_save_double(&YM2610.OPN.ST.BusyExpire, 1);
3328 	state_save_byte(&YM2610.OPN.ST.address, 1);
3329 	state_save_byte(&YM2610.OPN.ST.irq, 1);
3330 	state_save_byte(&YM2610.OPN.ST.irqmask, 1);
3331 	state_save_byte(&YM2610.OPN.ST.status, 1);
3332 	state_save_long(&YM2610.OPN.ST.mode, 1);
3333 	state_save_byte(&YM2610.OPN.ST.prescaler_sel, 1);
3334 	state_save_byte(&YM2610.OPN.ST.fn_h, 1);
3335 	state_save_long(&YM2610.OPN.ST.TA, 1);
3336 	state_save_long(&YM2610.OPN.ST.TAC, 1);
3337 	state_save_byte(&YM2610.OPN.ST.TB, 1);
3338 	state_save_long(&YM2610.OPN.ST.TBC, 1);
3339 
3340 	for (ch = 0; ch < 6; ch++)
3341 	{
3342 		state_save_long(YM2610.CH[ch].op1_out, 2);
3343 		state_save_long(&YM2610.CH[ch].fc, 1);
3344 
3345 		for (slot = 0; slot < 4; slot++)
3346 		{
3347 			FM_SLOT *SLOT = &YM2610.CH[ch].SLOT[slot];
3348 
3349 			state_save_long(&SLOT->phase, 1);
3350 			state_save_byte(&SLOT->state, 1);
3351 			state_save_long(&SLOT->volume, 1);
3352 		}
3353 	}
3354 
3355 	state_save_long(YM2610.OPN.SL3.fc, 3);
3356 	state_save_byte(&YM2610.OPN.SL3.fn_h, 1);
3357 	state_save_byte(YM2610.OPN.SL3.kcode, 3);
3358 
3359 	state_save_byte(&YM2610.addr_A1, 1);
3360 	state_save_byte(&YM2610.adpcm_arrivedEndAddress, 1);
3361 
3362 	for (ch = 0; ch < 6; ch++)
3363 	{
3364 		state_save_byte(&YM2610.adpcma[ch].flag, 1);
3365 		state_save_byte(&YM2610.adpcma[ch].now_data, 1);
3366 		state_save_long(&YM2610.adpcma[ch].now_addr, 1);
3367 		state_save_long(&YM2610.adpcma[ch].now_step, 1);
3368 		state_save_long(&YM2610.adpcma[ch].adpcma_acc, 1);
3369 		state_save_long(&YM2610.adpcma[ch].adpcma_step, 1);
3370 		state_save_long(&YM2610.adpcma[ch].adpcma_out, 1);
3371 	}
3372 
3373 	state_save_byte(&YM2610.adpcmb.portstate, 1);
3374 	state_save_long(&YM2610.adpcmb.now_addr, 1);
3375 	state_save_long(&YM2610.adpcmb.now_step, 1);
3376 	state_save_long(&YM2610.adpcmb.acc, 1);
3377 	state_save_long(&YM2610.adpcmb.prev_acc, 1);
3378 	state_save_long(&YM2610.adpcmb.adpcmd, 1);
3379 	state_save_long(&YM2610.adpcmb.adpcml, 1);
3380 
3381 	state_save_long(&option_samplerate, 1);
3382 }
3383 
STATE_LOAD(ym2610)3384 STATE_LOAD( ym2610 )
3385 {
3386 	int slot, ch, r;
3387 
3388 	state_load_byte(YM2610.regs, 512);
3389 
3390 	state_load_double(&YM2610.OPN.ST.BusyExpire, 1);
3391 	state_load_byte(&YM2610.OPN.ST.address, 1);
3392 	state_load_byte(&YM2610.OPN.ST.irq, 1);
3393 	state_load_byte(&YM2610.OPN.ST.irqmask, 1);
3394 	state_load_byte(&YM2610.OPN.ST.status, 1);
3395 	state_load_long(&YM2610.OPN.ST.mode, 1);
3396 	state_load_byte(&YM2610.OPN.ST.prescaler_sel, 1);
3397 	state_load_byte(&YM2610.OPN.ST.fn_h, 1);
3398 	state_load_long(&YM2610.OPN.ST.TA, 1);
3399 	state_load_long(&YM2610.OPN.ST.TAC, 1);
3400 	state_load_byte(&YM2610.OPN.ST.TB, 1);
3401 	state_load_long(&YM2610.OPN.ST.TBC, 1);
3402 
3403 	for (ch = 0; ch < 6; ch++)
3404 	{
3405 		state_load_long(YM2610.CH[ch].op1_out, 2);
3406 		state_load_long(&YM2610.CH[ch].fc, 1);
3407 
3408 		for (slot = 0; slot < 4; slot++)
3409 		{
3410 			FM_SLOT *SLOT = &YM2610.CH[ch].SLOT[slot];
3411 
3412 			state_load_long(&SLOT->phase, 1);
3413 			state_load_byte(&SLOT->state, 1);
3414 			state_load_long(&SLOT->volume, 1);
3415 		}
3416 	}
3417 
3418 	state_load_long(YM2610.OPN.SL3.fc, 3);
3419 	state_load_byte(&YM2610.OPN.SL3.fn_h, 1);
3420 	state_load_byte(YM2610.OPN.SL3.kcode, 3);
3421 
3422 	state_load_byte(&YM2610.addr_A1, 1);
3423 	state_load_byte(&YM2610.adpcm_arrivedEndAddress, 1);
3424 
3425 	for (ch = 0; ch < 6; ch++)
3426 	{
3427 		state_load_byte(&YM2610.adpcma[ch].flag, 1);
3428 		state_load_byte(&YM2610.adpcma[ch].now_data, 1);
3429 		state_load_long(&YM2610.adpcma[ch].now_addr, 1);
3430 		state_load_long(&YM2610.adpcma[ch].now_step, 1);
3431 		state_load_long(&YM2610.adpcma[ch].adpcma_acc, 1);
3432 		state_load_long(&YM2610.adpcma[ch].adpcma_step, 1);
3433 		state_load_long(&YM2610.adpcma[ch].adpcma_out, 1);
3434 	}
3435 
3436 	state_load_byte(&YM2610.adpcmb.portstate, 1);
3437 	state_load_long(&YM2610.adpcmb.now_addr, 1);
3438 	state_load_long(&YM2610.adpcmb.now_step, 1);
3439 	state_load_long(&YM2610.adpcmb.acc, 1);
3440 	state_load_long(&YM2610.adpcmb.prev_acc, 1);
3441 	state_load_long(&YM2610.adpcmb.adpcmd, 1);
3442 	state_load_long(&YM2610.adpcmb.adpcml, 1);
3443 
3444 	state_load_long(&option_samplerate, 1);
3445 
3446 	for (r = 0; r < 16; r++)
3447 	{
3448 		SSG_write(0, r);
3449 		SSG_write(1, YM2610.regs[r]);
3450 	}
3451 
3452 	for (r = 0x30; r <0x9e; r++)
3453 	{
3454 		if ((r & 3) != 3)
3455 		{
3456 			OPNWriteReg(&YM2610.OPN, r, YM2610.regs[r]);
3457 			OPNWriteReg(&YM2610.OPN, r | 0x100, YM2610.regs[r | 0x100]);
3458 		}
3459 	}
3460 
3461 	for (r = 0xb0; r < 0xb6; r++)
3462 	{
3463 		if ((r & 3) != 3)
3464 		{
3465 			OPNWriteReg(&YM2610.OPN, r, YM2610.regs[r]);
3466 			OPNWriteReg(&YM2610.OPN, r | 0x100, YM2610.regs[r | 0x100]);
3467 		}
3468 	}
3469 
3470 	OPNB_ADPCMA_write(0x101, YM2610.regs[0x101]);
3471 	for (r = 0; r < 6; r++)
3472 	{
3473 		OPNB_ADPCMA_write(r + 0x108, YM2610.regs[r + 0x108]);
3474 		OPNB_ADPCMA_write(r + 0x110, YM2610.regs[r + 0x110]);
3475 		OPNB_ADPCMA_write(r + 0x118, YM2610.regs[r + 0x118]);
3476 		OPNB_ADPCMA_write(r + 0x120, YM2610.regs[r + 0x120]);
3477 		OPNB_ADPCMA_write(r + 0x128, YM2610.regs[r + 0x128]);
3478 	}
3479 
3480 	YM2610.adpcmb.volume = 0;
3481 
3482 	for (r = 1; r < 16; r++)
3483 		OPNB_ADPCMB_write(&YM2610.adpcmb, r + 0x10, YM2610.regs[r + 0x10]);
3484 
3485 	if (pcmbufB)
3486 		YM2610.adpcmb.now_data = *(pcmbufB + (YM2610.adpcmb.now_addr >> 1));
3487 }
3488 
3489 #endif /* SAVE_STATE */
3490