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