1 /*
2 **
3 ** File: ym2413.c - software implementation of YM2413
4 **                  FM sound generator type OPLL
5 **
6 ** Copyright (C) 2002 Jarek Burczynski
7 **
8 ** Version 1.0
9 **
10 
11 
12 to do:
13 
14 - make sure of the sinus amplitude bits
15 
16 - make sure of the EG resolution bits (looks like the biggest
17   modulation index generated by the modulator is 123, 124 = no modulation)
18 - find proper algorithm for attack phase of EG
19 
20 - tune up instruments ROM
21 
22 - support sample replay in test mode (it is NOT as simple as setting bit 0
23   in register 0x0f and using register 0x10 for sample data).
24   Which games use this feature ?
25 
26 
27 */
28 
29 #include "driver.h"
30 #include "state.h"
31 #include "ym2413.h"
32 
33 #ifndef MAME_INLINE
34 #ifndef MAME_INLINE
35 #define MAME_INLINE static inline
36 #endif
37 #endif
38 
39 #ifndef PI
40 #define PI 3.14159265358979323846
41 #endif
42 
43 /* output final shift */
44 #if (SAMPLE_BITS==16)
45 	#define FINAL_SH	(0)
46 	#define MAXOUT		(+32767)
47 	#define MINOUT		(-32768)
48 #else
49 	#define FINAL_SH	(8)
50 	#define MAXOUT		(+127)
51 	#define MINOUT		(-128)
52 #endif
53 
54 
55 #define FREQ_SH			16  /* 16.16 fixed point (frequency calculations) */
56 #define EG_SH			16  /* 16.16 fixed point (EG timing)              */
57 #define LFO_SH			24  /*  8.24 fixed point (LFO calculations)       */
58 
59 #define FREQ_MASK		((1<<FREQ_SH)-1)
60 
61 /* envelope output entries */
62 #define ENV_BITS		10
63 #define ENV_LEN			(1<<ENV_BITS)
64 #define ENV_STEP		(128.0/ENV_LEN)
65 
66 #define MAX_ATT_INDEX	((1<<(ENV_BITS-2))-1) /*255*/
67 #define MIN_ATT_INDEX	(0)
68 
69 /* sinwave entries */
70 #define SIN_BITS		10
71 #define SIN_LEN			(1<<SIN_BITS)
72 #define SIN_MASK		(SIN_LEN-1)
73 
74 #define TL_RES_LEN		(256)	/* 8 bits addressing (real chip) */
75 
76 
77 
78 /* register number to channel number , slot offset */
79 #define SLOT1 0
80 #define SLOT2 1
81 
82 /* Envelope Generator phases */
83 
84 #define EG_DMP			5
85 #define EG_ATT			4
86 #define EG_DEC			3
87 #define EG_SUS			2
88 #define EG_REL			1
89 #define EG_OFF			0
90 
91 
92 /* save output as raw 16-bit sample */
93 
94 //#define SAVE_SAMPLE
95 
96 #ifdef SAVE_SAMPLE
acc_calc(signed int value)97 MAME_INLINE signed int acc_calc(signed int value)
98 {
99 	if (value>=0)
100 	{
101 		if (value < 0x0200)
102 			return (value & ~0);
103 		if (value < 0x0400)
104 			return (value & ~1);
105 		if (value < 0x0800)
106 			return (value & ~3);
107 		if (value < 0x1000)
108 			return (value & ~7);
109 		if (value < 0x2000)
110 			return (value & ~15);
111 		if (value < 0x4000)
112 			return (value & ~31);
113 		return (value & ~63);
114 	}
115 	/*else value < 0*/
116 	if (value > -0x0200)
117 		return (~abs(value) & ~0);
118 	if (value > -0x0400)
119 		return (~abs(value) & ~1);
120 	if (value > -0x0800)
121 		return (~abs(value) & ~3);
122 	if (value > -0x1000)
123 		return (~abs(value) & ~7);
124 	if (value > -0x2000)
125 		return (~abs(value) & ~15);
126 	if (value > -0x4000)
127 		return (~abs(value) & ~31);
128 	return (~abs(value) & ~63);
129 }
130 
131 
132 static FILE *sample[1];
133 	#if 0	/*save to MONO file */
134 		#define SAVE_ALL_CHANNELS \
135 		{	signed int pom = acc_calc(mo); \
136 			fputc((unsigned short)pom&0xff,sample[0]); \
137 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
138 		}
139 	#else	/*save to STEREO file */
140 		#define SAVE_ALL_CHANNELS \
141 		{	signed int pom = mo; \
142 			fputc((unsigned short)pom&0xff,sample[0]); \
143 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
144 			pom = ro; \
145 			fputc((unsigned short)pom&0xff,sample[0]); \
146 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
147 		}
148 		#define SAVE_SEPARATE_CHANNEL(j) \
149 		{	signed int pom = outchan; \
150 			fputc((unsigned short)pom&0xff,sample[0]); \
151 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
152 			pom = chip->instvol_r[j]>>4; \
153 			fputc((unsigned short)pom&0xff,sample[0]); \
154 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
155 		}
156 	#endif
157 #endif
158 
159 /*#define LOG_CYM_FILE*/
160 #ifdef LOG_CYM_FILE
161 	FILE * cymfile = NULL;
162 #endif
163 
164 
165 
166 
167 typedef struct{
168 	UINT32	ar;			/* attack rate: AR<<2			*/
169 	UINT32	dr;			/* decay rate:  DR<<2			*/
170 	UINT32	rr;			/* release rate:RR<<2			*/
171 	UINT8	KSR;		/* key scale rate				*/
172 	UINT8	ksl;		/* keyscale level				*/
173 	UINT8	ksr;		/* key scale rate: kcode>>KSR	*/
174 	UINT8	mul;		/* multiple: mul_tab[ML]		*/
175 
176 	/* Phase Generator */
177 	UINT32	phase;		/* frequency counter			*/
178 	UINT32	freq;		/* frequency counter step		*/
179 	UINT8   fb_shift;	/* feedback shift value			*/
180 	INT32   op1_out[2];	/* slot1 output for feedback	*/
181 
182 	/* Envelope Generator */
183 	UINT8	eg_type;	/* percussive/nonpercussive mode*/
184 	UINT8	state;		/* phase type					*/
185 	UINT32	TL;			/* total level: TL << 2			*/
186 	INT32	TLL;		/* adjusted now TL				*/
187 	INT32	volume;		/* envelope counter				*/
188 	UINT32	sl;			/* sustain level: sl_tab[SL]	*/
189 
190 	UINT8	eg_sh_dp;	/* (dump state)					*/
191 	UINT8	eg_sel_dp;	/* (dump state)					*/
192 	UINT8	eg_sh_ar;	/* (attack state)				*/
193 	UINT8	eg_sel_ar;	/* (attack state)				*/
194 	UINT8	eg_sh_dr;	/* (decay state)				*/
195 	UINT8	eg_sel_dr;	/* (decay state)				*/
196 	UINT8	eg_sh_rr;	/* (release state for non-perc.)*/
197 	UINT8	eg_sel_rr;	/* (release state for non-perc.)*/
198 	UINT8	eg_sh_rs;	/* (release state for perc.mode)*/
199 	UINT8	eg_sel_rs;	/* (release state for perc.mode)*/
200 
201 	UINT32	key;		/* 0 = KEY OFF, >0 = KEY ON		*/
202 
203 	/* LFO */
204 	UINT32	AMmask;		/* LFO Amplitude Modulation enable mask */
205 	UINT8	vib;		/* LFO Phase Modulation enable flag (active high)*/
206 
207 	/* waveform select */
208 	UINT32 wavetable;
209 } YM2413_OPLL_SLOT;
210 
211 typedef struct{
212     YM2413_OPLL_SLOT SLOT[2];
213 	/* phase generator state */
214 	UINT32  block_fnum;	/* block+fnum					*/
215 	UINT32  fc;			/* Freq. freqement base			*/
216 	UINT32  ksl_base;	/* KeyScaleLevel Base step		*/
217 	UINT8   kcode;		/* key code (for key scaling)	*/
218 	UINT8   sus;		/* sus on/off (release speed in percussive mode)*/
219 } YM2413_OPLL_CH;
220 
221 /* chip state */
222 typedef struct {
223     YM2413_OPLL_CH P_CH[9];                /* OPLL chips have 9 channels*/
224 	UINT8	instvol_r[9];			/* instrument/volume (or volume/volume in percussive mode)*/
225 
226 	UINT32	eg_cnt;					/* global envelope generator counter	*/
227 	UINT32	eg_timer;				/* global envelope generator counter works at frequency = chipclock/72 */
228 	UINT32	eg_timer_add;			/* step of eg_timer						*/
229 	UINT32	eg_timer_overflow;		/* envelope generator timer overlfows every 1 sample (on real chip) */
230 
231 	UINT8	rhythm;					/* Rhythm mode					*/
232 
233 	/* LFO */
234 	UINT32	lfo_am_cnt;
235 	UINT32	lfo_am_inc;
236 	UINT32	lfo_pm_cnt;
237 	UINT32	lfo_pm_inc;
238 
239 	UINT32	noise_rng;				/* 23 bit noise shift register	*/
240 	UINT32	noise_p;				/* current noise 'phase'		*/
241 	UINT32	noise_f;				/* current noise period			*/
242 
243 
244 /* instrument settings */
245 /*
246 	0-user instrument
247 	1-15 - fixed instruments
248 	16 -bass drum settings
249 	17,18 - other percussion instruments
250 */
251 	UINT8 inst_tab[19][8];
252 
253 	/* external event callback handlers */
254 	OPLL_UPDATEHANDLER UpdateHandler; /* stream update handler		*/
255 	int UpdateParam;				/* stream update parameter		*/
256 
257 	UINT32	fn_tab[1024];			/* fnumber->increment counter	*/
258 
259 	UINT8 address;					/* address register				*/
260 	UINT8 status;					/* status flag					*/
261 
262 	int clock;						/* master clock  (Hz)			*/
263 	int rate;						/* sampling rate (Hz)			*/
264 	double freqbase;				/* frequency base				*/
265 } YM2413;
266 
267 /* key scale level */
268 /* table is 3dB/octave, DV converts this into 6dB/octave */
269 /* 0.1875 is bit 0 weight of the envelope counter (volume) expressed in the 'decibel' scale */
270 #define DV (0.1875/1.0)
271 static const UINT32 ksl_tab[8*16]=
272 {
273 	/* OCT 0 */
274 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
275 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
276 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
277 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
278 	/* OCT 1 */
279 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
280 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
281 	 0.000/DV, 0.750/DV, 1.125/DV, 1.500/DV,
282 	 1.875/DV, 2.250/DV, 2.625/DV, 3.000/DV,
283 	/* OCT 2 */
284 	 0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
285 	 0.000/DV, 1.125/DV, 1.875/DV, 2.625/DV,
286 	 3.000/DV, 3.750/DV, 4.125/DV, 4.500/DV,
287 	 4.875/DV, 5.250/DV, 5.625/DV, 6.000/DV,
288 	/* OCT 3 */
289 	 0.000/DV, 0.000/DV, 0.000/DV, 1.875/DV,
290 	 3.000/DV, 4.125/DV, 4.875/DV, 5.625/DV,
291 	 6.000/DV, 6.750/DV, 7.125/DV, 7.500/DV,
292 	 7.875/DV, 8.250/DV, 8.625/DV, 9.000/DV,
293 	/* OCT 4 */
294 	 0.000/DV, 0.000/DV, 3.000/DV, 4.875/DV,
295 	 6.000/DV, 7.125/DV, 7.875/DV, 8.625/DV,
296 	 9.000/DV, 9.750/DV,10.125/DV,10.500/DV,
297 	10.875/DV,11.250/DV,11.625/DV,12.000/DV,
298 	/* OCT 5 */
299 	 0.000/DV, 3.000/DV, 6.000/DV, 7.875/DV,
300 	 9.000/DV,10.125/DV,10.875/DV,11.625/DV,
301 	12.000/DV,12.750/DV,13.125/DV,13.500/DV,
302 	13.875/DV,14.250/DV,14.625/DV,15.000/DV,
303 	/* OCT 6 */
304 	 0.000/DV, 6.000/DV, 9.000/DV,10.875/DV,
305 	12.000/DV,13.125/DV,13.875/DV,14.625/DV,
306 	15.000/DV,15.750/DV,16.125/DV,16.500/DV,
307 	16.875/DV,17.250/DV,17.625/DV,18.000/DV,
308 	/* OCT 7 */
309 	 0.000/DV, 9.000/DV,12.000/DV,13.875/DV,
310 	15.000/DV,16.125/DV,16.875/DV,17.625/DV,
311 	18.000/DV,18.750/DV,19.125/DV,19.500/DV,
312 	19.875/DV,20.250/DV,20.625/DV,21.000/DV
313 };
314 #undef DV
315 
316 /* sustain level table (3dB per step) */
317 /* 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,45 (dB)*/
318 #define SC(db) (UINT32) ( db * (1.0/ENV_STEP) )
319 static const UINT32 sl_tab[16]={
320  SC( 0),SC( 1),SC( 2),SC(3 ),SC(4 ),SC(5 ),SC(6 ),SC( 7),
321  SC( 8),SC( 9),SC(10),SC(11),SC(12),SC(13),SC(14),SC(15)
322 };
323 #undef SC
324 
325 
326 #define RATE_STEPS (8)
327 static const unsigned char eg_inc[15*RATE_STEPS]={
328 
329 /*cycle:0 1  2 3  4 5  6 7*/
330 
331 /* 0 */ 0,1, 0,1, 0,1, 0,1, /* rates 00..12 0 (increment by 0 or 1) */
332 /* 1 */ 0,1, 0,1, 1,1, 0,1, /* rates 00..12 1 */
333 /* 2 */ 0,1, 1,1, 0,1, 1,1, /* rates 00..12 2 */
334 /* 3 */ 0,1, 1,1, 1,1, 1,1, /* rates 00..12 3 */
335 
336 /* 4 */ 1,1, 1,1, 1,1, 1,1, /* rate 13 0 (increment by 1) */
337 /* 5 */ 1,1, 1,2, 1,1, 1,2, /* rate 13 1 */
338 /* 6 */ 1,2, 1,2, 1,2, 1,2, /* rate 13 2 */
339 /* 7 */ 1,2, 2,2, 1,2, 2,2, /* rate 13 3 */
340 
341 /* 8 */ 2,2, 2,2, 2,2, 2,2, /* rate 14 0 (increment by 2) */
342 /* 9 */ 2,2, 2,4, 2,2, 2,4, /* rate 14 1 */
343 /*10 */ 2,4, 2,4, 2,4, 2,4, /* rate 14 2 */
344 /*11 */ 2,4, 4,4, 2,4, 4,4, /* rate 14 3 */
345 
346 /*12 */ 4,4, 4,4, 4,4, 4,4, /* rates 15 0, 15 1, 15 2, 15 3 (increment by 4) */
347 /*13 */ 8,8, 8,8, 8,8, 8,8, /* rates 15 2, 15 3 for attack */
348 /*14 */ 0,0, 0,0, 0,0, 0,0, /* infinity rates for attack and decay(s) */
349 };
350 
351 
352 #define O(a) (a*RATE_STEPS)
353 
354 /*note that there is no O(13) in this table - it's directly in the code */
355 static const unsigned char eg_rate_select[16+64+16]={	/* Envelope Generator rates (16 + 64 rates + 16 RKS) */
356 /* 16 infinite time rates */
357 O(14),O(14),O(14),O(14),O(14),O(14),O(14),O(14),
358 O(14),O(14),O(14),O(14),O(14),O(14),O(14),O(14),
359 
360 /* rates 00-12 */
361 O( 0),O( 1),O( 2),O( 3),
362 O( 0),O( 1),O( 2),O( 3),
363 O( 0),O( 1),O( 2),O( 3),
364 O( 0),O( 1),O( 2),O( 3),
365 O( 0),O( 1),O( 2),O( 3),
366 O( 0),O( 1),O( 2),O( 3),
367 O( 0),O( 1),O( 2),O( 3),
368 O( 0),O( 1),O( 2),O( 3),
369 O( 0),O( 1),O( 2),O( 3),
370 O( 0),O( 1),O( 2),O( 3),
371 O( 0),O( 1),O( 2),O( 3),
372 O( 0),O( 1),O( 2),O( 3),
373 O( 0),O( 1),O( 2),O( 3),
374 
375 /* rate 13 */
376 O( 4),O( 5),O( 6),O( 7),
377 
378 /* rate 14 */
379 O( 8),O( 9),O(10),O(11),
380 
381 /* rate 15 */
382 O(12),O(12),O(12),O(12),
383 
384 /* 16 dummy rates (same as 15 3) */
385 O(12),O(12),O(12),O(12),O(12),O(12),O(12),O(12),
386 O(12),O(12),O(12),O(12),O(12),O(12),O(12),O(12),
387 
388 };
389 #undef O
390 
391 /*rate  0,    1,    2,    3,    4,   5,   6,   7,  8,  9, 10, 11, 12, 13, 14, 15 */
392 /*shift 13,   12,   11,   10,   9,   8,   7,   6,  5,  4,  3,  2,  1,  0,  0,  0 */
393 /*mask  8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7,  3,  1,  0,  0,  0 */
394 
395 #define O(a) (a*1)
396 static const unsigned char eg_rate_shift[16+64+16]={	/* Envelope Generator counter shifts (16 + 64 rates + 16 RKS) */
397 /* 16 infinite time rates */
398 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
399 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
400 
401 /* rates 00-12 */
402 O(13),O(13),O(13),O(13),
403 O(12),O(12),O(12),O(12),
404 O(11),O(11),O(11),O(11),
405 O(10),O(10),O(10),O(10),
406 O( 9),O( 9),O( 9),O( 9),
407 O( 8),O( 8),O( 8),O( 8),
408 O( 7),O( 7),O( 7),O( 7),
409 O( 6),O( 6),O( 6),O( 6),
410 O( 5),O( 5),O( 5),O( 5),
411 O( 4),O( 4),O( 4),O( 4),
412 O( 3),O( 3),O( 3),O( 3),
413 O( 2),O( 2),O( 2),O( 2),
414 O( 1),O( 1),O( 1),O( 1),
415 
416 /* rate 13 */
417 O( 0),O( 0),O( 0),O( 0),
418 
419 /* rate 14 */
420 O( 0),O( 0),O( 0),O( 0),
421 
422 /* rate 15 */
423 O( 0),O( 0),O( 0),O( 0),
424 
425 /* 16 dummy rates (same as 15 3) */
426 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
427 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
428 
429 };
430 #undef O
431 
432 
433 /* multiple table */
434 #define ML 2
435 static const UINT8 mul_tab[16]= {
436 /* 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,10,12,12,15,15 */
437    0.50*ML, 1.00*ML, 2.00*ML, 3.00*ML, 4.00*ML, 5.00*ML, 6.00*ML, 7.00*ML,
438    8.00*ML, 9.00*ML,10.00*ML,10.00*ML,12.00*ML,12.00*ML,15.00*ML,15.00*ML
439 };
440 #undef ML
441 
442 /*	TL_TAB_LEN is calculated as:
443 *	11 - sinus amplitude bits     (Y axis)
444 *	2  - sinus sign bit           (Y axis)
445 *	TL_RES_LEN - sinus resolution (X axis)
446 */
447 #define TL_TAB_LEN (11*2*TL_RES_LEN)
448 static signed int tl_tab[TL_TAB_LEN];
449 
450 #define ENV_QUIET		(TL_TAB_LEN>>5)
451 
452 /* sin waveform table in 'decibel' scale */
453 /* two waveforms on OPLL type chips */
454 static unsigned int sin_tab[SIN_LEN * 2];
455 
456 
457 /* LFO Amplitude Modulation table (verified on real YM3812)
458    27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples
459 
460    Length: 210 elements.
461 
462 	Each of the elements has to be repeated
463 	exactly 64 times (on 64 consecutive samples).
464 	The whole table takes: 64 * 210 = 13440 samples.
465 
466 We use data>>1, until we find what it really is on real chip...
467 
468 */
469 
470 #define LFO_AM_TAB_ELEMENTS 210
471 
472 static const UINT8 lfo_am_table[LFO_AM_TAB_ELEMENTS] = {
473 0,0,0,0,0,0,0,
474 1,1,1,1,
475 2,2,2,2,
476 3,3,3,3,
477 4,4,4,4,
478 5,5,5,5,
479 6,6,6,6,
480 7,7,7,7,
481 8,8,8,8,
482 9,9,9,9,
483 10,10,10,10,
484 11,11,11,11,
485 12,12,12,12,
486 13,13,13,13,
487 14,14,14,14,
488 15,15,15,15,
489 16,16,16,16,
490 17,17,17,17,
491 18,18,18,18,
492 19,19,19,19,
493 20,20,20,20,
494 21,21,21,21,
495 22,22,22,22,
496 23,23,23,23,
497 24,24,24,24,
498 25,25,25,25,
499 26,26,26,
500 25,25,25,25,
501 24,24,24,24,
502 23,23,23,23,
503 22,22,22,22,
504 21,21,21,21,
505 20,20,20,20,
506 19,19,19,19,
507 18,18,18,18,
508 17,17,17,17,
509 16,16,16,16,
510 15,15,15,15,
511 14,14,14,14,
512 13,13,13,13,
513 12,12,12,12,
514 11,11,11,11,
515 10,10,10,10,
516 9,9,9,9,
517 8,8,8,8,
518 7,7,7,7,
519 6,6,6,6,
520 5,5,5,5,
521 4,4,4,4,
522 3,3,3,3,
523 2,2,2,2,
524 1,1,1,1
525 };
526 
527 /* LFO Phase Modulation table (verified on real YM2413) */
528 static const INT8 lfo_pm_table[8*8] = {
529 
530 /* FNUM2/FNUM = 0 00xxxxxx (0x0000) */
531 0, 0, 0, 0, 0, 0, 0, 0,
532 
533 /* FNUM2/FNUM = 0 01xxxxxx (0x0040) */
534 1, 0, 0, 0,-1, 0, 0, 0,
535 
536 /* FNUM2/FNUM = 0 10xxxxxx (0x0080) */
537 2, 1, 0,-1,-2,-1, 0, 1,
538 
539 /* FNUM2/FNUM = 0 11xxxxxx (0x00C0) */
540 3, 1, 0,-1,-3,-1, 0, 1,
541 
542 /* FNUM2/FNUM = 1 00xxxxxx (0x0100) */
543 4, 2, 0,-2,-4,-2, 0, 2,
544 
545 /* FNUM2/FNUM = 1 01xxxxxx (0x0140) */
546 5, 2, 0,-2,-5,-2, 0, 2,
547 
548 /* FNUM2/FNUM = 1 10xxxxxx (0x0180) */
549 6, 3, 0,-3,-6,-3, 0, 3,
550 
551 /* FNUM2/FNUM = 1 11xxxxxx (0x01C0) */
552 7, 3, 0,-3,-7,-3, 0, 3,
553 };
554 
555 
556 
557 
558 
559 
560 /* This is not 100% perfect yet but very close */
561 /*
562  - multi parameters are 100% correct (instruments and drums)
563  - LFO PM and AM enable are 100% correct
564  - waveform DC and DM select are 100% correct
565 */
566 
567 static unsigned char table[19][8] = {
568 /* MULT  MULT modTL DcDmFb AR/DR AR/DR SL/RR SL/RR */
569 /*   0     1     2     3     4     5     6    7    */
570   {0x49, 0x4c, 0x4c, 0x12, 0x00, 0x00, 0x00, 0x00 },	//0
571 
572   {0x61, 0x61, 0x1e, 0x17, 0xf0, 0x78, 0x00, 0x17 },	//1
573   {0x13, 0x41, 0x1e, 0x0d, 0xd7, 0xf7, 0x13, 0x13 },	//2
574   {0x13, 0x01, 0x99, 0x04, 0xf2, 0xf4, 0x11, 0x23 },	//3
575   {0x21, 0x61, 0x1b, 0x07, 0xaf, 0x64, 0x40, 0x27 },	//4
576 
577 //{0x22, 0x21, 0x1e, 0x09, 0xf0, 0x76, 0x08, 0x28 },	//5
578   {0x22, 0x21, 0x1e, 0x06, 0xf0, 0x75, 0x08, 0x18 },	//5
579 
580 //{0x31, 0x22, 0x16, 0x09, 0x90, 0x7f, 0x00, 0x08 },	//6
581   {0x31, 0x22, 0x16, 0x05, 0x90, 0x71, 0x00, 0x13 },	//6
582 
583   {0x21, 0x61, 0x1d, 0x07, 0x82, 0x80, 0x10, 0x17 },	//7
584   {0x23, 0x21, 0x2d, 0x16, 0xc0, 0x70, 0x07, 0x07 },	//8
585   {0x61, 0x61, 0x1b, 0x06, 0x64, 0x65, 0x10, 0x17 },	//9
586 
587 //{0x61, 0x61, 0x0c, 0x08, 0x85, 0xa0, 0x79, 0x07 },	//A
588   {0x61, 0x61, 0x0c, 0x18, 0x85, 0xf0, 0x70, 0x07 },	//A
589 
590   {0x23, 0x01, 0x07, 0x11, 0xf0, 0xa4, 0x00, 0x22 },	//B
591   {0x97, 0xc1, 0x24, 0x07, 0xff, 0xf8, 0x22, 0x12 },	//C
592 
593 //{0x61, 0x10, 0x0c, 0x08, 0xf2, 0xc4, 0x40, 0xc8 },	//D
594   {0x61, 0x10, 0x0c, 0x05, 0xf2, 0xf4, 0x40, 0x44 },	//D
595 
596   {0x01, 0x01, 0x55, 0x03, 0xf3, 0x92, 0xf3, 0xf3 },	//E
597   {0x61, 0x41, 0x89, 0x03, 0xf1, 0xf4, 0xf0, 0x13 },	//F
598 
599 /* drum instruments definitions */
600 /* MULTI MULTI modTL  xxx  AR/DR AR/DR SL/RR SL/RR */
601 /*   0     1     2     3     4     5     6    7    */
602   {0x01, 0x01, 0x16, 0x00, 0xfd, 0xf8, 0x2f, 0x6d },/* BD(multi verified, modTL verified, mod env - verified(close), carr. env verifed) */
603   {0x01, 0x01, 0x00, 0x00, 0xd8, 0xd8, 0xf9, 0xf8 },/* HH(multi verified), SD(multi not used) */
604   {0x05, 0x01, 0x00, 0x00, 0xf8, 0xba, 0x49, 0x55 },/* TOM(multi,env verified), TOP CYM(multi verified, env verified) */
605 };
606 
607 /* lock level of common table */
608 static int num_lock = 0;
609 
610 /* work table */
611 static void *cur_chip = NULL;	/* current chip pointer */
612 static YM2413_OPLL_SLOT *SLOT7_1,*SLOT7_2,*SLOT8_1,*SLOT8_2;
613 
614 static signed int output[2];
615 static signed int outchan;
616 
617 static UINT32	LFO_AM;
618 static INT32	LFO_PM;
619 
620 
limit(int val,int max,int min)621 MAME_INLINE int limit( int val, int max, int min ) {
622 	if ( val > max )
623 		val = max;
624 	else if ( val < min )
625 		val = min;
626 
627 	return val;
628 }
629 
630 
631 /* advance LFO to next sample */
advance_lfo(YM2413 * chip)632 MAME_INLINE void advance_lfo(YM2413 *chip)
633 {
634 	/* LFO */
635 	chip->lfo_am_cnt += chip->lfo_am_inc;
636 	if (chip->lfo_am_cnt >= (LFO_AM_TAB_ELEMENTS<<LFO_SH) )	/* lfo_am_table is 210 elements long */
637 		chip->lfo_am_cnt -= (LFO_AM_TAB_ELEMENTS<<LFO_SH);
638 
639 	LFO_AM = lfo_am_table[ chip->lfo_am_cnt >> LFO_SH ] >> 1;
640 
641 	chip->lfo_pm_cnt += chip->lfo_pm_inc;
642 	LFO_PM = (chip->lfo_pm_cnt>>LFO_SH) & 7;
643 }
644 
645 /* advance to next sample */
advance(YM2413 * chip)646 MAME_INLINE void advance(YM2413 *chip)
647 {
648     YM2413_OPLL_CH *CH;
649     YM2413_OPLL_SLOT *op;
650 	unsigned int i;
651 
652 //profiler_mark(PROFILER_USER3);
653 
654 	/* Envelope Generator */
655 	chip->eg_timer += chip->eg_timer_add;
656 
657 	while (chip->eg_timer >= chip->eg_timer_overflow)
658 	{
659 		chip->eg_timer -= chip->eg_timer_overflow;
660 
661 		chip->eg_cnt++;
662 
663 		for (i=0; i<9*2; i++)
664 		{
665 			CH  = &chip->P_CH[i/2];
666 
667 			op  = &CH->SLOT[i&1];
668 
669 			switch(op->state)
670 			{
671 
672 			case EG_DMP:		/* dump phase */
673 			/*dump phase is performed by both operators in each channel*/
674 			/*when CARRIER envelope gets down to zero level,
675 			**  phases in BOTH opearators are reset (at the same time ?)
676 			*/
677 				if ( !(chip->eg_cnt & ((1<<op->eg_sh_dp)-1) ) )
678 				{
679 					op->volume += eg_inc[op->eg_sel_dp + ((chip->eg_cnt>>op->eg_sh_dp)&7)];
680 
681 					if ( op->volume >= MAX_ATT_INDEX )
682 					{
683 						op->volume = MAX_ATT_INDEX;
684 						op->state = EG_ATT;
685 						/* restart Phase Generator  */
686 						op->phase = 0;
687 					}
688 				}
689 			break;
690 
691 			case EG_ATT:		/* attack phase */
692 				if ( !(chip->eg_cnt & ((1<<op->eg_sh_ar)-1) ) )
693 				{
694 					op->volume += (~op->volume *
695 	                        		           (eg_inc[op->eg_sel_ar + ((chip->eg_cnt>>op->eg_sh_ar)&7)])
696         			                          ) >>2;
697 
698 					if (op->volume <= MIN_ATT_INDEX)
699 					{
700 						op->volume = MIN_ATT_INDEX;
701 						op->state = EG_DEC;
702 					}
703 				}
704 			break;
705 
706 			case EG_DEC:	/* decay phase */
707 				if ( !(chip->eg_cnt & ((1<<op->eg_sh_dr)-1) ) )
708 				{
709 					op->volume += eg_inc[op->eg_sel_dr + ((chip->eg_cnt>>op->eg_sh_dr)&7)];
710 
711 					if ( op->volume >= op->sl )
712 						op->state = EG_SUS;
713 				}
714 			break;
715 
716 			case EG_SUS:	/* sustain phase */
717 				/* this is important behaviour:
718 				one can change percusive/non-percussive modes on the fly and
719 				the chip will remain in sustain phase - verified on real YM3812 */
720 
721 				if(op->eg_type)		/* non-percussive mode (sustained tone) */
722 				{
723 									/* do nothing */
724 				}
725 				else				/* percussive mode */
726 				{
727 					/* during sustain phase chip adds Release Rate (in percussive mode) */
728 					if ( !(chip->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
729 					{
730 						op->volume += eg_inc[op->eg_sel_rr + ((chip->eg_cnt>>op->eg_sh_rr)&7)];
731 
732 						if ( op->volume >= MAX_ATT_INDEX )
733 							op->volume = MAX_ATT_INDEX;
734 					}
735 					/* else do nothing in sustain phase */
736 				}
737 			break;
738 
739 			case EG_REL:	/* release phase */
740 			/* exclude modulators in melody channels from performing anything in this mode*/
741 			/* allowed are only carriers in melody mode and rhythm slots in rhythm mode */
742 
743 			/*This table shows which operators and on what conditions are allowed to perform EG_REL:
744 			(a) - always perform EG_REL
745 			(n) - never perform EG_REL
746 			(r) - perform EG_REL in Rhythm mode ONLY
747 				0: 0 (n),  1 (a)
748 				1: 2 (n),  3 (a)
749 				2: 4 (n),  5 (a)
750 				3: 6 (n),  7 (a)
751 				4: 8 (n),  9 (a)
752 				5: 10(n),  11(a)
753 				6: 12(r),  13(a)
754 				7: 14(r),  15(a)
755 				8: 16(r),  17(a)
756 			*/
757 				if ( (i&1) || ((chip->rhythm&0x20) && (i>=12)) )/* exclude modulators */
758 				{
759 					if(op->eg_type)		/* non-percussive mode (sustained tone) */
760 					/*this is correct: use RR when SUS = OFF*/
761 					/*and use RS when SUS = ON*/
762 					{
763 						if (CH->sus)
764 						{
765 							if ( !(chip->eg_cnt & ((1<<op->eg_sh_rs)-1) ) )
766 							{
767 								op->volume += eg_inc[op->eg_sel_rs + ((chip->eg_cnt>>op->eg_sh_rs)&7)];
768 								if ( op->volume >= MAX_ATT_INDEX )
769 								{
770 									op->volume = MAX_ATT_INDEX;
771 									op->state = EG_OFF;
772 								}
773 							}
774 						}
775 						else
776 						{
777 							if ( !(chip->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
778 							{
779 								op->volume += eg_inc[op->eg_sel_rr + ((chip->eg_cnt>>op->eg_sh_rr)&7)];
780 								if ( op->volume >= MAX_ATT_INDEX )
781 								{
782 									op->volume = MAX_ATT_INDEX;
783 									op->state = EG_OFF;
784 								}
785 							}
786 						}
787 					}
788 					else				/* percussive mode */
789 					{
790 						if ( !(chip->eg_cnt & ((1<<op->eg_sh_rs)-1) ) )
791 						{
792 							op->volume += eg_inc[op->eg_sel_rs + ((chip->eg_cnt>>op->eg_sh_rs)&7)];
793 							if ( op->volume >= MAX_ATT_INDEX )
794 							{
795 								op->volume = MAX_ATT_INDEX;
796 								op->state = EG_OFF;
797 							}
798 						}
799 					}
800 				}
801 			break;
802 
803 			default:
804 			break;
805 			}
806 		}
807 	}
808 
809 //profiler_mark(PROFILER_END);
810 
811 //profiler_mark(PROFILER_USER4);
812 
813 	for (i=0; i<9*2; i++)
814 	{
815 		CH  = &chip->P_CH[i/2];
816 		op  = &CH->SLOT[i&1];
817 
818 		/* Phase Generator */
819 		if(op->vib)
820 		{
821 			UINT8 block;
822 
823 			unsigned int fnum_lfo   = 8*((CH->block_fnum&0x01c0) >> 6);
824 			unsigned int block_fnum = CH->block_fnum * 2;
825 			signed int lfo_fn_table_index_offset = lfo_pm_table[LFO_PM + fnum_lfo ];
826 
827 			if (lfo_fn_table_index_offset)	/* LFO phase modulation active */
828 			{
829 				block_fnum += lfo_fn_table_index_offset;
830 				block = (block_fnum&0x1c00) >> 10;
831 				op->phase += (chip->fn_tab[block_fnum&0x03ff] >> (7-block)) * op->mul;
832 			}
833 			else	/* LFO phase modulation  = zero */
834 			{
835 				op->phase += op->freq;
836 			}
837 		}
838 		else	/* LFO phase modulation disabled for this operator */
839 		{
840 			op->phase += op->freq;
841 		}
842 	}
843 
844 	/*	The Noise Generator of the YM3812 is 23-bit shift register.
845 	*	Period is equal to 2^23-2 samples.
846 	*	Register works at sampling frequency of the chip, so output
847 	*	can change on every sample.
848 	*
849 	*	Output of the register and input to the bit 22 is:
850 	*	bit0 XOR bit14 XOR bit15 XOR bit22
851 	*
852 	*	Simply use bit 22 as the noise output.
853 	*/
854 
855 	chip->noise_p += chip->noise_f;
856 	i = chip->noise_p >> FREQ_SH;		/* number of events (shifts of the shift register) */
857 	chip->noise_p &= FREQ_MASK;
858 	while (i)
859 	{
860 		/*
861 		UINT32 j;
862 		j = ( (chip->noise_rng) ^ (chip->noise_rng>>14) ^ (chip->noise_rng>>15) ^ (chip->noise_rng>>22) ) & 1;
863 		chip->noise_rng = (j<<22) | (chip->noise_rng>>1);
864 		*/
865 
866 		/*
867 			Instead of doing all the logic operations above, we
868 			use a trick here (and use bit 0 as the noise output).
869 			The difference is only that the noise bit changes one
870 			step ahead. This doesn't matter since we don't know
871 			what is real state of the noise_rng after the reset.
872 		*/
873 
874 		if (chip->noise_rng & 1) chip->noise_rng ^= 0x800302;
875 		chip->noise_rng >>= 1;
876 
877 		i--;
878 	}
879 //profiler_mark(PROFILER_END);
880 }
881 
882 
op_calc(UINT32 phase,unsigned int env,signed int pm,unsigned int wave_tab)883 MAME_INLINE signed int op_calc(UINT32 phase, unsigned int env, signed int pm, unsigned int wave_tab)
884 {
885 	UINT32 p;
886 
887 	p = (env<<5) + sin_tab[wave_tab + ((((signed int)((phase & ~FREQ_MASK) + (pm<<17))) >> FREQ_SH ) & SIN_MASK) ];
888 
889 	if (p >= TL_TAB_LEN)
890 		return 0;
891 	return tl_tab[p];
892 }
893 
op_calc1(UINT32 phase,unsigned int env,signed int pm,unsigned int wave_tab)894 MAME_INLINE signed int op_calc1(UINT32 phase, unsigned int env, signed int pm, unsigned int wave_tab)
895 {
896 	UINT32 p;
897 	INT32  i;
898 
899 	i = (phase & ~FREQ_MASK) + pm;
900 
901 /*logerror("i=%08x (i>>16)&511=%8i phase=%i [pm=%08x] ",i, (i>>16)&511, phase>>FREQ_SH, pm);*/
902 
903 	p = (env<<5) + sin_tab[ wave_tab + ((i>>FREQ_SH) & SIN_MASK)];
904 
905 /*logerror("(p&255=%i p>>8=%i) out= %i\n", p&255,p>>8, tl_tab[p&255]>>(p>>8) );*/
906 
907 	if (p >= TL_TAB_LEN)
908 		return 0;
909 	return tl_tab[p];
910 }
911 
912 
913 #define volume_calc(OP) ((OP)->TLL + ((UINT32)(OP)->volume) + (LFO_AM & (OP)->AMmask))
914 
915 /* calculate output */
chan_calc(YM2413_OPLL_CH * CH)916 MAME_INLINE void chan_calc( YM2413_OPLL_CH *CH )
917 {
918     YM2413_OPLL_SLOT *SLOT;
919 	unsigned int env;
920 	signed int out;
921 	signed int phase_modulation;	/* phase modulation input (SLOT 2) */
922 
923 
924 	/* SLOT 1 */
925 	SLOT = &CH->SLOT[SLOT1];
926 	env  = volume_calc(SLOT);
927 	out  = SLOT->op1_out[0] + SLOT->op1_out[1];
928 
929 	SLOT->op1_out[0] = SLOT->op1_out[1];
930 	phase_modulation = SLOT->op1_out[0];
931 
932 	SLOT->op1_out[1] = 0;
933 
934 	if( env < ENV_QUIET )
935 	{
936 		if (!SLOT->fb_shift)
937 			out = 0;
938 		SLOT->op1_out[1] = op_calc1(SLOT->phase, env, (out<<SLOT->fb_shift), SLOT->wavetable );
939 	}
940 
941 	/* SLOT 2 */
942 
943 outchan=0;
944 
945 	SLOT++;
946 	env = volume_calc(SLOT);
947 	if( env < ENV_QUIET )
948 	{
949 		signed int outp = op_calc(SLOT->phase, env, phase_modulation, SLOT->wavetable);
950 		output[0] += outp;
951 		outchan = outp;
952 		//output[0] += op_calc(SLOT->phase, env, phase_modulation, SLOT->wavetable);
953 	}
954 }
955 
956 /*
957 	operators used in the rhythm sounds generation process:
958 
959 	Envelope Generator:
960 
961 channel  operator  register number   Bass  High  Snare Tom  Top
962 / slot   number    TL ARDR SLRR Wave Drum  Hat   Drum  Tom  Cymbal
963  6 / 0   12        50  70   90   f0  +
964  6 / 1   15        53  73   93   f3  +
965  7 / 0   13        51  71   91   f1        +
966  7 / 1   16        54  74   94   f4              +
967  8 / 0   14        52  72   92   f2                    +
968  8 / 1   17        55  75   95   f5                          +
969 
970 	Phase Generator:
971 
972 channel  operator  register number   Bass  High  Snare Tom  Top
973 / slot   number    MULTIPLE          Drum  Hat   Drum  Tom  Cymbal
974  6 / 0   12        30                +
975  6 / 1   15        33                +
976  7 / 0   13        31                      +     +           +
977  7 / 1   16        34                -----  n o t  u s e d -----
978  8 / 0   14        32                                  +
979  8 / 1   17        35                      +                 +
980 
981 channel  operator  register number   Bass  High  Snare Tom  Top
982 number   number    BLK/FNUM2 FNUM    Drum  Hat   Drum  Tom  Cymbal
983    6     12,15     B6        A6      +
984 
985    7     13,16     B7        A7            +     +           +
986 
987    8     14,17     B8        A8            +           +     +
988 
989 */
990 
991 /* calculate rhythm */
992 
rhythm_calc(YM2413_OPLL_CH * CH,unsigned int noise)993 MAME_INLINE void rhythm_calc( YM2413_OPLL_CH *CH, unsigned int noise )
994 {
995     YM2413_OPLL_SLOT *SLOT;
996 	signed int out;
997 	unsigned int env;
998 	signed int phase_modulation;	/* phase modulation input (SLOT 2) */
999 
1000 
1001 	/* Bass Drum (verified on real YM3812):
1002 	  - depends on the channel 6 'connect' register:
1003 	      when connect = 0 it works the same as in normal (non-rhythm) mode (op1->op2->out)
1004 	      when connect = 1 _only_ operator 2 is present on output (op2->out), operator 1 is ignored
1005 	  - output sample always is multiplied by 2
1006 	*/
1007 
1008 
1009 	/* SLOT 1 */
1010 	SLOT = &CH[6].SLOT[SLOT1];
1011 	env = volume_calc(SLOT);
1012 
1013 	out = SLOT->op1_out[0] + SLOT->op1_out[1];
1014 	SLOT->op1_out[0] = SLOT->op1_out[1];
1015 
1016 	phase_modulation = SLOT->op1_out[0];
1017 
1018 	SLOT->op1_out[1] = 0;
1019 	if( env < ENV_QUIET )
1020 	{
1021 		if (!SLOT->fb_shift)
1022 			out = 0;
1023 		SLOT->op1_out[1] = op_calc1(SLOT->phase, env, (out<<SLOT->fb_shift), SLOT->wavetable );
1024 	}
1025 
1026 	/* SLOT 2 */
1027 	SLOT++;
1028 	env = volume_calc(SLOT);
1029 	if( env < ENV_QUIET )
1030 		output[1] += op_calc(SLOT->phase, env, phase_modulation, SLOT->wavetable) * 2;
1031 
1032 
1033 	/* Phase generation is based on: */
1034 	// HH  (13) channel 7->slot 1 combined with channel 8->slot 2 (same combination as TOP CYMBAL but different output phases)
1035 	// SD  (16) channel 7->slot 1
1036 	// TOM (14) channel 8->slot 1
1037 	// TOP (17) channel 7->slot 1 combined with channel 8->slot 2 (same combination as HIGH HAT but different output phases)
1038 
1039 	/* Envelope generation based on: */
1040 	// HH  channel 7->slot1
1041 	// SD  channel 7->slot2
1042 	// TOM channel 8->slot1
1043 	// TOP channel 8->slot2
1044 
1045 
1046 	/* The following formulas can be well optimized.
1047 	   I leave them in direct form for now (in case I've missed something).
1048 	*/
1049 
1050 	/* High Hat (verified on real YM3812) */
1051 	env = volume_calc(SLOT7_1);
1052 	if( env < ENV_QUIET )
1053 	{
1054 
1055 		/* high hat phase generation:
1056 			phase = d0 or 234 (based on frequency only)
1057 			phase = 34 or 2d0 (based on noise)
1058 		*/
1059 
1060 		/* base frequency derived from operator 1 in channel 7 */
1061 		unsigned char bit7 = ((SLOT7_1->phase>>FREQ_SH)>>7)&1;
1062 		unsigned char bit3 = ((SLOT7_1->phase>>FREQ_SH)>>3)&1;
1063 		unsigned char bit2 = ((SLOT7_1->phase>>FREQ_SH)>>2)&1;
1064 
1065 		unsigned char res1 = (bit2 ^ bit7) | bit3;
1066 
1067 		/* when res1 = 0 phase = 0x000 | 0xd0; */
1068 		/* when res1 = 1 phase = 0x200 | (0xd0>>2); */
1069 		UINT32 phase = res1 ? (0x200|(0xd0>>2)) : 0xd0;
1070 
1071 		/* enable gate based on frequency of operator 2 in channel 8 */
1072 		unsigned char bit5e= ((SLOT8_2->phase>>FREQ_SH)>>5)&1;
1073 		unsigned char bit3e= ((SLOT8_2->phase>>FREQ_SH)>>3)&1;
1074 
1075 		unsigned char res2 = (bit3e | bit5e);
1076 
1077 		/* when res2 = 0 pass the phase from calculation above (res1); */
1078 		/* when res2 = 1 phase = 0x200 | (0xd0>>2); */
1079 		if (res2)
1080 			phase = (0x200|(0xd0>>2));
1081 
1082 
1083 		/* when phase & 0x200 is set and noise=1 then phase = 0x200|0xd0 */
1084 		/* when phase & 0x200 is set and noise=0 then phase = 0x200|(0xd0>>2), ie no change */
1085 		if (phase&0x200)
1086 		{
1087 			if (noise)
1088 				phase = 0x200|0xd0;
1089 		}
1090 		else
1091 		/* when phase & 0x200 is clear and noise=1 then phase = 0xd0>>2 */
1092 		/* when phase & 0x200 is clear and noise=0 then phase = 0xd0, ie no change */
1093 		{
1094 			if (noise)
1095 				phase = 0xd0>>2;
1096 		}
1097 
1098 		output[1] += op_calc(phase<<FREQ_SH, env, 0, SLOT7_1->wavetable) * 2;
1099 	}
1100 
1101 	/* Snare Drum (verified on real YM3812) */
1102 	env = volume_calc(SLOT7_2);
1103 	if( env < ENV_QUIET )
1104 	{
1105 		/* base frequency derived from operator 1 in channel 7 */
1106 		unsigned char bit8 = ((SLOT7_1->phase>>FREQ_SH)>>8)&1;
1107 
1108 		/* when bit8 = 0 phase = 0x100; */
1109 		/* when bit8 = 1 phase = 0x200; */
1110 		UINT32 phase = bit8 ? 0x200 : 0x100;
1111 
1112 		/* Noise bit XOR'es phase by 0x100 */
1113 		/* when noisebit = 0 pass the phase from calculation above */
1114 		/* when noisebit = 1 phase ^= 0x100; */
1115 		/* in other words: phase ^= (noisebit<<8); */
1116 		if (noise)
1117 			phase ^= 0x100;
1118 
1119 		output[1] += op_calc(phase<<FREQ_SH, env, 0, SLOT7_2->wavetable) * 2;
1120 	}
1121 
1122 	/* Tom Tom (verified on real YM3812) */
1123 	env = volume_calc(SLOT8_1);
1124 	if( env < ENV_QUIET )
1125 		output[1] += op_calc(SLOT8_1->phase, env, 0, SLOT8_1->wavetable) * 2;
1126 
1127 	/* Top Cymbal (verified on real YM2413) */
1128 	env = volume_calc(SLOT8_2);
1129 	if( env < ENV_QUIET )
1130 	{
1131 		/* base frequency derived from operator 1 in channel 7 */
1132 		unsigned char bit7 = ((SLOT7_1->phase>>FREQ_SH)>>7)&1;
1133 		unsigned char bit3 = ((SLOT7_1->phase>>FREQ_SH)>>3)&1;
1134 		unsigned char bit2 = ((SLOT7_1->phase>>FREQ_SH)>>2)&1;
1135 
1136 		unsigned char res1 = (bit2 ^ bit7) | bit3;
1137 
1138 		/* when res1 = 0 phase = 0x000 | 0x100; */
1139 		/* when res1 = 1 phase = 0x200 | 0x100; */
1140 		UINT32 phase = res1 ? 0x300 : 0x100;
1141 
1142 		/* enable gate based on frequency of operator 2 in channel 8 */
1143 		unsigned char bit5e= ((SLOT8_2->phase>>FREQ_SH)>>5)&1;
1144 		unsigned char bit3e= ((SLOT8_2->phase>>FREQ_SH)>>3)&1;
1145 
1146 		unsigned char res2 = (bit3e | bit5e);
1147 		/* when res2 = 0 pass the phase from calculation above (res1); */
1148 		/* when res2 = 1 phase = 0x200 | 0x100; */
1149 		if (res2)
1150 			phase = 0x300;
1151 
1152 		output[1] += op_calc(phase<<FREQ_SH, env, 0, SLOT8_2->wavetable) * 2;
1153 	}
1154 
1155 }
1156 
1157 
1158 /* generic table initialize */
init_tables(void)1159 static int init_tables(void)
1160 {
1161 	signed int i,x;
1162 	signed int n;
1163 	double o,m;
1164 
1165 
1166 	for (x=0; x<TL_RES_LEN; x++)
1167 	{
1168 		m = (1<<16) / pow(2, (x+1) * (ENV_STEP/4.0) / 8.0);
1169 		m = floor(m);
1170 
1171 		/* we never reach (1<<16) here due to the (x+1) */
1172 		/* result fits within 16 bits at maximum */
1173 
1174 		n = (int)m;		/* 16 bits here */
1175 		n >>= 4;		/* 12 bits here */
1176 		if (n&1)		/* round to nearest */
1177 			n = (n>>1)+1;
1178 		else
1179 			n = n>>1;
1180 						/* 11 bits here (rounded) */
1181 		tl_tab[ x*2 + 0 ] = n;
1182 		tl_tab[ x*2 + 1 ] = -tl_tab[ x*2 + 0 ];
1183 
1184 		for (i=1; i<11; i++)
1185 		{
1186 			tl_tab[ x*2+0 + i*2*TL_RES_LEN ] =  tl_tab[ x*2+0 ]>>i;
1187 			tl_tab[ x*2+1 + i*2*TL_RES_LEN ] = -tl_tab[ x*2+0 + i*2*TL_RES_LEN ];
1188 		}
1189 	#if 0
1190 			logerror("tl %04i", x*2);
1191 			for (i=0; i<11; i++)
1192 				logerror(", [%02i] %5i", i*2, tl_tab[ x*2 /*+1*/ + i*2*TL_RES_LEN ] );
1193 			logerror("\n");
1194 	#endif
1195 	}
1196 	/*logerror("ym2413.c: TL_TAB_LEN = %i elements (%i bytes)\n",TL_TAB_LEN, (int)sizeof(tl_tab));*/
1197 
1198 
1199 	for (i=0; i<SIN_LEN; i++)
1200 	{
1201 		/* non-standard sinus */
1202 		m = sin( ((i*2)+1) * PI / SIN_LEN ); /* checked against the real chip */
1203 
1204 		/* we never reach zero here due to ((i*2)+1) */
1205 
1206 		if (m>0.0)
1207 			o = 8*log(1.0/m)/log(2);	/* convert to 'decibels' */
1208 		else
1209 			o = 8*log(-1.0/m)/log(2);	/* convert to 'decibels' */
1210 
1211 		o = o / (ENV_STEP/4);
1212 
1213 		n = (int)(2.0*o);
1214 		if (n&1)						/* round to nearest */
1215 			n = (n>>1)+1;
1216 		else
1217 			n = n>>1;
1218 
1219 		/* waveform 0: standard sinus  */
1220 		sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
1221 
1222 		/*logerror("ym2413.c: sin [%4i (hex=%03x)]= %4i (tl_tab value=%5i)\n", i, i, sin_tab[i], tl_tab[sin_tab[i]] );*/
1223 
1224 
1225 		/* waveform 1:  __      __     */
1226 		/*             /  \____/  \____*/
1227 		/* output only first half of the sinus waveform (positive one) */
1228 		if (i & (1<<(SIN_BITS-1)) )
1229 			sin_tab[1*SIN_LEN+i] = TL_TAB_LEN;
1230 		else
1231 			sin_tab[1*SIN_LEN+i] = sin_tab[i];
1232 
1233 		/*logerror("ym2413.c: sin1[%4i]= %4i (tl_tab value=%5i)\n", i, sin_tab[1*SIN_LEN+i], tl_tab[sin_tab[1*SIN_LEN+i]] );*/
1234 	}
1235 #if 0
1236 	logerror("YM2413.C: ENV_QUIET= %08x (*32=%08x)\n", ENV_QUIET, ENV_QUIET*32 );
1237 	for (i=0; i<ENV_QUIET; i++)
1238 	{
1239 		logerror("tl_tb[%4x(%4i)]=%8x\n", i<<5, i, tl_tab[i<<5] );
1240 	}
1241 #endif
1242 #ifdef SAVE_SAMPLE
1243 	sample[0]=fopen("sampsum.pcm","wb");
1244 #endif
1245 
1246 	return 1;
1247 }
1248 
OPLCloseTable(void)1249 static void OPLCloseTable( void )
1250 {
1251 #ifdef SAVE_SAMPLE
1252 	fclose(sample[0]);
1253 #endif
1254 }
1255 
OPLL_initalize(YM2413 * chip)1256 static void OPLL_initalize(YM2413 *chip)
1257 {
1258 	int i;
1259 
1260 	/* frequency base */
1261 	chip->freqbase  = (chip->rate) ? ((double)chip->clock / 72.0) / chip->rate  : 0;
1262 #if 0
1263 	chip->rate = (double)chip->clock / 72.0;
1264 	chip->freqbase  = 1.0;
1265 	logerror("freqbase=%f\n", chip->freqbase);
1266 #endif
1267 
1268 	/* make fnumber -> increment counter table */
1269 	for( i = 0 ; i < 1024; i++ )
1270 	{
1271 		/* OPLL (YM2413) phase increment counter = 18bit */
1272 
1273 		chip->fn_tab[i] = (UINT32)( (double)i * 64 * chip->freqbase * (1<<(FREQ_SH-10)) ); /* -10 because chip works with 10.10 fixed point, while we use 16.16 */
1274 #if 0
1275 		logerror("ym2413.c: fn_tab[%4i] = %08x (dec=%8i)\n",
1276 				 i, chip->fn_tab[i]>>6, chip->fn_tab[i]>>6 );
1277 #endif
1278 	}
1279 
1280 #if 0
1281 	for( i=0 ; i < 16 ; i++ )
1282 	{
1283 		logerror("ym2413.c: sl_tab[%i] = %08x\n", i, sl_tab[i] );
1284 	}
1285 	for( i=0 ; i < 8 ; i++ )
1286 	{
1287 		int j;
1288 		logerror("ym2413.c: ksl_tab[oct=%2i] =",i);
1289 		for (j=0; j<16; j++)
1290 		{
1291 			logerror("%08x ", ksl_tab[i*16+j] );
1292 		}
1293 		logerror("\n");
1294 	}
1295 #endif
1296 
1297 
1298 	/* Amplitude modulation: 27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples */
1299 	/* One entry from LFO_AM_TABLE lasts for 64 samples */
1300 	chip->lfo_am_inc = (1.0 / 64.0 ) * (1<<LFO_SH) * chip->freqbase;
1301 
1302 	/* Vibrato: 8 output levels (triangle waveform); 1 level takes 1024 samples */
1303 	chip->lfo_pm_inc = (1.0 / 1024.0) * (1<<LFO_SH) * chip->freqbase;
1304 
1305 	/*logerror ("chip->lfo_am_inc = %8x ; chip->lfo_pm_inc = %8x\n", chip->lfo_am_inc, chip->lfo_pm_inc);*/
1306 
1307 	/* Noise generator: a step takes 1 sample */
1308 	chip->noise_f = (1.0 / 1.0) * (1<<FREQ_SH) * chip->freqbase;
1309 	/*logerror("YM2413init noise_f=%8x\n", chip->noise_f);*/
1310 
1311 	chip->eg_timer_add  = (1<<EG_SH)  * chip->freqbase;
1312 	chip->eg_timer_overflow = ( 1 ) * (1<<EG_SH);
1313 	/*logerror("YM2413init eg_timer_add=%8x eg_timer_overflow=%8x\n", chip->eg_timer_add, chip->eg_timer_overflow);*/
1314 
1315 }
1316 
KEY_ON(YM2413_OPLL_SLOT * SLOT,UINT32 key_set)1317 MAME_INLINE void KEY_ON(YM2413_OPLL_SLOT *SLOT, UINT32 key_set)
1318 {
1319 	if( !SLOT->key )
1320 	{
1321 		/* do NOT restart Phase Generator (verified on real YM2413)*/
1322 		/* phase -> Dump */
1323 		SLOT->state = EG_DMP;
1324 	}
1325 	SLOT->key |= key_set;
1326 }
1327 
KEY_OFF(YM2413_OPLL_SLOT * SLOT,UINT32 key_clr)1328 MAME_INLINE void KEY_OFF(YM2413_OPLL_SLOT *SLOT, UINT32 key_clr)
1329 {
1330 	if( SLOT->key )
1331 	{
1332 		SLOT->key &= key_clr;
1333 
1334 		if( !SLOT->key )
1335 		{
1336 			/* phase -> Release */
1337 			if (SLOT->state>EG_REL)
1338 				SLOT->state = EG_REL;
1339 		}
1340 	}
1341 }
1342 
1343 /* update phase increment counter of operator (also update the EG rates if necessary) */
CALC_FCSLOT(YM2413_OPLL_CH * CH,YM2413_OPLL_SLOT * SLOT)1344 MAME_INLINE void CALC_FCSLOT(YM2413_OPLL_CH *CH,YM2413_OPLL_SLOT *SLOT)
1345 {
1346 	int ksr;
1347 	UINT32 SLOT_rs;
1348 	UINT32 SLOT_dp;
1349 
1350 	/* (frequency) phase increment counter */
1351 	SLOT->freq = CH->fc * SLOT->mul;
1352 	ksr = CH->kcode >> SLOT->KSR;
1353 
1354 	if( SLOT->ksr != ksr )
1355 	{
1356 		SLOT->ksr = ksr;
1357 
1358 		/* calculate envelope generator rates */
1359 		if ((SLOT->ar + SLOT->ksr) < 16+62)
1360 		{
1361 			SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
1362 			SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
1363 		}
1364 		else
1365 		{
1366 			SLOT->eg_sh_ar  = 0;
1367 			SLOT->eg_sel_ar = 13*RATE_STEPS;
1368 		}
1369 		SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
1370 		SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
1371 		SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
1372 		SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
1373 
1374 	}
1375 
1376 	if (CH->sus)
1377 		SLOT_rs  = 16 + (5<<2);
1378 	else
1379 		SLOT_rs  = 16 + (7<<2);
1380 
1381 	SLOT->eg_sh_rs  = eg_rate_shift [SLOT_rs + SLOT->ksr ];
1382 	SLOT->eg_sel_rs = eg_rate_select[SLOT_rs + SLOT->ksr ];
1383 
1384 	SLOT_dp  = 16 + (13<<2);
1385 	SLOT->eg_sh_dp  = eg_rate_shift [SLOT_dp + SLOT->ksr ];
1386 	SLOT->eg_sel_dp = eg_rate_select[SLOT_dp + SLOT->ksr ];
1387 }
1388 
1389 /* set multi,am,vib,EG-TYP,KSR,mul */
set_mul(YM2413 * chip,int slot,int v)1390 MAME_INLINE void set_mul(YM2413 *chip,int slot,int v)
1391 {
1392     YM2413_OPLL_CH   *CH   = &chip->P_CH[slot/2];
1393     YM2413_OPLL_SLOT *SLOT = &CH->SLOT[slot&1];
1394 
1395 	SLOT->mul     = mul_tab[v&0x0f];
1396 	SLOT->KSR     = (v&0x10) ? 0 : 2;
1397 	SLOT->eg_type = (v&0x20);
1398 	SLOT->vib     = (v&0x40);
1399 	SLOT->AMmask  = (v&0x80) ? ~0 : 0;
1400 	CALC_FCSLOT(CH,SLOT);
1401 }
1402 
1403 /* set ksl, tl */
set_ksl_tl(YM2413 * chip,int chan,int v)1404 MAME_INLINE void set_ksl_tl(YM2413 *chip,int chan,int v)
1405 {
1406 	int ksl;
1407     YM2413_OPLL_CH   *CH   = &chip->P_CH[chan];
1408 /* modulator */
1409     YM2413_OPLL_SLOT *SLOT = &CH->SLOT[SLOT1];
1410 
1411 	ksl = v>>6; /* 0 / 1.5 / 3.0 / 6.0 dB/OCT */
1412 
1413 	SLOT->ksl = ksl ? 3-ksl : 31;
1414 	SLOT->TL  = (v&0x3f)<<(ENV_BITS-2-7); /* 7 bits TL (bit 6 = always 0) */
1415 	SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1416 }
1417 
1418 /* set ksl , waveforms, feedback */
set_ksl_wave_fb(YM2413 * chip,int chan,int v)1419 MAME_INLINE void set_ksl_wave_fb(YM2413 *chip,int chan,int v)
1420 {
1421 	int ksl;
1422     YM2413_OPLL_CH   *CH   = &chip->P_CH[chan];
1423 /* modulator */
1424     YM2413_OPLL_SLOT *SLOT = &CH->SLOT[SLOT1];
1425 	SLOT->wavetable = ((v&0x08)>>3)*SIN_LEN;
1426 	SLOT->fb_shift  = (v&7) ? (v&7) + 8 : 0;
1427 
1428 /*carrier*/
1429 	SLOT = &CH->SLOT[SLOT2];
1430 	ksl = v>>6; /* 0 / 1.5 / 3.0 / 6.0 dB/OCT */
1431 
1432 	SLOT->ksl = ksl ? 3-ksl : 31;
1433 	SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1434 
1435 	SLOT->wavetable = ((v&0x10)>>4)*SIN_LEN;
1436 }
1437 
1438 /* set attack rate & decay rate  */
set_ar_dr(YM2413 * chip,int slot,int v)1439 MAME_INLINE void set_ar_dr(YM2413 *chip,int slot,int v)
1440 {
1441     YM2413_OPLL_CH   *CH   = &chip->P_CH[slot/2];
1442     YM2413_OPLL_SLOT *SLOT = &CH->SLOT[slot&1];
1443 
1444 	SLOT->ar = (v>>4)  ? 16 + ((v>>4)  <<2) : 0;
1445 
1446 	if ((SLOT->ar + SLOT->ksr) < 16+62)
1447 	{
1448 		SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
1449 		SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
1450 	}
1451 	else
1452 	{
1453 		SLOT->eg_sh_ar  = 0;
1454 		SLOT->eg_sel_ar = 13*RATE_STEPS;
1455 	}
1456 
1457 	SLOT->dr    = (v&0x0f)? 16 + ((v&0x0f)<<2) : 0;
1458 	SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
1459 	SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
1460 }
1461 
1462 /* set sustain level & release rate */
set_sl_rr(YM2413 * chip,int slot,int v)1463 MAME_INLINE void set_sl_rr(YM2413 *chip,int slot,int v)
1464 {
1465     YM2413_OPLL_CH   *CH   = &chip->P_CH[slot/2];
1466     YM2413_OPLL_SLOT *SLOT = &CH->SLOT[slot&1];
1467 
1468 	SLOT->sl  = sl_tab[ v>>4 ];
1469 
1470 	SLOT->rr  = (v&0x0f)? 16 + ((v&0x0f)<<2) : 0;
1471 	SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
1472 	SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
1473 }
1474 
load_instrument(YM2413 * chip,UINT32 chan,UINT32 slot,UINT8 * inst)1475 static void load_instrument(YM2413 *chip, UINT32 chan, UINT32 slot, UINT8* inst )
1476 {
1477 	set_mul			(chip, slot,   inst[0]);
1478 	set_mul			(chip, slot+1, inst[1]);
1479 	set_ksl_tl		(chip, chan,   inst[2]);
1480 	set_ksl_wave_fb	(chip, chan,   inst[3]);
1481 	set_ar_dr		(chip, slot,   inst[4]);
1482 	set_ar_dr		(chip, slot+1, inst[5]);
1483 	set_sl_rr		(chip, slot,   inst[6]);
1484 	set_sl_rr		(chip, slot+1, inst[7]);
1485 }
update_instrument_zero(YM2413 * chip,UINT8 r)1486 static void update_instrument_zero(YM2413 *chip, UINT8 r )
1487 {
1488 	UINT8* inst = &chip->inst_tab[0][0]; /* point to user instrument */
1489 	UINT32 chan;
1490 	UINT32 chan_max;
1491 
1492 	chan_max = 9;
1493 	if (chip->rhythm & 0x20)
1494 		chan_max=6;
1495 
1496 	switch(r)
1497 	{
1498 	case 0:
1499 		for (chan=0; chan<chan_max; chan++)
1500 		{
1501 			if ((chip->instvol_r[chan]&0xf0)==0)
1502 			{
1503 				set_mul			(chip, chan*2, inst[0]);
1504 			}
1505 		}
1506         break;
1507 	case 1:
1508 		for (chan=0; chan<chan_max; chan++)
1509 		{
1510 			if ((chip->instvol_r[chan]&0xf0)==0)
1511 			{
1512 				set_mul			(chip, chan*2+1,inst[1]);
1513 			}
1514 		}
1515         break;
1516 	case 2:
1517 		for (chan=0; chan<chan_max; chan++)
1518 		{
1519 			if ((chip->instvol_r[chan]&0xf0)==0)
1520 			{
1521 				set_ksl_tl		(chip, chan,   inst[2]);
1522 			}
1523 		}
1524         break;
1525 	case 3:
1526 		for (chan=0; chan<chan_max; chan++)
1527 		{
1528 			if ((chip->instvol_r[chan]&0xf0)==0)
1529 			{
1530 				set_ksl_wave_fb	(chip, chan,   inst[3]);
1531 			}
1532 		}
1533         break;
1534 	case 4:
1535 		for (chan=0; chan<chan_max; chan++)
1536 		{
1537 			if ((chip->instvol_r[chan]&0xf0)==0)
1538 			{
1539 				set_ar_dr		(chip, chan*2, inst[4]);
1540 			}
1541 		}
1542         break;
1543 	case 5:
1544 		for (chan=0; chan<chan_max; chan++)
1545 		{
1546 			if ((chip->instvol_r[chan]&0xf0)==0)
1547 			{
1548 				set_ar_dr		(chip, chan*2+1,inst[5]);
1549 			}
1550 		}
1551         break;
1552 	case 6:
1553 		for (chan=0; chan<chan_max; chan++)
1554 		{
1555 			if ((chip->instvol_r[chan]&0xf0)==0)
1556 			{
1557 				set_sl_rr		(chip, chan*2, inst[6]);
1558 			}
1559 		}
1560         break;
1561 	case 7:
1562 		for (chan=0; chan<chan_max; chan++)
1563 		{
1564 			if ((chip->instvol_r[chan]&0xf0)==0)
1565 			{
1566 				set_sl_rr		(chip, chan*2+1,inst[7]);
1567 			}
1568 		}
1569         break;
1570     }
1571 }
1572 
1573 /* write a value v to register r on chip chip */
OPLLWriteReg(YM2413 * chip,int r,int v)1574 static void OPLLWriteReg(YM2413 *chip, int r, int v)
1575 {
1576     YM2413_OPLL_CH *CH;
1577     YM2413_OPLL_SLOT *SLOT;
1578 	UINT8 *inst;
1579 	int chan;
1580 	int slot;
1581 
1582 	/* adjust bus to 8 bits */
1583 	r &= 0xff;
1584 	v &= 0xff;
1585 
1586 
1587 #ifdef LOG_CYM_FILE
1588 	if ((cymfile) && (r!=8) )
1589 	{
1590 		fputc( (unsigned char)r, cymfile );
1591 		fputc( (unsigned char)v, cymfile );
1592 	}
1593 #endif
1594 
1595 
1596 	switch(r&0xf0)
1597 	{
1598 	case 0x00:	/* 00-0f:control */
1599 	{
1600 		switch(r&0x0f)
1601 		{
1602 		case 0x00:	/* AM/VIB/EGTYP/KSR/MULTI (modulator) */
1603 		case 0x01:	/* AM/VIB/EGTYP/KSR/MULTI (carrier) */
1604 		case 0x02:	/* Key Scale Level, Total Level (modulator) */
1605 		case 0x03:	/* Key Scale Level, carrier waveform, modulator waveform, Feedback */
1606 		case 0x04:	/* Attack, Decay (modulator) */
1607 		case 0x05:	/* Attack, Decay (carrier) */
1608 		case 0x06:	/* Sustain, Release (modulator) */
1609 		case 0x07:	/* Sustain, Release (carrier) */
1610 			chip->inst_tab[0][r & 0x07] = v;
1611 			update_instrument_zero(chip,r&7);
1612 		break;
1613 
1614 		case 0x0e:	/* x, x, r,bd,sd,tom,tc,hh */
1615 		{
1616 			if(v&0x20)
1617 			{
1618 				if ((chip->rhythm&0x20)==0)
1619 				/*rhythm off to on*/
1620 				{
1621 					logerror("YM2413: Rhythm mode enable\n");
1622 
1623 	/* Load instrument settings for channel seven(chan=6 since we're zero based). (Bass drum) */
1624 					chan = 6;
1625 					inst = &chip->inst_tab[16][0];
1626 					slot = chan*2;
1627 
1628 					load_instrument(chip, chan, slot, inst);
1629 
1630 	/* Load instrument settings for channel eight. (High hat and snare drum) */
1631 					chan = 7;
1632 					inst = &chip->inst_tab[17][0];
1633 					slot = chan*2;
1634 
1635 					load_instrument(chip, chan, slot, inst);
1636 
1637 					CH   = &chip->P_CH[chan];
1638 					SLOT = &CH->SLOT[SLOT1]; /* modulator envelope is HH */
1639 					SLOT->TL  = ((chip->instvol_r[chan]>>4)<<2)<<(ENV_BITS-2-7); /* 7 bits TL (bit 6 = always 0) */
1640 					SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1641 
1642 	/* Load instrument settings for channel nine. (Tom-tom and top cymbal) */
1643 					chan = 8;
1644 					inst = &chip->inst_tab[18][0];
1645 					slot = chan*2;
1646 
1647 					load_instrument(chip, chan, slot, inst);
1648 
1649 					CH   = &chip->P_CH[chan];
1650 					SLOT = &CH->SLOT[SLOT1]; /* modulator envelope is TOM */
1651 					SLOT->TL  = ((chip->instvol_r[chan]>>4)<<2)<<(ENV_BITS-2-7); /* 7 bits TL (bit 6 = always 0) */
1652 					SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1653 				}
1654 				/* BD key on/off */
1655 				if(v&0x10)
1656 				{
1657 					KEY_ON (&chip->P_CH[6].SLOT[SLOT1], 2);
1658 					KEY_ON (&chip->P_CH[6].SLOT[SLOT2], 2);
1659 				}
1660 				else
1661 				{
1662 					KEY_OFF(&chip->P_CH[6].SLOT[SLOT1],~2);
1663 					KEY_OFF(&chip->P_CH[6].SLOT[SLOT2],~2);
1664 				}
1665 				/* HH key on/off */
1666 				if(v&0x01) KEY_ON (&chip->P_CH[7].SLOT[SLOT1], 2);
1667 				else       KEY_OFF(&chip->P_CH[7].SLOT[SLOT1],~2);
1668 				/* SD key on/off */
1669 				if(v&0x08) KEY_ON (&chip->P_CH[7].SLOT[SLOT2], 2);
1670 				else       KEY_OFF(&chip->P_CH[7].SLOT[SLOT2],~2);
1671 				/* TOM key on/off */
1672 				if(v&0x04) KEY_ON (&chip->P_CH[8].SLOT[SLOT1], 2);
1673 				else       KEY_OFF(&chip->P_CH[8].SLOT[SLOT1],~2);
1674 				/* TOP-CY key on/off */
1675 				if(v&0x02) KEY_ON (&chip->P_CH[8].SLOT[SLOT2], 2);
1676 				else       KEY_OFF(&chip->P_CH[8].SLOT[SLOT2],~2);
1677 			}
1678 			else
1679 			{
1680 				if (chip->rhythm&0x20)
1681 				/*rhythm on to off*/
1682 				{
1683 					logerror("YM2413: Rhythm mode disable\n");
1684 	/* Load instrument settings for channel seven(chan=6 since we're zero based).*/
1685 					chan = 6;
1686 					inst = &chip->inst_tab[chip->instvol_r[chan]>>4][0];
1687 					slot = chan*2;
1688 
1689 					load_instrument(chip, chan, slot, inst);
1690 
1691 	/* Load instrument settings for channel eight.*/
1692 					chan = 7;
1693 					inst = &chip->inst_tab[chip->instvol_r[chan]>>4][0];
1694 					slot = chan*2;
1695 
1696 					load_instrument(chip, chan, slot, inst);
1697 
1698 	/* Load instrument settings for channel nine.*/
1699 					chan = 8;
1700 					inst = &chip->inst_tab[chip->instvol_r[chan]>>4][0];
1701 					slot = chan*2;
1702 
1703 					load_instrument(chip, chan, slot, inst);
1704 				}
1705 				/* BD key off */
1706 				KEY_OFF(&chip->P_CH[6].SLOT[SLOT1],~2);
1707 				KEY_OFF(&chip->P_CH[6].SLOT[SLOT2],~2);
1708 				/* HH key off */
1709 				KEY_OFF(&chip->P_CH[7].SLOT[SLOT1],~2);
1710 				/* SD key off */
1711 				KEY_OFF(&chip->P_CH[7].SLOT[SLOT2],~2);
1712 				/* TOM key off */
1713 				KEY_OFF(&chip->P_CH[8].SLOT[SLOT1],~2);
1714 				/* TOP-CY off */
1715 				KEY_OFF(&chip->P_CH[8].SLOT[SLOT2],~2);
1716 			}
1717 			chip->rhythm  = v&0x3f;
1718 		}
1719 		break;
1720 		}
1721 	}
1722 	break;
1723 
1724 	case 0x10:
1725 	case 0x20:
1726 	{
1727 		int block_fnum;
1728 
1729 		chan = r&0x0f;
1730 
1731 		if (chan >= 9)
1732 			chan -= 9;	/* verified on real YM2413 */
1733 
1734 		CH = &chip->P_CH[chan];
1735 
1736 		if(r&0x10)
1737 		{	/* 10-18: FNUM 0-7 */
1738 			block_fnum  = (CH->block_fnum&0x0f00) | v;
1739 		}
1740 		else
1741 		{	/* 20-28: suson, keyon, block, FNUM 8 */
1742 			block_fnum = ((v&0x0f)<<8) | (CH->block_fnum&0xff);
1743 
1744 			if(v&0x10)
1745 			{
1746 				KEY_ON (&CH->SLOT[SLOT1], 1);
1747 				KEY_ON (&CH->SLOT[SLOT2], 1);
1748 			}
1749 			else
1750 			{
1751 				KEY_OFF(&CH->SLOT[SLOT1],~1);
1752 				KEY_OFF(&CH->SLOT[SLOT2],~1);
1753 			}
1754 
1755 
1756 			if (CH->sus!=(v&0x20))
1757 				logerror("chan=%i sus=%2x\n",chan,v&0x20);
1758 
1759 			CH->sus = v & 0x20;
1760 		}
1761 		/* update */
1762 		if(CH->block_fnum != block_fnum)
1763 		{
1764 			UINT8 block;
1765 
1766 			CH->block_fnum = block_fnum;
1767 
1768 			/* BLK 2,1,0 bits -> bits 3,2,1 of kcode, FNUM MSB -> kcode LSB */
1769 			CH->kcode    = (block_fnum&0x0f00)>>8;
1770 
1771 			CH->ksl_base = ksl_tab[block_fnum>>5];
1772 
1773 			block_fnum   = block_fnum * 2;
1774 			block        = (block_fnum&0x1c00) >> 10;
1775 			CH->fc       = chip->fn_tab[block_fnum&0x03ff] >> (7-block);
1776 
1777 			/* refresh Total Level in both SLOTs of this channel */
1778 			CH->SLOT[SLOT1].TLL = CH->SLOT[SLOT1].TL + (CH->ksl_base>>CH->SLOT[SLOT1].ksl);
1779 			CH->SLOT[SLOT2].TLL = CH->SLOT[SLOT2].TL + (CH->ksl_base>>CH->SLOT[SLOT2].ksl);
1780 
1781 			/* refresh frequency counter in both SLOTs of this channel */
1782 			CALC_FCSLOT(CH,&CH->SLOT[SLOT1]);
1783 			CALC_FCSLOT(CH,&CH->SLOT[SLOT2]);
1784 		}
1785 	}
1786 	break;
1787 
1788 	case 0x30:	/* inst 4 MSBs, VOL 4 LSBs */
1789 	{
1790 		UINT8 old_instvol;
1791 
1792 		chan = r&0x0f;
1793 
1794 		if (chan >= 9)
1795 			chan -= 9;	/* verified on real YM2413 */
1796 
1797 		old_instvol = chip->instvol_r[chan];
1798 		chip->instvol_r[chan] = v;	/* store for later use */
1799 
1800 		CH   = &chip->P_CH[chan];
1801 		SLOT = &CH->SLOT[SLOT2]; /* carrier */
1802 		SLOT->TL  = ((v&0x0f)<<2)<<(ENV_BITS-2-7); /* 7 bits TL (bit 6 = always 0) */
1803 		SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1804 
1805 
1806 		/*check wether we are in rhythm mode and handle instrument/volume register accordingly*/
1807 		if ((chan>=6) && (chip->rhythm&0x20))
1808 		{
1809 			/* we're in rhythm mode*/
1810 
1811 			if (chan>=7) /* only for channel 7 and 8 (channel 6 is handled in usual way)*/
1812 			{
1813 				SLOT = &CH->SLOT[SLOT1]; /* modulator envelope is HH(chan=7) or TOM(chan=8) */
1814 				SLOT->TL  = ((chip->instvol_r[chan]>>4)<<2)<<(ENV_BITS-2-7); /* 7 bits TL (bit 6 = always 0) */
1815 				SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1816 			}
1817 		}
1818 		else
1819 		{
1820 			if ( (old_instvol&0xf0) == (v&0xf0) )
1821 				return;
1822 
1823 			inst = &chip->inst_tab[chip->instvol_r[chan]>>4][0];
1824 			slot = chan*2;
1825 
1826 			load_instrument(chip, chan, slot, inst);
1827 
1828 		#if 0
1829 			logerror("YM2413: chan#%02i inst=%02i:  (r=%2x, v=%2x)\n",chan,v>>4,r,v);
1830 			logerror("  0:%2x  1:%2x\n",inst[0],inst[1]);	logerror("  2:%2x  3:%2x\n",inst[2],inst[3]);
1831 			logerror("  4:%2x  5:%2x\n",inst[4],inst[5]);	logerror("  6:%2x  7:%2x\n",inst[6],inst[7]);
1832 		#endif
1833 		}
1834 	}
1835 	break;
1836 
1837 	default:
1838 	break;
1839 	}
1840 }
1841 
1842 #ifdef LOG_CYM_FILE
cymfile_callback(int n)1843 static void cymfile_callback (int n)
1844 {
1845 	if (cymfile)
1846 	{
1847 		fputc( (unsigned char)8, cymfile );
1848 	}
1849 }
1850 #endif
1851 
1852 /* lock/unlock for common table */
OPLL_LockTable(void)1853 static int OPLL_LockTable(void)
1854 {
1855 	num_lock++;
1856 	if(num_lock>1) return 0;
1857 
1858 	/* first time */
1859 
1860 	cur_chip = NULL;
1861 	/* allocate total level table (128kb space) */
1862 	if( !init_tables() )
1863 	{
1864 		num_lock--;
1865 		return -1;
1866 	}
1867 
1868 #ifdef LOG_CYM_FILE
1869 	cymfile = fopen("2413_.cym","wb");
1870 	if (cymfile)
1871 		timer_pulse ( TIME_IN_HZ(110), 0, cymfile_callback); /*110 Hz pulse timer*/
1872 	else
1873 		logerror("Could not create file 2413_.cym\n");
1874 #endif
1875 
1876 	return 0;
1877 }
1878 
OPLL_UnLockTable(void)1879 static void OPLL_UnLockTable(void)
1880 {
1881 	if(num_lock) num_lock--;
1882 	if(num_lock) return;
1883 
1884 	/* last time */
1885 
1886 	cur_chip = NULL;
1887 	OPLCloseTable();
1888 
1889 #ifdef LOG_CYM_FILE
1890 	fclose (cymfile);
1891 	cymfile = NULL;
1892 #endif
1893 
1894 }
1895 
OPLLResetChip(YM2413 * chip)1896 static void OPLLResetChip(YM2413 *chip)
1897 {
1898 	int c,s;
1899 	int i;
1900 
1901 	chip->eg_timer = 0;
1902 	chip->eg_cnt   = 0;
1903 
1904 	chip->noise_rng = 1;	/* noise shift register */
1905 
1906 
1907 	/* setup instruments table */
1908 	for (i=0; i<19; i++)
1909 	{
1910 		for (c=0; c<8; c++)
1911 		{
1912 			chip->inst_tab[i][c] = table[i][c];
1913 		}
1914 	}
1915 
1916 
1917 	/* reset with register write */
1918 	OPLLWriteReg(chip,0x0f,0); /*test reg*/
1919 	for(i = 0x3f ; i >= 0x10 ; i-- ) OPLLWriteReg(chip,i,0x00);
1920 
1921 	/* reset operator parameters */
1922 	for( c = 0 ; c < 9 ; c++ )
1923 	{
1924         YM2413_OPLL_CH *CH = &chip->P_CH[c];
1925 		for(s = 0 ; s < 2 ; s++ )
1926 		{
1927 			/* wave table */
1928 			CH->SLOT[s].wavetable = 0;
1929 			CH->SLOT[s].state     = EG_OFF;
1930 			CH->SLOT[s].volume    = MAX_ATT_INDEX;
1931 		}
1932 	}
1933 }
1934 
1935 /* Create one of virtual YM2413 */
1936 /* 'clock' is chip clock in Hz  */
1937 /* 'rate'  is sampling rate  */
OPLLCreate(int clock,int rate)1938 static YM2413 *OPLLCreate(int clock, int rate)
1939 {
1940 	char *ptr;
1941 	YM2413 *chip;
1942 	int state_size;
1943 
1944 	if (OPLL_LockTable() ==-1) return NULL;
1945 
1946 	/* calculate chip state size */
1947 	state_size  = sizeof(YM2413);
1948 
1949 	/* allocate memory block */
1950 	ptr = malloc(state_size);
1951 
1952 	if (ptr==NULL)
1953 		return NULL;
1954 
1955 	/* clear */
1956 	memset(ptr,0,state_size);
1957 
1958 	chip  = (YM2413 *)ptr;
1959 
1960 	chip->clock = clock;
1961 	chip->rate  = rate;
1962 
1963 	/* init global tables */
1964 	OPLL_initalize(chip);
1965 
1966 	/* reset chip */
1967 	OPLLResetChip(chip);
1968 	return chip;
1969 }
1970 
1971 /* Destroy one of virtual YM3812 */
OPLLDestroy(YM2413 * chip)1972 static void OPLLDestroy(YM2413 *chip)
1973 {
1974 	OPLL_UnLockTable();
1975 	if (chip) {
1976 		free(chip);
1977 		chip = NULL;
1978 	}
1979 }
1980 
1981 /* Option handlers */
1982 
OPLLSetUpdateHandler(YM2413 * chip,OPLL_UPDATEHANDLER UpdateHandler,int param)1983 static void OPLLSetUpdateHandler(YM2413 *chip,OPLL_UPDATEHANDLER UpdateHandler,int param)
1984 {
1985 	chip->UpdateHandler = UpdateHandler;
1986 	chip->UpdateParam = param;
1987 }
1988 
1989 /* YM3812 I/O interface */
OPLLWrite(YM2413 * chip,int a,int v)1990 static void OPLLWrite(YM2413 *chip,int a,int v)
1991 {
1992 	if( !(a&1) )
1993 	{	/* address port */
1994 		chip->address = v & 0xff;
1995 	}
1996 	else
1997 	{	/* data port */
1998 		if(chip->UpdateHandler) chip->UpdateHandler(chip->UpdateParam,0);
1999 		OPLLWriteReg(chip,chip->address,v);
2000 	}
2001 }
2002 
OPLLRead(YM2413 * chip,int a)2003 static unsigned char OPLLRead(YM2413 *chip,int a)
2004 {
2005 	if( !(a&1) )
2006 	{
2007 		/* status port */
2008 		return chip->status;
2009 	}
2010 	return 0xff;
2011 }
2012 
2013 
2014 
2015 
2016 
2017 #define MAX_OPLL_CHIPS 4
2018 
2019 
2020 static YM2413 *OPLL_YM2413[MAX_OPLL_CHIPS];	/* array of pointers to the YM2413's */
2021 static int YM2413NumChips = 0;				/* number of chips */
2022 
YM2413Init(int num,int clock,int rate)2023 int YM2413Init(int num, int clock, int rate)
2024 {
2025 	int i;
2026 
2027 	if (YM2413NumChips)
2028 		return -1;	/* duplicate init. */
2029 
2030 	YM2413NumChips = num;
2031 
2032 	for (i = 0;i < YM2413NumChips; i++)
2033 	{
2034 		/* emulator create */
2035 		OPLL_YM2413[i] = OPLLCreate(clock, rate);
2036 		if(OPLL_YM2413[i] == NULL)
2037 		{
2038 			/* it's really bad - we run out of memeory */
2039 			YM2413NumChips = 0;
2040 			return -1;
2041 		}
2042 	}
2043 
2044 	return 0;
2045 }
2046 
YM2413Shutdown(void)2047 void YM2413Shutdown(void)
2048 {
2049 	int i;
2050 
2051 	for (i = 0;i < YM2413NumChips; i++)
2052 	{
2053 		/* emulator shutdown */
2054         if(OPLL_YM2413[i])
2055             OPLLDestroy(OPLL_YM2413[i]);
2056 		OPLL_YM2413[i] = NULL;
2057 	}
2058 	YM2413NumChips = 0;
2059 }
2060 
YM2413ResetChip(int which)2061 void YM2413ResetChip(int which)
2062 {
2063 	OPLLResetChip(OPLL_YM2413[which]);
2064 }
2065 
YM2413Write(int which,int a,int v)2066 void YM2413Write(int which, int a, int v)
2067 {
2068 	OPLLWrite(OPLL_YM2413[which], a, v);
2069 }
2070 
YM2413WriteReg(int which,int r,int v)2071 void YM2413WriteReg(int which, int r, int v)
2072 {
2073 	OPLLWriteReg(OPLL_YM2413[which], r, v);
2074 }
2075 
YM2413Read(int which,int a)2076 unsigned char YM2413Read(int which, int a)
2077 {
2078 	return OPLLRead(OPLL_YM2413[which], a) & 0x03 ;
2079 }
2080 
YM2413SetUpdateHandler(int which,OPLL_UPDATEHANDLER UpdateHandler,int param)2081 void YM2413SetUpdateHandler(int which,OPLL_UPDATEHANDLER UpdateHandler,int param)
2082 {
2083 	OPLLSetUpdateHandler(OPLL_YM2413[which], UpdateHandler, param);
2084 }
2085 
2086 
2087 /*
2088 ** Generate samples for one of the YM2413's
2089 **
2090 ** 'which' is the virtual YM2413 number
2091 ** '*buffer' is the output buffer pointer
2092 ** 'length' is the number of samples that should be generated
2093 */
YM2413UpdateOne(int which,INT16 ** buffers,int length)2094 void YM2413UpdateOne(int which, INT16 **buffers, int length)
2095 {
2096 	YM2413		*chip  = OPLL_YM2413[which];
2097 	UINT8		rhythm = chip->rhythm&0x20;
2098 	SAMP		*bufMO = buffers[0];
2099 	SAMP		*bufRO = buffers[1];
2100 
2101 	int i;
2102 
2103 	if( (void *)chip != cur_chip ){
2104 		cur_chip = (void *)chip;
2105 		/* rhythm slots */
2106 		SLOT7_1 = &chip->P_CH[7].SLOT[SLOT1];
2107 		SLOT7_2 = &chip->P_CH[7].SLOT[SLOT2];
2108 		SLOT8_1 = &chip->P_CH[8].SLOT[SLOT1];
2109 		SLOT8_2 = &chip->P_CH[8].SLOT[SLOT2];
2110 	}
2111 
2112 
2113 	for( i=0; i < length ; i++ )
2114 	{
2115 		int mo,ro;
2116 
2117 		output[0] = 0;
2118 		output[1] = 0;
2119 
2120 		advance_lfo(chip);
2121 
2122 		/* FM part */
2123 		chan_calc(&chip->P_CH[0]);
2124 //SAVE_SEPARATE_CHANNEL(0);
2125 		chan_calc(&chip->P_CH[1]);
2126 		chan_calc(&chip->P_CH[2]);
2127 		chan_calc(&chip->P_CH[3]);
2128 		chan_calc(&chip->P_CH[4]);
2129 		chan_calc(&chip->P_CH[5]);
2130 
2131 		if(!rhythm)
2132 		{
2133 			chan_calc(&chip->P_CH[6]);
2134 			chan_calc(&chip->P_CH[7]);
2135 			chan_calc(&chip->P_CH[8]);
2136 		}
2137 		else		/* Rhythm part */
2138 		{
2139 			rhythm_calc(&chip->P_CH[0], (chip->noise_rng>>0)&1 );
2140 		}
2141 
2142 		mo = output[0];
2143 		ro = output[1];
2144 
2145 		mo >>= FINAL_SH;
2146 		ro >>= FINAL_SH;
2147 
2148 		/* limit check */
2149 		mo = limit( mo , MAXOUT, MINOUT );
2150 		ro = limit( ro , MAXOUT, MINOUT );
2151 
2152 		#ifdef SAVE_SAMPLE
2153 		if (which==0)
2154 		{
2155 			SAVE_ALL_CHANNELS
2156 		}
2157 		#endif
2158 
2159 		/* store to sound buffer */
2160 		bufMO[i] = mo;
2161 		bufRO[i] = ro;
2162 
2163 		advance(chip);
2164 	}
2165 
2166 }
2167 
YM2413Scan(INT32 which,INT32 nAction)2168 void YM2413Scan(INT32 which, INT32 nAction)
2169 {
2170 	YM2413 *chip  = OPLL_YM2413[which];
2171 
2172 	if (nAction & ACB_DRIVER_DATA) {
2173 		INT32 chnum;
2174 		INT32 slotnum;
2175 
2176 		SCAN_VAR(chip->instvol_r);
2177 		SCAN_VAR(chip->eg_cnt);
2178 		SCAN_VAR(chip->eg_timer);
2179 		SCAN_VAR(chip->eg_timer_add);
2180 		SCAN_VAR(chip->eg_timer_overflow);
2181 		SCAN_VAR(chip->rhythm);
2182 		SCAN_VAR(chip->lfo_am_cnt);
2183 		SCAN_VAR(chip->lfo_am_inc);
2184 		SCAN_VAR(chip->lfo_pm_cnt);
2185 		SCAN_VAR(chip->lfo_pm_inc);
2186 		SCAN_VAR(chip->noise_rng);
2187 		SCAN_VAR(chip->noise_p);
2188 		SCAN_VAR(chip->noise_f);
2189 		SCAN_VAR(chip->inst_tab);
2190 		SCAN_VAR(chip->address);
2191 		SCAN_VAR(chip->status);
2192 
2193 		for (chnum = 0; chnum < 9; chnum++) {
2194 			YM2413_OPLL_CH *ch = &chip->P_CH[chnum];
2195 
2196 			SCAN_VAR(ch->block_fnum);
2197 			SCAN_VAR(ch->fc);
2198 			SCAN_VAR(ch->ksl_base);
2199 			SCAN_VAR(ch->kcode);
2200 			SCAN_VAR(ch->sus);
2201 
2202 			for (slotnum = 0; slotnum < 2; slotnum++) {
2203 				YM2413_OPLL_SLOT *sl = &ch->SLOT[slotnum];
2204 
2205 				SCAN_VAR(sl->ar);
2206 				SCAN_VAR(sl->dr);
2207 				SCAN_VAR(sl->rr);
2208 				SCAN_VAR(sl->KSR);
2209 				SCAN_VAR(sl->ksl);
2210 				SCAN_VAR(sl->ksr);
2211 				SCAN_VAR(sl->mul);
2212 				SCAN_VAR(sl->phase);
2213 				SCAN_VAR(sl->freq);
2214 				SCAN_VAR(sl->fb_shift);
2215 				SCAN_VAR(sl->op1_out);
2216 				SCAN_VAR(sl->eg_type);
2217 				SCAN_VAR(sl->state);
2218 				SCAN_VAR(sl->TL);
2219 				SCAN_VAR(sl->TLL);
2220 				SCAN_VAR(sl->volume);
2221 				SCAN_VAR(sl->sl);
2222 				SCAN_VAR(sl->eg_sh_dp);
2223 				SCAN_VAR(sl->eg_sel_dp);
2224 				SCAN_VAR(sl->eg_sh_ar);
2225 				SCAN_VAR(sl->eg_sel_ar);
2226 				SCAN_VAR(sl->eg_sh_dr);
2227 				SCAN_VAR(sl->eg_sel_dr);
2228 				SCAN_VAR(sl->eg_sh_rr);
2229 				SCAN_VAR(sl->eg_sel_rr);
2230 				SCAN_VAR(sl->eg_sh_rs);
2231 				SCAN_VAR(sl->eg_sel_rs);
2232 				SCAN_VAR(sl->key);
2233 				SCAN_VAR(sl->AMmask);
2234 				SCAN_VAR(sl->vib);
2235 				SCAN_VAR(sl->wavetable);
2236 			}
2237 		}
2238 	}
2239 }
2240