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