1 // Based on MAME sources by Jarek Burczynski
2 /*****************************************************************************
3 *
4 *	Yamaha YM2151 driver (version 2.150 final beta)
5 *
6 ******************************************************************************/
7 
8 #include <stdio.h>
9 #include <stdarg.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <math.h>
13 
14 #include "driver.h"
15 #include "state.h"
16 #include "ym2151.h"
17 
18 #if defined FBA_DEBUG
19 #ifdef __GNUC__
20 	// MSVC doesn't like this - this module only supports debug tracking with GCC only
21 	#include <tchar.h>
22 	extern UINT8 DebugSnd_AY8910Initted;
23 	extern INT32 (__cdecl *bprintf) (INT32 nStatus, TCHAR* szFormat, ...);
24 	#define PRINT_ERROR		(3)
25 #endif
26 #endif
27 
28 /* undef this to not use MAME timer system */
29 // #define USE_MAME_TIMERS
30 
31 /*#define FM_EMU*/
32 #ifdef FM_EMU
33 	#define INLINE static __inline__
34 	#ifdef USE_MAME_TIMERS
35 		#undef USE_MAME_TIMERS
36 	#endif
37 #endif
38 #ifdef USE_MAME_TIMERS
39 	/*#define LOG_CYM_FILE*/
40 	#ifdef LOG_CYM_FILE
41 		FILE * cymfile = NULL;
42 	#endif
43 #endif
44 
45 
46 /* struct describing a single operator */
47 typedef struct{
48 	UINT32		phase;					/* accumulated operator phase */
49 	UINT32		freq;					/* operator frequency count */
50 	INT32		dt1;					/* current DT1 (detune 1 phase inc/decrement) value */
51 	UINT32		mul;					/* frequency count multiply */
52 	UINT32		dt1_i;					/* DT1 index * 32 */
53 	UINT32		dt2;					/* current DT2 (detune 2) value */
54 
55 	signed int *connect;				/* operator output 'direction' */
56 
57 	/* only M1 (operator 0) is filled with this data: */
58 	signed int *mem_connect;			/* where to put the delayed sample (MEM) */
59 	INT32		mem_value;				/* delayed sample (MEM) value */
60 
61 	/* channel specific data; note: each operator number 0 contains channel specific data */
62 	UINT32		fb_shift;				/* feedback shift value for operators 0 in each channel */
63 	INT32		fb_out_curr;			/* operator feedback value (used only by operators 0) */
64 	INT32		fb_out_prev;			/* previous feedback value (used only by operators 0) */
65 	UINT32		kc;						/* channel KC (copied to all operators) */
66 	UINT32		kc_i;					/* just for speedup */
67 	UINT32		pms;					/* channel PMS */
68 	UINT32		ams;					/* channel AMS */
69 	/* end of channel specific data */
70 
71 	UINT32		AMmask;					/* LFO Amplitude Modulation enable mask */
72 	UINT32		state;					/* Envelope state: 4-attack(AR) 3-decay(D1R) 2-sustain(D2R) 1-release(RR) 0-off */
73 	UINT8		eg_sh_ar;				/*  (attack state) */
74 	UINT8		eg_sel_ar;				/*  (attack state) */
75 	UINT32		tl;						/* Total attenuation Level */
76 	INT32		volume;					/* current envelope attenuation level */
77 	UINT8		eg_sh_d1r;				/*  (decay state) */
78 	UINT8		eg_sel_d1r;				/*  (decay state) */
79 	UINT32		d1l;					/* envelope switches to sustain state after reaching this level */
80 	UINT8		eg_sh_d2r;				/*  (sustain state) */
81 	UINT8		eg_sel_d2r;				/*  (sustain state) */
82 	UINT8		eg_sh_rr;				/*  (release state) */
83 	UINT8		eg_sel_rr;				/*  (release state) */
84 
85 	UINT32		key;					/* 0=last key was KEY OFF, 1=last key was KEY ON */
86 
87 	UINT32		ks;						/* key scale    */
88 	UINT32		ar;						/* attack rate  */
89 	UINT32		d1r;					/* decay rate   */
90 	UINT32		d2r;					/* sustain rate */
91 	UINT32		rr;						/* release rate */
92 
93 	UINT32		reserved0;				/**/
94 	UINT32		reserved1;				/**/
95 
96 } YM2151Operator;
97 
98 
99 typedef struct
100 {
101 	YM2151Operator	oper[32];			/* the 32 operators */
102 
103 	UINT32		pan[16];				/* channels output masks (0xffffffff = enable) */
104 
105 	UINT32		eg_cnt;					/* global envelope generator counter */
106 	UINT32		eg_timer;				/* global envelope generator counter works at frequency = chipclock/64/3 */
107 	UINT32		eg_timer_add;			/* step of eg_timer */
108 	UINT32		eg_timer_overflow;		/* envelope generator timer overlfows every 3 samples (on real chip) */
109 
110 	UINT32		lfo_phase;				/* accumulated LFO phase (0 to 255) */
111 	UINT32		lfo_timer;				/* LFO timer						*/
112 	UINT32		lfo_timer_add;			/* step of lfo_timer				*/
113 	UINT32		lfo_overflow;			/* LFO generates new output when lfo_timer reaches this value */
114 	UINT32		lfo_counter;			/* LFO phase increment counter		*/
115 	UINT32		lfo_counter_add;		/* step of lfo_counter				*/
116 	UINT8		lfo_wsel;				/* LFO waveform (0-saw, 1-square, 2-triangle, 3-random noise) */
117 	UINT8		amd;					/* LFO Amplitude Modulation Depth	*/
118 	INT8		pmd;					/* LFO Phase Modulation Depth		*/
119 	UINT32		lfa;					/* LFO current AM output			*/
120 	INT32		lfp;					/* LFO current PM output			*/
121 
122 	UINT8		test;					/* TEST register */
123 	UINT8		ct;						/* output control pins (bit1-CT2, bit0-CT1) */
124 
125 	UINT32		noise;					/* noise enable/period register (bit 7 - noise enable, bits 4-0 - noise period */
126 	UINT32		noise_rng;				/* 17 bit noise shift register */
127 	UINT32		noise_p;				/* current noise 'phase'*/
128 	UINT32		noise_f;				/* current noise period */
129 
130 	UINT32		csm_req;				/* CSM  KEY ON / KEY OFF sequence request */
131 
132 	UINT32		irq_enable;				/* IRQ enable for timer B (bit 3) and timer A (bit 2); bit 7 - CSM mode (keyon to all slots, everytime timer A overflows) */
133 	UINT32		status;					/* chip status (BUSY, IRQ Flags) */
134 	UINT8		connect[8];				/* channels connections */
135 
136 //#ifdef USE_MAME_TIMERS
137 /* ASG 980324 -- added for tracking timers */
138 	INT32       UseBurnTimer;
139 	void        (*timer_callback)(INT32, double);
140 	INT32		timer_A;                // Timer A / B enable/disable
141 	INT32		timer_B;                // ""
142 	double		timer_A_time[1024];		/* timer A times for MAME/FM Timers */
143 	double		timer_B_time[256];		/* timer B times for MAME/FM Timers */
144 //#else
145 	UINT8		tim_A;					/* timer A enable (0-disabled) */
146 	UINT8		tim_B;					/* timer B enable (0-disabled) */
147 	double		tim_A_val;				/* current value of timer A */
148 	double		tim_B_val;				/* current value of timer B */
149 	double		tim_A_tab[1024];		/* timer A deltas */
150 	double		tim_B_tab[256];			/* timer B deltas */
151 //#endif
152 	UINT32		timer_A_index;			/* timer A index */
153 	UINT32		timer_B_index;			/* timer B index */
154 	UINT32		timer_A_index_old;		/* timer A previous index */
155 	UINT32		timer_B_index_old;		/* timer B previous index */
156 
157 	double      timer_sync;             /* sync to interleave for better timerb resolution */
158 
159 	/*	Frequency-deltas to get the closest frequency possible.
160 	*	There are 11 octaves because of DT2 (max 950 cents over base frequency)
161 	*	and LFO phase modulation (max 800 cents below AND over base frequency)
162 	*	Summary:   octave  explanation
163 	*              0       note code - LFO PM
164 	*              1       note code
165 	*              2       note code
166 	*              3       note code
167 	*              4       note code
168 	*              5       note code
169 	*              6       note code
170 	*              7       note code
171 	*              8       note code
172 	*              9       note code + DT2 + LFO PM
173 	*              10      note code + DT2 + LFO PM
174 	*/
175 	UINT32		freq[11*768];			/* 11 octaves, 768 'cents' per octave */
176 
177 	/*	Frequency deltas for DT1. These deltas alter operator frequency
178 	*	after it has been taken from frequency-deltas table.
179 	*/
180 	INT32		dt1_freq[8*32];			/* 8 DT1 levels, 32 KC values */
181 
182 	UINT32		noise_tab[32];			/* 17bit Noise Generator periods */
183 
184 	void (*irqhandler)(int irq);		/* IRQ function handler */
185 	write8_handler porthandler;		/* port write function handler */
186 
187 	unsigned int clock;					/* chip clock in Hz (passed from 2151intf.c) */
188 	unsigned int sampfreq;				/* sampling frequency in Hz (passed from 2151intf.c) */
189 
190 } YM2151;
191 
192 
193 #define FREQ_SH			16  /* 16.16 fixed point (frequency calculations) */
194 #define EG_SH			16  /* 16.16 fixed point (envelope generator timing) */
195 #define LFO_SH			10  /* 22.10 fixed point (LFO calculations)       */
196 #define TIMER_SH		16  /* 16.16 fixed point (timers calculations)    */
197 
198 #define FREQ_MASK		((1<<FREQ_SH)-1)
199 
200 #define ENV_BITS		10
201 #define ENV_LEN			(1<<ENV_BITS)
202 #define ENV_STEP		(128.0/ENV_LEN)
203 
204 #define MAX_ATT_INDEX	(ENV_LEN-1) /* 1023 */
205 #define MIN_ATT_INDEX	(0)			/* 0 */
206 
207 #define EG_ATT			4
208 #define EG_DEC			3
209 #define EG_SUS			2
210 #define EG_REL			1
211 #define EG_OFF			0
212 
213 #define SIN_BITS		10
214 #define SIN_LEN			(1<<SIN_BITS)
215 #define SIN_MASK		(SIN_LEN-1)
216 
217 #define TL_RES_LEN		(256) /* 8 bits addressing (real chip) */
218 
219 
220 #if (SAMPLE_BITS==16)
221 	#define FINAL_SH	(0)
222 	#define MAXOUT		(+32767)
223 	#define MINOUT		(-32768)
224 #else
225 	#define FINAL_SH	(8)
226 	#define MAXOUT		(+127)
227 	#define MINOUT		(-128)
228 #endif
229 
230 
231 /*	TL_TAB_LEN is calculated as:
232 *	13 - sinus amplitude bits     (Y axis)
233 *	2  - sinus sign bit           (Y axis)
234 *	TL_RES_LEN - sinus resolution (X axis)
235 */
236 #define TL_TAB_LEN (13*2*TL_RES_LEN)
237 static signed int tl_tab[TL_TAB_LEN];
238 
239 #define ENV_QUIET		(TL_TAB_LEN>>3)
240 
241 /* sin waveform table in 'decibel' scale */
242 static unsigned int sin_tab[SIN_LEN];
243 
244 
245 /* translate from D1L to volume index (16 D1L levels) */
246 static UINT32 d1l_tab[16];
247 
248 
249 #define RATE_STEPS (8)
250 static UINT8 eg_inc[19*RATE_STEPS]={
251 
252 /*cycle:0 1  2 3  4 5  6 7*/
253 
254 /* 0 */ 0,1, 0,1, 0,1, 0,1, /* rates 00..11 0 (increment by 0 or 1) */
255 /* 1 */ 0,1, 0,1, 1,1, 0,1, /* rates 00..11 1 */
256 /* 2 */ 0,1, 1,1, 0,1, 1,1, /* rates 00..11 2 */
257 /* 3 */ 0,1, 1,1, 1,1, 1,1, /* rates 00..11 3 */
258 
259 /* 4 */ 1,1, 1,1, 1,1, 1,1, /* rate 12 0 (increment by 1) */
260 /* 5 */ 1,1, 1,2, 1,1, 1,2, /* rate 12 1 */
261 /* 6 */ 1,2, 1,2, 1,2, 1,2, /* rate 12 2 */
262 /* 7 */ 1,2, 2,2, 1,2, 2,2, /* rate 12 3 */
263 
264 /* 8 */ 2,2, 2,2, 2,2, 2,2, /* rate 13 0 (increment by 2) */
265 /* 9 */ 2,2, 2,4, 2,2, 2,4, /* rate 13 1 */
266 /*10 */ 2,4, 2,4, 2,4, 2,4, /* rate 13 2 */
267 /*11 */ 2,4, 4,4, 2,4, 4,4, /* rate 13 3 */
268 
269 /*12 */ 4,4, 4,4, 4,4, 4,4, /* rate 14 0 (increment by 4) */
270 /*13 */ 4,4, 4,8, 4,4, 4,8, /* rate 14 1 */
271 /*14 */ 4,8, 4,8, 4,8, 4,8, /* rate 14 2 */
272 /*15 */ 4,8, 8,8, 4,8, 8,8, /* rate 14 3 */
273 
274 /*16 */ 8,8, 8,8, 8,8, 8,8, /* rates 15 0, 15 1, 15 2, 15 3 (increment by 8) */
275 /*17 */ 16,16,16,16,16,16,16,16, /* rates 15 2, 15 3 for attack */
276 /*18 */ 0,0, 0,0, 0,0, 0,0, /* infinity rates for attack and decay(s) */
277 };
278 
279 
280 #define O(a) (a*RATE_STEPS)
281 
282 /*note that there is no O(17) in this table - it's directly in the code */
283 static UINT8 eg_rate_select[32+64+32]={	/* Envelope Generator rates (32 + 64 rates + 32 RKS) */
284 /* 32 dummy (infinite time) rates */
285 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
286 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
287 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
288 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
289 
290 /* rates 00-11 */
291 O( 0),O( 1),O( 2),O( 3),
292 O( 0),O( 1),O( 2),O( 3),
293 O( 0),O( 1),O( 2),O( 3),
294 O( 0),O( 1),O( 2),O( 3),
295 O( 0),O( 1),O( 2),O( 3),
296 O( 0),O( 1),O( 2),O( 3),
297 O( 0),O( 1),O( 2),O( 3),
298 O( 0),O( 1),O( 2),O( 3),
299 O( 0),O( 1),O( 2),O( 3),
300 O( 0),O( 1),O( 2),O( 3),
301 O( 0),O( 1),O( 2),O( 3),
302 O( 0),O( 1),O( 2),O( 3),
303 
304 /* rate 12 */
305 O( 4),O( 5),O( 6),O( 7),
306 
307 /* rate 13 */
308 O( 8),O( 9),O(10),O(11),
309 
310 /* rate 14 */
311 O(12),O(13),O(14),O(15),
312 
313 /* rate 15 */
314 O(16),O(16),O(16),O(16),
315 
316 /* 32 dummy rates (same as 15 3) */
317 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
318 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
319 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
320 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16)
321 
322 };
323 #undef O
324 
325 /*rate  0,    1,    2,   3,   4,   5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15*/
326 /*shift 11,   10,   9,   8,   7,   6,  5,  4,  3,  2, 1,  0,  0,  0,  0,  0 */
327 /*mask  2047, 1023, 511, 255, 127, 63, 31, 15, 7,  3, 1,  0,  0,  0,  0,  0 */
328 
329 #define O(a) (a*1)
330 static UINT8 eg_rate_shift[32+64+32]={	/* Envelope Generator counter shifts (32 + 64 rates + 32 RKS) */
331 /* 32 infinite time rates */
332 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
333 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
334 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
335 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
336 
337 
338 /* rates 00-11 */
339 O(11),O(11),O(11),O(11),
340 O(10),O(10),O(10),O(10),
341 O( 9),O( 9),O( 9),O( 9),
342 O( 8),O( 8),O( 8),O( 8),
343 O( 7),O( 7),O( 7),O( 7),
344 O( 6),O( 6),O( 6),O( 6),
345 O( 5),O( 5),O( 5),O( 5),
346 O( 4),O( 4),O( 4),O( 4),
347 O( 3),O( 3),O( 3),O( 3),
348 O( 2),O( 2),O( 2),O( 2),
349 O( 1),O( 1),O( 1),O( 1),
350 O( 0),O( 0),O( 0),O( 0),
351 
352 /* rate 12 */
353 O( 0),O( 0),O( 0),O( 0),
354 
355 /* rate 13 */
356 O( 0),O( 0),O( 0),O( 0),
357 
358 /* rate 14 */
359 O( 0),O( 0),O( 0),O( 0),
360 
361 /* rate 15 */
362 O( 0),O( 0),O( 0),O( 0),
363 
364 /* 32 dummy rates (same as 15 3) */
365 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
366 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
367 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
368 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0)
369 
370 };
371 #undef O
372 
373 /*	DT2 defines offset in cents from base note
374 *
375 *	This table defines offset in frequency-deltas table.
376 *	User's Manual page 22
377 *
378 *	Values below were calculated using formula: value =  orig.val / 1.5625
379 *
380 *	DT2=0 DT2=1 DT2=2 DT2=3
381 *	0     600   781   950
382 */
383 static UINT32 dt2_tab[4] = { 0, 384, 500, 608 };
384 
385 /*	DT1 defines offset in Hertz from base note
386 *	This table is converted while initialization...
387 *	Detune table shown in YM2151 User's Manual is wrong (verified on the real chip)
388 */
389 
390 static UINT8 dt1_tab[4*32] = { /* 4*32 DT1 values */
391 /* DT1=0 */
392   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
393   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
394 
395 /* DT1=1 */
396   0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
397   2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
398 
399 /* DT1=2 */
400   1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5,
401   5, 6, 6, 7, 8, 8, 9,10,11,12,13,14,16,16,16,16,
402 
403 /* DT1=3 */
404   2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7,
405   8, 8, 9,10,11,12,13,14,16,17,19,20,22,22,22,22
406 };
407 
408 static UINT16 phaseinc_rom[768]={
409 1299,1300,1301,1302,1303,1304,1305,1306,1308,1309,1310,1311,1313,1314,1315,1316,
410 1318,1319,1320,1321,1322,1323,1324,1325,1327,1328,1329,1330,1332,1333,1334,1335,
411 1337,1338,1339,1340,1341,1342,1343,1344,1346,1347,1348,1349,1351,1352,1353,1354,
412 1356,1357,1358,1359,1361,1362,1363,1364,1366,1367,1368,1369,1371,1372,1373,1374,
413 1376,1377,1378,1379,1381,1382,1383,1384,1386,1387,1388,1389,1391,1392,1393,1394,
414 1396,1397,1398,1399,1401,1402,1403,1404,1406,1407,1408,1409,1411,1412,1413,1414,
415 1416,1417,1418,1419,1421,1422,1423,1424,1426,1427,1429,1430,1431,1432,1434,1435,
416 1437,1438,1439,1440,1442,1443,1444,1445,1447,1448,1449,1450,1452,1453,1454,1455,
417 1458,1459,1460,1461,1463,1464,1465,1466,1468,1469,1471,1472,1473,1474,1476,1477,
418 1479,1480,1481,1482,1484,1485,1486,1487,1489,1490,1492,1493,1494,1495,1497,1498,
419 1501,1502,1503,1504,1506,1507,1509,1510,1512,1513,1514,1515,1517,1518,1520,1521,
420 1523,1524,1525,1526,1528,1529,1531,1532,1534,1535,1536,1537,1539,1540,1542,1543,
421 1545,1546,1547,1548,1550,1551,1553,1554,1556,1557,1558,1559,1561,1562,1564,1565,
422 1567,1568,1569,1570,1572,1573,1575,1576,1578,1579,1580,1581,1583,1584,1586,1587,
423 1590,1591,1592,1593,1595,1596,1598,1599,1601,1602,1604,1605,1607,1608,1609,1610,
424 1613,1614,1615,1616,1618,1619,1621,1622,1624,1625,1627,1628,1630,1631,1632,1633,
425 1637,1638,1639,1640,1642,1643,1645,1646,1648,1649,1651,1652,1654,1655,1656,1657,
426 1660,1661,1663,1664,1666,1667,1669,1670,1672,1673,1675,1676,1678,1679,1681,1682,
427 1685,1686,1688,1689,1691,1692,1694,1695,1697,1698,1700,1701,1703,1704,1706,1707,
428 1709,1710,1712,1713,1715,1716,1718,1719,1721,1722,1724,1725,1727,1728,1730,1731,
429 1734,1735,1737,1738,1740,1741,1743,1744,1746,1748,1749,1751,1752,1754,1755,1757,
430 1759,1760,1762,1763,1765,1766,1768,1769,1771,1773,1774,1776,1777,1779,1780,1782,
431 1785,1786,1788,1789,1791,1793,1794,1796,1798,1799,1801,1802,1804,1806,1807,1809,
432 1811,1812,1814,1815,1817,1819,1820,1822,1824,1825,1827,1828,1830,1832,1833,1835,
433 1837,1838,1840,1841,1843,1845,1846,1848,1850,1851,1853,1854,1856,1858,1859,1861,
434 1864,1865,1867,1868,1870,1872,1873,1875,1877,1879,1880,1882,1884,1885,1887,1888,
435 1891,1892,1894,1895,1897,1899,1900,1902,1904,1906,1907,1909,1911,1912,1914,1915,
436 1918,1919,1921,1923,1925,1926,1928,1930,1932,1933,1935,1937,1939,1940,1942,1944,
437 1946,1947,1949,1951,1953,1954,1956,1958,1960,1961,1963,1965,1967,1968,1970,1972,
438 1975,1976,1978,1980,1982,1983,1985,1987,1989,1990,1992,1994,1996,1997,1999,2001,
439 2003,2004,2006,2008,2010,2011,2013,2015,2017,2019,2021,2022,2024,2026,2028,2029,
440 2032,2033,2035,2037,2039,2041,2043,2044,2047,2048,2050,2052,2054,2056,2058,2059,
441 2062,2063,2065,2067,2069,2071,2073,2074,2077,2078,2080,2082,2084,2086,2088,2089,
442 2092,2093,2095,2097,2099,2101,2103,2104,2107,2108,2110,2112,2114,2116,2118,2119,
443 2122,2123,2125,2127,2129,2131,2133,2134,2137,2139,2141,2142,2145,2146,2148,2150,
444 2153,2154,2156,2158,2160,2162,2164,2165,2168,2170,2172,2173,2176,2177,2179,2181,
445 2185,2186,2188,2190,2192,2194,2196,2197,2200,2202,2204,2205,2208,2209,2211,2213,
446 2216,2218,2220,2222,2223,2226,2227,2230,2232,2234,2236,2238,2239,2242,2243,2246,
447 2249,2251,2253,2255,2256,2259,2260,2263,2265,2267,2269,2271,2272,2275,2276,2279,
448 2281,2283,2285,2287,2288,2291,2292,2295,2297,2299,2301,2303,2304,2307,2308,2311,
449 2315,2317,2319,2321,2322,2325,2326,2329,2331,2333,2335,2337,2338,2341,2342,2345,
450 2348,2350,2352,2354,2355,2358,2359,2362,2364,2366,2368,2370,2371,2374,2375,2378,
451 2382,2384,2386,2388,2389,2392,2393,2396,2398,2400,2402,2404,2407,2410,2411,2414,
452 2417,2419,2421,2423,2424,2427,2428,2431,2433,2435,2437,2439,2442,2445,2446,2449,
453 2452,2454,2456,2458,2459,2462,2463,2466,2468,2470,2472,2474,2477,2480,2481,2484,
454 2488,2490,2492,2494,2495,2498,2499,2502,2504,2506,2508,2510,2513,2516,2517,2520,
455 2524,2526,2528,2530,2531,2534,2535,2538,2540,2542,2544,2546,2549,2552,2553,2556,
456 2561,2563,2565,2567,2568,2571,2572,2575,2577,2579,2581,2583,2586,2589,2590,2593
457 };
458 
459 
460 /*
461 	Noise LFO waveform.
462 
463 	Here are just 256 samples out of much longer data.
464 
465 	It does NOT repeat every 256 samples on real chip and I wasnt able to find
466 	the point where it repeats (even in strings as long as 131072 samples).
467 
468 	I only put it here because its better than nothing and perhaps
469 	someone might be able to figure out the real algorithm.
470 
471 
472 	Note that (due to the way the LFO output is calculated) it is quite
473 	possible that two values: 0x80 and 0x00 might be wrong in this table.
474 	To be exact:
475 		some 0x80 could be 0x81 as well as some 0x00 could be 0x01.
476 */
477 
478 static UINT8 lfo_noise_waveform[256] = {
479 0xFF,0xEE,0xD3,0x80,0x58,0xDA,0x7F,0x94,0x9E,0xE3,0xFA,0x00,0x4D,0xFA,0xFF,0x6A,
480 0x7A,0xDE,0x49,0xF6,0x00,0x33,0xBB,0x63,0x91,0x60,0x51,0xFF,0x00,0xD8,0x7F,0xDE,
481 0xDC,0x73,0x21,0x85,0xB2,0x9C,0x5D,0x24,0xCD,0x91,0x9E,0x76,0x7F,0x20,0xFB,0xF3,
482 0x00,0xA6,0x3E,0x42,0x27,0x69,0xAE,0x33,0x45,0x44,0x11,0x41,0x72,0x73,0xDF,0xA2,
483 
484 0x32,0xBD,0x7E,0xA8,0x13,0xEB,0xD3,0x15,0xDD,0xFB,0xC9,0x9D,0x61,0x2F,0xBE,0x9D,
485 0x23,0x65,0x51,0x6A,0x84,0xF9,0xC9,0xD7,0x23,0xBF,0x65,0x19,0xDC,0x03,0xF3,0x24,
486 0x33,0xB6,0x1E,0x57,0x5C,0xAC,0x25,0x89,0x4D,0xC5,0x9C,0x99,0x15,0x07,0xCF,0xBA,
487 0xC5,0x9B,0x15,0x4D,0x8D,0x2A,0x1E,0x1F,0xEA,0x2B,0x2F,0x64,0xA9,0x50,0x3D,0xAB,
488 
489 0x50,0x77,0xE9,0xC0,0xAC,0x6D,0x3F,0xCA,0xCF,0x71,0x7D,0x80,0xA6,0xFD,0xFF,0xB5,
490 0xBD,0x6F,0x24,0x7B,0x00,0x99,0x5D,0xB1,0x48,0xB0,0x28,0x7F,0x80,0xEC,0xBF,0x6F,
491 0x6E,0x39,0x90,0x42,0xD9,0x4E,0x2E,0x12,0x66,0xC8,0xCF,0x3B,0x3F,0x10,0x7D,0x79,
492 0x00,0xD3,0x1F,0x21,0x93,0x34,0xD7,0x19,0x22,0xA2,0x08,0x20,0xB9,0xB9,0xEF,0x51,
493 
494 0x99,0xDE,0xBF,0xD4,0x09,0x75,0xE9,0x8A,0xEE,0xFD,0xE4,0x4E,0x30,0x17,0xDF,0xCE,
495 0x11,0xB2,0x28,0x35,0xC2,0x7C,0x64,0xEB,0x91,0x5F,0x32,0x0C,0x6E,0x00,0xF9,0x92,
496 0x19,0xDB,0x8F,0xAB,0xAE,0xD6,0x12,0xC4,0x26,0x62,0xCE,0xCC,0x0A,0x03,0xE7,0xDD,
497 0xE2,0x4D,0x8A,0xA6,0x46,0x95,0x0F,0x8F,0xF5,0x15,0x97,0x32,0xD4,0x28,0x1E,0x55
498 };
499 
500 
501 static YM2151 * YMPSG = NULL;	/* array of YM2151's */
502 static unsigned int YMNumChips;	/* total # of YM2151's emulated */
503 
504 
505 /* these variables stay here for speedup purposes only */
506 static YM2151 * PSG;
507 static signed int chanout[8];
508 static signed int m2,c1,c2; /* Phase Modulation input for operators 2,3,4 */
509 static signed int mem;		/* one sample delay memory */
510 
511 
512 /* save output as raw 16-bit sample */
513 /* #define SAVE_SAMPLE */
514 /* #define SAVE_SEPARATE_CHANNELS */
515 #if defined SAVE_SAMPLE || defined SAVE_SEPARATE_CHANNELS
516 static FILE *sample[9];
517 #endif
518 
519 
520 /* own PI definition */
521 #ifdef PI
522 	#undef PI
523 #endif
524 #define PI 3.14159265358979323846
525 
init_tables(void)526 static void init_tables(void)
527 {
528 	signed int i,x,n;
529 	double o,m;
530 
531 	for (x=0; x<TL_RES_LEN; x++)
532 	{
533 		m = (1<<16) / pow(2, (x+1) * (ENV_STEP/4.0) / 8.0);
534 		m = floor(m);
535 
536 		/* we never reach (1<<16) here due to the (x+1) */
537 		/* result fits within 16 bits at maximum */
538 
539 		n = (int)m;		/* 16 bits here */
540 		n >>= 4;		/* 12 bits here */
541 		if (n&1)		/* round to closest */
542 			n = (n>>1)+1;
543 		else
544 			n = n>>1;
545 						/* 11 bits here (rounded) */
546 		n <<= 2;		/* 13 bits here (as in real chip) */
547 		tl_tab[ x*2 + 0 ] = n;
548 		tl_tab[ x*2 + 1 ] = -tl_tab[ x*2 + 0 ];
549 
550 		for (i=1; i<13; i++)
551 		{
552 			tl_tab[ x*2+0 + i*2*TL_RES_LEN ] =  tl_tab[ x*2+0 ]>>i;
553 			tl_tab[ x*2+1 + i*2*TL_RES_LEN ] = -tl_tab[ x*2+0 + i*2*TL_RES_LEN ];
554 		}
555 	#if 0
556 		logerror("tl %04i", x*2);
557 		for (i=0; i<13; i++)
558 			logerror(", [%02i] %4i", i*2, tl_tab[ x*2 /*+1*/ + i*2*TL_RES_LEN ]);
559 		logerror("\n");
560 	#endif
561 	}
562 	/*logerror("TL_TAB_LEN = %i (%i bytes)\n",TL_TAB_LEN, (int)sizeof(tl_tab));*/
563 	/*logerror("ENV_QUIET= %i\n",ENV_QUIET );*/
564 
565 
566 	for (i=0; i<SIN_LEN; i++)
567 	{
568 		/* non-standard sinus */
569 		m = sin( ((i*2)+1) * PI / SIN_LEN ); /* verified on the real chip */
570 
571 		/* we never reach zero here due to ((i*2)+1) */
572 
573 		if (m>0.0)
574 			o = 8*log(1.0/m)/log(2.0);	/* convert to 'decibels' */
575 		else
576 			o = 8*log(-1.0/m)/log(2.0);	/* convert to 'decibels' */
577 
578 		o = o / (ENV_STEP/4);
579 
580 		n = (int)(2.0*o);
581 		if (n&1)						/* round to closest */
582 			n = (n>>1)+1;
583 		else
584 			n = n>>1;
585 
586 		sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
587 		/*logerror("sin [0x%4x]= %4i (tl_tab value=%8x)\n", i, sin_tab[i],tl_tab[sin_tab[i]]);*/
588 	}
589 
590 
591 	/* calculate d1l_tab table */
592 	for (i=0; i<16; i++)
593 	{
594 		m = (i!=15 ? i : i+16) * (4.0/ENV_STEP);   /* every 3 'dB' except for all bits = 1 = 45+48 'dB' */
595 		d1l_tab[i] = m;
596 		/*logerror("d1l_tab[%02x]=%08x\n",i,d1l_tab[i] );*/
597 	}
598 
599 #ifdef SAVE_SAMPLE
600 	sample[8]=fopen("sampsum.pcm","wb");
601 #endif
602 #ifdef SAVE_SEPARATE_CHANNELS
603 	sample[0]=fopen("samp0.pcm","wb");
604 	sample[1]=fopen("samp1.pcm","wb");
605 	sample[2]=fopen("samp2.pcm","wb");
606 	sample[3]=fopen("samp3.pcm","wb");
607 	sample[4]=fopen("samp4.pcm","wb");
608 	sample[5]=fopen("samp5.pcm","wb");
609 	sample[6]=fopen("samp6.pcm","wb");
610 	sample[7]=fopen("samp7.pcm","wb");
611 #endif
612 }
613 
init_chip_tables(YM2151 * chip)614 static void init_chip_tables(YM2151 *chip)
615 {
616 	int i,j;
617 	double mult,pom,phaseinc,Hz;
618 	double scaler;
619 
620 	scaler = ( (double)chip->clock / 64.0 ) / ( (double)chip->sampfreq );
621 	/*logerror("scaler    = %20.15f\n", scaler);*/
622 
623 
624 	/* this loop calculates Hertz values for notes from c-0 to b-7 */
625 	/* including 64 'cents' (100/64 that is 1.5625 of real cent) per note */
626 	/* i*100/64/1200 is equal to i/768 */
627 
628 	/* real chip works with 10 bits fixed point values (10.10) */
629 	mult = (1<<(FREQ_SH-10)); /* -10 because phaseinc_rom table values are already in 10.10 format */
630 
631 	for (i=0; i<768; i++)
632 	{
633 		/* 3.4375 Hz is note A; C# is 4 semitones higher */
634 		Hz = 1000;
635 #if 0
636 /* Hz is close, but not perfect */
637 		//Hz = scaler * 3.4375 * pow (2, (i + 4 * 64 ) / 768.0 );
638 		/* calculate phase increment */
639 		phaseinc = (Hz*SIN_LEN) / (double)chip->sampfreq;
640 #endif
641 
642 		phaseinc = phaseinc_rom[i];	/* real chip phase increment */
643 		phaseinc *= scaler;			/* adjust */
644 
645 
646 		/* octave 2 - reference octave */
647 		chip->freq[ 768+2*768+i ] = ((int)(phaseinc*mult)) & 0xffffffc0; /* adjust to X.10 fixed point */
648 		/* octave 0 and octave 1 */
649 		for (j=0; j<2; j++)
650 		{
651 			chip->freq[768 + j*768 + i] = (chip->freq[ 768+2*768+i ] >> (2-j) ) & 0xffffffc0; /* adjust to X.10 fixed point */
652 		}
653 		/* octave 3 to 7 */
654 		for (j=3; j<8; j++)
655 		{
656 			chip->freq[768 + j*768 + i] = chip->freq[ 768+2*768+i ] << (j-2);
657 		}
658 
659 	#if 0
660 			pom = (double)chip->freq[ 768+2*768+i ] / ((double)(1<<FREQ_SH));
661 			pom = pom * (double)chip->sampfreq / (double)SIN_LEN;
662 			logerror("1freq[%4i][%08x]= real %20.15f Hz  emul %20.15f Hz\n", i, chip->freq[ 768+2*768+i ], Hz, pom);
663 	#endif
664 	}
665 
666 	/* octave -1 (all equal to: oct 0, _KC_00_, _KF_00_) */
667 	for (i=0; i<768; i++)
668 	{
669 		chip->freq[ 0*768 + i ] = chip->freq[1*768+0];
670 	}
671 
672 	/* octave 8 and 9 (all equal to: oct 7, _KC_14_, _KF_63_) */
673 	for (j=8; j<10; j++)
674 	{
675 		for (i=0; i<768; i++)
676 		{
677 			chip->freq[768+ j*768 + i ] = chip->freq[768 + 8*768 -1];
678 		}
679 	}
680 
681 #if 0
682 		for (i=0; i<11*768; i++)
683 		{
684 			pom = (double)chip->freq[i] / ((double)(1<<FREQ_SH));
685 			pom = pom * (double)chip->sampfreq / (double)SIN_LEN;
686 			logerror("freq[%4i][%08x]= emul %20.15f Hz\n", i, chip->freq[i], pom);
687 		}
688 #endif
689 
690 	mult = (1<<FREQ_SH);
691 	for (j=0; j<4; j++)
692 	{
693 		for (i=0; i<32; i++)
694 		{
695 			Hz = ( (double)dt1_tab[j*32+i] * ((double)chip->clock/64.0) ) / (double)(1<<20);
696 
697 			/*calculate phase increment*/
698 			phaseinc = (Hz*SIN_LEN) / (double)chip->sampfreq;
699 
700 			/*positive and negative values*/
701 			chip->dt1_freq[ (j+0)*32 + i ] = phaseinc * mult;
702 			chip->dt1_freq[ (j+4)*32 + i ] = -chip->dt1_freq[ (j+0)*32 + i ];
703 
704 #if 0
705 			{
706 				int x = j*32 + i;
707 				pom = (double)chip->dt1_freq[x] / mult;
708 				pom = pom * (double)chip->sampfreq / (double)SIN_LEN;
709 				logerror("DT1(%03i)[%02i %02i][%08x]= real %19.15f Hz  emul %19.15f Hz\n",
710 						 x, j, i, chip->dt1_freq[x], Hz, pom);
711 			}
712 #endif
713 		}
714 	}
715 
716 
717 	/* calculate timers' deltas */
718 	/* User's Manual pages 15,16  */
719 	mult = (1<<TIMER_SH);
720 	for (i=0; i<1024; i++)
721 	{
722 		/* ASG 980324: changed to compute both tim_A_tab and timer_A_time */
723 		pom= ( 64.0  *  (1024.0-i) / (double)chip->clock );
724         //#ifdef USE_MAME_TIMERS
725 			chip->timer_A_time[i] = pom;
726 		//#else
727 			chip->tim_A_tab[i] = pom * (double)chip->sampfreq * mult;  /* number of samples that timer period takes (fixed point) */
728 		//#endif
729 	}
730 	for (i=0; i<256; i++)
731 	{
732 		/* ASG 980324: changed to compute both tim_B_tab and timer_B_time */
733 		pom= ( 1024.0 * (256.0-i)  / (double)chip->clock );
734 		//#ifdef USE_MAME_TIMERS
735 			chip->timer_B_time[i] = pom;
736 		//#else
737 			if (chip->timer_sync != 0)
738 				chip->tim_B_tab[i] = pom * (double)chip->timer_sync * mult;  /* number of samples that timer period takes (fixed point) */
739 			else
740 				chip->tim_B_tab[i] = pom * (double)chip->sampfreq * mult;  /* number of samples that timer period takes (fixed point) */
741 		//#endif
742 	}
743 
744 	/* calculate noise periods table */
745 	scaler = ( (double)chip->clock / 64.0 ) / ( (double)chip->sampfreq );
746 	for (i=0; i<32; i++)
747 	{
748 		j = (i!=31 ? i : 30);				/* rate 30 and 31 are the same */
749 		j = 32-j;
750 		j = (65536.0 / (double)(j*32.0));	/* number of samples per one shift of the shift register */
751 		/*chip->noise_tab[i] = j * 64;*/	/* number of chip clock cycles per one shift */
752 		chip->noise_tab[i] = j * 64 * scaler;
753 		/*logerror("noise_tab[%02x]=%08x\n", i, chip->noise_tab[i]);*/
754 	}
755 }
756 
757 #define KEY_ON(op, key_set){									\
758 		if (!(op)->key)											\
759 		{														\
760 			(op)->phase = 0;			/* clear phase */		\
761 			(op)->state = EG_ATT;		/* KEY ON = attack */	\
762 			(op)->volume += (~(op)->volume *					\
763                            (eg_inc[(op)->eg_sel_ar + ((PSG->eg_cnt>>(op)->eg_sh_ar)&7)])	\
764                           ) >>4;								\
765 			if ((op)->volume <= MIN_ATT_INDEX)					\
766 			{													\
767 				(op)->volume = MIN_ATT_INDEX;					\
768 				(op)->state = EG_DEC;							\
769 			}													\
770 		}														\
771 		(op)->key |= key_set;									\
772 }
773 
774 #define KEY_OFF(op, key_clr){									\
775 		if ((op)->key)											\
776 		{														\
777 			(op)->key &= key_clr;								\
778 			if (!(op)->key)										\
779 			{													\
780 				if ((op)->state>EG_REL)							\
781 					(op)->state = EG_REL;/* KEY OFF = release */\
782 			}													\
783 		}														\
784 }
785 
envelope_KONKOFF(YM2151Operator * op,int v)786 INLINE void envelope_KONKOFF(YM2151Operator * op, int v)
787 {
788 	if (v&0x08)	/* M1 */
789 		KEY_ON (op+0, 1)
790 	else
791 		KEY_OFF(op+0,~1)
792 
793 	if (v&0x20)	/* M2 */
794 		KEY_ON (op+1, 1)
795 	else
796 		KEY_OFF(op+1,~1)
797 
798 	if (v&0x10)	/* C1 */
799 		KEY_ON (op+2, 1)
800 	else
801 		KEY_OFF(op+2,~1)
802 
803 	if (v&0x40)	/* C2 */
804 		KEY_ON (op+3, 1)
805 	else
806 		KEY_OFF(op+3,~1)
807 }
808 
809 
810 //#ifdef USE_MAME_TIMERS
timer_callback_a(int n)811 static void timer_callback_a (int n)
812 {
813 	YM2151 *chip = &YMPSG[n];
814 
815 	//timer_adjust(chip->timer_A, chip->timer_A_time[ chip->timer_A_index ], n, 0);
816 	chip->timer_callback(0, chip->timer_A_time[ chip->timer_A_index ]);
817 
818 	chip->timer_A_index_old = chip->timer_A_index;
819 	if (chip->irq_enable & 0x04)
820 	{
821 		int oldstate = chip->status & 3;
822 		chip->status |= 1;
823 		if ((!oldstate) && (chip->irqhandler)) (*chip->irqhandler)(1);
824 	}
825 	if (chip->irq_enable & 0x80)
826 		chip->csm_req = 2;		/* request KEY ON / KEY OFF sequence */
827 }
timer_callback_b(int n)828 static void timer_callback_b (int n)
829 {
830 	YM2151 *chip = &YMPSG[n];
831 
832 	//timer_adjust(chip->timer_B, chip->timer_B_time[ chip->timer_B_index ], n, 0);
833 	chip->timer_callback(1, chip->timer_B_time[ chip->timer_B_index ]);
834 
835 	chip->timer_B_index_old = chip->timer_B_index;
836 	if (chip->irq_enable & 0x08)
837 	{
838 		int oldstate = chip->status & 3;
839 		chip->status |= 2;
840 		if ((!oldstate) && (chip->irqhandler)) (*chip->irqhandler)(1);
841 	}
842 }
843 
ym2151_timer_over(int num,int timer)844 int ym2151_timer_over(int num, int timer)
845 {
846 	switch (timer) {
847 		case 0: timer_callback_a(0); break;
848 		case 1: timer_callback_b(0); break;
849 	}
850 
851 	return 0;
852 }
853 
854 
855 #if 0
856 static void timer_callback_chip_busy (int n)
857 {
858 	YM2151 *chip = &YMPSG[n];
859 	chip->status &= 0x7f;	/* reset busy flag */
860 }
861 #endif
862 //#endif
863 
864 
865 
866 
867 
868 
set_connect(YM2151Operator * om1,int cha,int v)869 INLINE void set_connect( YM2151Operator *om1, int cha, int v)
870 {
871 	YM2151Operator *om2 = om1+1;
872 	YM2151Operator *oc1 = om1+2;
873 
874 	/* set connect algorithm */
875 
876 	/* MEM is simply one sample delay */
877 
878 	switch( v&7 )
879 	{
880 	case 0:
881 		/* M1---C1---MEM---M2---C2---OUT */
882 		om1->connect = &c1;
883 		oc1->connect = &mem;
884 		om2->connect = &c2;
885 		om1->mem_connect = &m2;
886 		break;
887 
888 	case 1:
889 		/* M1------+-MEM---M2---C2---OUT */
890 		/*      C1-+                     */
891 		om1->connect = &mem;
892 		oc1->connect = &mem;
893 		om2->connect = &c2;
894 		om1->mem_connect = &m2;
895 		break;
896 
897 	case 2:
898 		/* M1-----------------+-C2---OUT */
899 		/*      C1---MEM---M2-+          */
900 		om1->connect = &c2;
901 		oc1->connect = &mem;
902 		om2->connect = &c2;
903 		om1->mem_connect = &m2;
904 		break;
905 
906 	case 3:
907 		/* M1---C1---MEM------+-C2---OUT */
908 		/*                 M2-+          */
909 		om1->connect = &c1;
910 		oc1->connect = &mem;
911 		om2->connect = &c2;
912 		om1->mem_connect = &c2;
913 		break;
914 
915 	case 4:
916 		/* M1---C1-+-OUT */
917 		/* M2---C2-+     */
918 		/* MEM: not used */
919 		om1->connect = &c1;
920 		oc1->connect = &chanout[cha];
921 		om2->connect = &c2;
922 		om1->mem_connect = &mem;	/* store it anywhere where it will not be used */
923 		break;
924 
925 	case 5:
926 		/*    +----C1----+     */
927 		/* M1-+-MEM---M2-+-OUT */
928 		/*    +----C2----+     */
929 		om1->connect = 0;	/* special mark */
930 		oc1->connect = &chanout[cha];
931 		om2->connect = &chanout[cha];
932 		om1->mem_connect = &m2;
933 		break;
934 
935 	case 6:
936 		/* M1---C1-+     */
937 		/*      M2-+-OUT */
938 		/*      C2-+     */
939 		/* MEM: not used */
940 		om1->connect = &c1;
941 		oc1->connect = &chanout[cha];
942 		om2->connect = &chanout[cha];
943 		om1->mem_connect = &mem;	/* store it anywhere where it will not be used */
944 		break;
945 
946 	case 7:
947 		/* M1-+     */
948 		/* C1-+-OUT */
949 		/* M2-+     */
950 		/* C2-+     */
951 		/* MEM: not used*/
952 		om1->connect = &chanout[cha];
953 		oc1->connect = &chanout[cha];
954 		om2->connect = &chanout[cha];
955 		om1->mem_connect = &mem;	/* store it anywhere where it will not be used */
956 		break;
957 	}
958 }
959 
960 
refresh_EG(YM2151Operator * op)961 INLINE void refresh_EG(YM2151Operator * op)
962 {
963 	UINT32 kc;
964 	UINT32 v;
965 
966 	kc = op->kc;
967 
968 	/* v = 32 + 2*RATE + RKS = max 126 */
969 
970 	v = kc >> op->ks;
971 	if ((op->ar+v) < 32+62)
972 	{
973 		op->eg_sh_ar  = eg_rate_shift [op->ar  + v ];
974 		op->eg_sel_ar = eg_rate_select[op->ar  + v ];
975 	}
976 	else
977 	{
978 		op->eg_sh_ar  = 0;
979 		op->eg_sel_ar = 17*RATE_STEPS;
980 	}
981 	op->eg_sh_d1r = eg_rate_shift [op->d1r + v];
982 	op->eg_sel_d1r= eg_rate_select[op->d1r + v];
983 	op->eg_sh_d2r = eg_rate_shift [op->d2r + v];
984 	op->eg_sel_d2r= eg_rate_select[op->d2r + v];
985 	op->eg_sh_rr  = eg_rate_shift [op->rr  + v];
986 	op->eg_sel_rr = eg_rate_select[op->rr  + v];
987 
988 
989 	op+=1;
990 
991 	v = kc >> op->ks;
992 	if ((op->ar+v) < 32+62)
993 	{
994 		op->eg_sh_ar  = eg_rate_shift [op->ar  + v ];
995 		op->eg_sel_ar = eg_rate_select[op->ar  + v ];
996 	}
997 	else
998 	{
999 		op->eg_sh_ar  = 0;
1000 		op->eg_sel_ar = 17*RATE_STEPS;
1001 	}
1002 	op->eg_sh_d1r = eg_rate_shift [op->d1r + v];
1003 	op->eg_sel_d1r= eg_rate_select[op->d1r + v];
1004 	op->eg_sh_d2r = eg_rate_shift [op->d2r + v];
1005 	op->eg_sel_d2r= eg_rate_select[op->d2r + v];
1006 	op->eg_sh_rr  = eg_rate_shift [op->rr  + v];
1007 	op->eg_sel_rr = eg_rate_select[op->rr  + v];
1008 
1009 	op+=1;
1010 
1011 	v = kc >> op->ks;
1012 	if ((op->ar+v) < 32+62)
1013 	{
1014 		op->eg_sh_ar  = eg_rate_shift [op->ar  + v ];
1015 		op->eg_sel_ar = eg_rate_select[op->ar  + v ];
1016 	}
1017 	else
1018 	{
1019 		op->eg_sh_ar  = 0;
1020 		op->eg_sel_ar = 17*RATE_STEPS;
1021 	}
1022 	op->eg_sh_d1r = eg_rate_shift [op->d1r + v];
1023 	op->eg_sel_d1r= eg_rate_select[op->d1r + v];
1024 	op->eg_sh_d2r = eg_rate_shift [op->d2r + v];
1025 	op->eg_sel_d2r= eg_rate_select[op->d2r + v];
1026 	op->eg_sh_rr  = eg_rate_shift [op->rr  + v];
1027 	op->eg_sel_rr = eg_rate_select[op->rr  + v];
1028 
1029 	op+=1;
1030 
1031 	v = kc >> op->ks;
1032 	if ((op->ar+v) < 32+62)
1033 	{
1034 		op->eg_sh_ar  = eg_rate_shift [op->ar  + v ];
1035 		op->eg_sel_ar = eg_rate_select[op->ar  + v ];
1036 	}
1037 	else
1038 	{
1039 		op->eg_sh_ar  = 0;
1040 		op->eg_sel_ar = 17*RATE_STEPS;
1041 	}
1042 	op->eg_sh_d1r = eg_rate_shift [op->d1r + v];
1043 	op->eg_sel_d1r= eg_rate_select[op->d1r + v];
1044 	op->eg_sh_d2r = eg_rate_shift [op->d2r + v];
1045 	op->eg_sel_d2r= eg_rate_select[op->d2r + v];
1046 	op->eg_sh_rr  = eg_rate_shift [op->rr  + v];
1047 	op->eg_sel_rr = eg_rate_select[op->rr  + v];
1048 }
1049 
1050 
1051 /* write a register on YM2151 chip number 'n' */
YM2151WriteReg(int n,int r,int v)1052 void YM2151WriteReg(int n, int r, int v)
1053 {
1054 	YM2151 *chip = &YMPSG[n];
1055 	YM2151Operator *op = &chip->oper[ (r&0x07)*4+((r&0x18)>>3) ];
1056 
1057 	/* adjust bus to 8 bits */
1058 	r &= 0xff;
1059 	v &= 0xff;
1060 
1061 #if 0
1062 	/* There is no info on what YM2151 really does when busy flag is set */
1063 	if ( chip->status & 0x80 ) return;
1064 	timer_set ( 64.0 / (double)chip->clock, n, timer_callback_chip_busy);
1065 	chip->status |= 0x80;	/* set busy flag for 64 chip clock cycles */
1066 #endif
1067 
1068 #ifdef LOG_CYM_FILE
1069 	if ((cymfile) && (r!=0) )
1070 	{
1071 		fputc( (unsigned char)r, cymfile );
1072 		fputc( (unsigned char)v, cymfile );
1073 	}
1074 #endif
1075 
1076 
1077 	switch(r & 0xe0){
1078 	case 0x00:
1079 		switch(r){
1080 		case 0x01:	/* LFO reset(bit 1), Test Register (other bits) */
1081 			chip->test = v;
1082 			if (v&2) chip->lfo_phase = 0;
1083 			break;
1084 
1085 		case 0x08:
1086 			PSG = &YMPSG[n]; /* PSG is used in KEY_ON macro */
1087 			envelope_KONKOFF(&chip->oper[ (v&7)*4 ], v );
1088 			break;
1089 
1090 		case 0x0f:	/* noise mode enable, noise period */
1091 			chip->noise = v;
1092 			chip->noise_f = chip->noise_tab[ v & 0x1f ];
1093 			break;
1094 
1095 		case 0x10:	/* timer A hi */
1096 			chip->timer_A_index = (chip->timer_A_index & 0x003) | (v<<2);
1097 			break;
1098 
1099 		case 0x11:	/* timer A low */
1100 			chip->timer_A_index = (chip->timer_A_index & 0x3fc) | (v & 3);
1101 			break;
1102 
1103 		case 0x12:	/* timer B */
1104 			chip->timer_B_index = v;
1105 			break;
1106 
1107 		case 0x14:	/* CSM, irq flag reset, irq enable, timer start/stop */
1108 
1109 			chip->irq_enable = v;	/* bit 3-timer B, bit 2-timer A, bit 7 - CSM */
1110 
1111 			if (v&0x20)	/* reset timer B irq flag */
1112 			{
1113 				int oldstate = chip->status & 3;
1114 				chip->status &= 0xfd;
1115 				if ((oldstate==2) && (chip->irqhandler)) (*chip->irqhandler)(0);
1116 			}
1117 
1118 			if (v&0x10)	/* reset timer A irq flag */
1119 			{
1120 				int oldstate = chip->status & 3;
1121 				chip->status &= 0xfe;
1122 				if ((oldstate==1) && (chip->irqhandler)) (*chip->irqhandler)(0);
1123 
1124 			}
1125 
1126 			if (v&0x02){	/* load and start timer B */
1127 				//#ifdef USE_MAME_TIMERS
1128 				/* ASG 980324: added a real timer */
1129 				/* start timer _only_ if it wasn't already started (it will reload time value next round) */
1130 				if (chip->UseBurnTimer) {
1131 					if (!chip->timer_B) //(!timer_enable(chip->timer_B, 1))
1132 					{
1133 						//timer_adjust(chip->timer_B, chip->timer_B_time[ chip->timer_B_index ], n, 0);
1134 						chip->timer_callback(1, chip->timer_B_time[ chip->timer_B_index ]);
1135 						chip->timer_B = 1;
1136 						chip->timer_B_index_old = chip->timer_B_index;
1137 					}
1138 				} else {
1139 				//#else
1140 					if (!chip->tim_B)
1141 					{
1142 						chip->tim_B = 1;
1143 						chip->tim_B_val = chip->tim_B_tab[ chip->timer_B_index ];
1144 					}
1145 				}
1146 				//#endif
1147 			}else{		/* stop timer B */
1148 				//#ifdef USE_MAME_TIMERS
1149 				/* ASG 980324: added a real timer */
1150 				if (chip->UseBurnTimer) {
1151 					chip->timer_B = 0;
1152 					chip->timer_callback(1, 0.0);
1153 					//timer_enable(chip->timer_B, 0);
1154 				} else {
1155 				//#else
1156 					chip->tim_B = 0;
1157 				}
1158 				//#endif
1159 			}
1160 
1161 			if (v&0x01){	/* load and start timer A */
1162 				//#ifdef USE_MAME_TIMERS
1163 				/* ASG 980324: added a real timer */
1164 				/* start timer _only_ if it wasn't already started (it will reload time value next round) */
1165 				if (chip->UseBurnTimer) {
1166 					if (!chip->timer_A) //(!timer_enable(chip->timer_A, 1))
1167 					{
1168 						//timer_adjust(chip->timer_A, chip->timer_A_time[ chip->timer_A_index ], n, 0);
1169 						chip->timer_callback(0, chip->timer_A_time[ chip->timer_A_index ]);
1170 						chip->timer_A = 1;
1171 						chip->timer_A_index_old = chip->timer_A_index;
1172 					}
1173 				} else {
1174 				//#else
1175 					if (!chip->tim_A)
1176 					{
1177 						chip->tim_A = 1;
1178 						chip->tim_A_val = chip->tim_A_tab[ chip->timer_A_index ];
1179 					}
1180 				}
1181 				//#endif
1182 			}else{		/* stop timer A */
1183 				//#ifdef USE_MAME_TIMERS
1184 				/* ASG 980324: added a real timer */
1185 				if (chip->UseBurnTimer) {
1186 					chip->timer_A = 0;
1187 					chip->timer_callback(0, 0.0);
1188 					//timer_enable(chip->timer_A, 0);
1189 				} else {
1190 				//#else
1191 					chip->tim_A = 0;
1192 				}
1193 				//#endif
1194 			}
1195 			break;
1196 
1197 		case 0x18:	/* LFO frequency */
1198 			{
1199 				chip->lfo_overflow    = ( 1 << ((15-(v>>4))+3) ) * (1<<LFO_SH);
1200 				chip->lfo_counter_add = 0x10 + (v & 0x0f);
1201 			}
1202 			break;
1203 
1204 		case 0x19:	/* PMD (bit 7==1) or AMD (bit 7==0) */
1205 			if (v&0x80)
1206 				chip->pmd = v & 0x7f;
1207 			else
1208 				chip->amd = v & 0x7f;
1209 			break;
1210 
1211 		case 0x1b:	/* CT2, CT1, LFO waveform */
1212 			chip->ct = v >> 6;
1213 			chip->lfo_wsel = v & 3;
1214 			if (chip->porthandler) (*chip->porthandler)(0 , chip->ct );
1215 			break;
1216 
1217 		default:
1218 			logerror("YM2151 Write %02x to undocumented register #%02x\n",v,r);
1219 			break;
1220 		}
1221 		break;
1222 
1223 	case 0x20:
1224 //		bprintf(0, _T("%X: %X %X.\n"), n, r, v);
1225 		op = &chip->oper[ (r&7) * 4 ];
1226 		switch(r & 0x18){
1227 		case 0x00:	/* RL enable, Feedback, Connection */
1228 			op->fb_shift = ((v>>3)&7) ? ((v>>3)&7)+6:0;
1229 			chip->pan[ (r&7)*2    ] = (v & 0x40) ? ~0 : 0;
1230 			chip->pan[ (r&7)*2 +1 ] = (v & 0x80) ? ~0 : 0;
1231 			chip->connect[r&7] = v&7;
1232 			set_connect(op, r&7, v&7);
1233 			break;
1234 
1235 		case 0x08:	/* Key Code */
1236 			v &= 0x7f;
1237 			if (v != op->kc)
1238 			{
1239 				UINT32 kc, kc_channel;
1240 
1241 				kc_channel = (v - (v>>2))*64;
1242 				kc_channel += 768;
1243 				kc_channel |= (op->kc_i & 63);
1244 
1245 				(op+0)->kc = v;
1246 				(op+0)->kc_i = kc_channel;
1247 				(op+1)->kc = v;
1248 				(op+1)->kc_i = kc_channel;
1249 				(op+2)->kc = v;
1250 				(op+2)->kc_i = kc_channel;
1251 				(op+3)->kc = v;
1252 				(op+3)->kc_i = kc_channel;
1253 
1254 				kc = v>>2;
1255 
1256 				(op+0)->dt1 = chip->dt1_freq[ (op+0)->dt1_i + kc ];
1257 				(op+0)->freq = ( (chip->freq[ kc_channel + (op+0)->dt2 ] + (op+0)->dt1) * (op+0)->mul ) >> 1;
1258 
1259 				(op+1)->dt1 = chip->dt1_freq[ (op+1)->dt1_i + kc ];
1260 				(op+1)->freq = ( (chip->freq[ kc_channel + (op+1)->dt2 ] + (op+1)->dt1) * (op+1)->mul ) >> 1;
1261 
1262 				(op+2)->dt1 = chip->dt1_freq[ (op+2)->dt1_i + kc ];
1263 				(op+2)->freq = ( (chip->freq[ kc_channel + (op+2)->dt2 ] + (op+2)->dt1) * (op+2)->mul ) >> 1;
1264 
1265 				(op+3)->dt1 = chip->dt1_freq[ (op+3)->dt1_i + kc ];
1266 				(op+3)->freq = ( (chip->freq[ kc_channel + (op+3)->dt2 ] + (op+3)->dt1) * (op+3)->mul ) >> 1;
1267 
1268 				refresh_EG( op );
1269 			}
1270 			break;
1271 
1272 		case 0x10:	/* Key Fraction */
1273 			v >>= 2;
1274 			if (v !=  (op->kc_i & 63))
1275 			{
1276 				UINT32 kc_channel;
1277 
1278 				kc_channel = v;
1279 				kc_channel |= (op->kc_i & ~63);
1280 
1281 				(op+0)->kc_i = kc_channel;
1282 				(op+1)->kc_i = kc_channel;
1283 				(op+2)->kc_i = kc_channel;
1284 				(op+3)->kc_i = kc_channel;
1285 
1286 				(op+0)->freq = ( (chip->freq[ kc_channel + (op+0)->dt2 ] + (op+0)->dt1) * (op+0)->mul ) >> 1;
1287 				(op+1)->freq = ( (chip->freq[ kc_channel + (op+1)->dt2 ] + (op+1)->dt1) * (op+1)->mul ) >> 1;
1288 				(op+2)->freq = ( (chip->freq[ kc_channel + (op+2)->dt2 ] + (op+2)->dt1) * (op+2)->mul ) >> 1;
1289 				(op+3)->freq = ( (chip->freq[ kc_channel + (op+3)->dt2 ] + (op+3)->dt1) * (op+3)->mul ) >> 1;
1290 			}
1291 			break;
1292 
1293 		case 0x18:	/* PMS, AMS */
1294 			op->pms = (v>>4) & 7;
1295 			op->ams = (v & 3);
1296 			break;
1297 		}
1298 		break;
1299 
1300 	case 0x40:		/* DT1, MUL */
1301 		{
1302 			UINT32 olddt1_i = op->dt1_i;
1303 			UINT32 oldmul = op->mul;
1304 
1305 			op->dt1_i = (v&0x70)<<1;
1306 			op->mul   = (v&0x0f) ? (v&0x0f)<<1: 1;
1307 
1308 			if (olddt1_i != op->dt1_i)
1309 				op->dt1 = chip->dt1_freq[ op->dt1_i + (op->kc>>2) ];
1310 
1311 			if ( (olddt1_i != op->dt1_i) || (oldmul != op->mul) )
1312 				op->freq = ( (chip->freq[ op->kc_i + op->dt2 ] + op->dt1) * op->mul ) >> 1;
1313 		}
1314 		break;
1315 
1316 	case 0x60:		/* TL */
1317 		op->tl = (v&0x7f)<<(ENV_BITS-7); /* 7bit TL */
1318 		break;
1319 
1320 	case 0x80:		/* KS, AR */
1321 		{
1322 			UINT32 oldks = op->ks;
1323 			UINT32 oldar = op->ar;
1324 
1325 			op->ks = 5-(v>>6);
1326 			op->ar = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1327 
1328 			if ( (op->ar != oldar) || (op->ks != oldks) )
1329 			{
1330 				if ((op->ar + (op->kc>>op->ks)) < 32+62)
1331 				{
1332 					op->eg_sh_ar  = eg_rate_shift [op->ar  + (op->kc>>op->ks) ];
1333 					op->eg_sel_ar = eg_rate_select[op->ar  + (op->kc>>op->ks) ];
1334 				}
1335 				else
1336 				{
1337 					op->eg_sh_ar  = 0;
1338 					op->eg_sel_ar = 17*RATE_STEPS;
1339 				}
1340 			}
1341 
1342 			if (op->ks != oldks)
1343 			{
1344 				op->eg_sh_d1r = eg_rate_shift [op->d1r + (op->kc>>op->ks) ];
1345 				op->eg_sel_d1r= eg_rate_select[op->d1r + (op->kc>>op->ks) ];
1346 				op->eg_sh_d2r = eg_rate_shift [op->d2r + (op->kc>>op->ks) ];
1347 				op->eg_sel_d2r= eg_rate_select[op->d2r + (op->kc>>op->ks) ];
1348 				op->eg_sh_rr  = eg_rate_shift [op->rr  + (op->kc>>op->ks) ];
1349 				op->eg_sel_rr = eg_rate_select[op->rr  + (op->kc>>op->ks) ];
1350 			}
1351 		}
1352 		break;
1353 
1354 	case 0xa0:		/* LFO AM enable, D1R */
1355 		op->AMmask = (v&0x80) ? ~0 : 0;
1356 		op->d1r    = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1357 		op->eg_sh_d1r = eg_rate_shift [op->d1r + (op->kc>>op->ks) ];
1358 		op->eg_sel_d1r= eg_rate_select[op->d1r + (op->kc>>op->ks) ];
1359 		break;
1360 
1361 	case 0xc0:		/* DT2, D2R */
1362 		{
1363 			UINT32 olddt2 = op->dt2;
1364 			op->dt2 = dt2_tab[ v>>6 ];
1365 			if (op->dt2 != olddt2)
1366 				op->freq = ( (chip->freq[ op->kc_i + op->dt2 ] + op->dt1) * op->mul ) >> 1;
1367 		}
1368 		op->d2r = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1369 		op->eg_sh_d2r = eg_rate_shift [op->d2r + (op->kc>>op->ks) ];
1370 		op->eg_sel_d2r= eg_rate_select[op->d2r + (op->kc>>op->ks) ];
1371 		break;
1372 
1373 	case 0xe0:		/* D1L, RR */
1374 		op->d1l = d1l_tab[ v>>4 ];
1375 		op->rr  = 34 + ((v&0x0f)<<2);
1376 		op->eg_sh_rr  = eg_rate_shift [op->rr  + (op->kc>>op->ks) ];
1377 		op->eg_sel_rr = eg_rate_select[op->rr  + (op->kc>>op->ks) ];
1378 		break;
1379 	}
1380 }
1381 
1382 
1383 #ifdef LOG_CYM_FILE
cymfile_callback(int n)1384 static void cymfile_callback (int n)
1385 {
1386 	if (cymfile)
1387 		fputc( (unsigned char)0, cymfile );
1388 }
1389 #endif
1390 
1391 
YM2151ReadStatus(int n)1392 int YM2151ReadStatus( int n )
1393 {
1394 	return YMPSG[n].status;
1395 }
1396 
1397 
1398 
1399 //#ifdef USE_MAME_TIMERS
1400 #if 0 // disabled for now due to crashing in debug+map+symbols build
1401 /*
1402 *	state save support for MAME
1403 */
1404 static void ym2151_postload_refresh(void)
1405 {
1406 	int i,j;
1407 
1408 	for (i=0; i<YMNumChips; i++)
1409 	{
1410 		for (j=0; j<8; j++)
1411 		{
1412 			set_connect(&YMPSG[i].oper[j*4], j, YMPSG[i].connect[j]);
1413 		}
1414 	}
1415 }
1416 
1417 static void ym2151_state_save_register( int numchips )
1418 {
1419 	int i,j;
1420 	char buf1[20];
1421 
1422 	for (i=0; i<numchips; i++)
1423 	{
1424 		/* save all 32 operators of chip #i */
1425 		for (j=0; j<32; j++)
1426 		{
1427 			YM2151Operator *op;
1428 
1429 			sprintf(buf1,"YM2151.op%02i",j);
1430 			op = &YMPSG[i].oper[(j&7)*4+(j>>3)];
1431 
1432 			state_save_register_UINT32 (buf1, i, "phase", &op->phase, 1);
1433 			state_save_register_UINT32 (buf1, i, "freq" , &op->freq,  1);
1434 			state_save_register_INT32  (buf1, i, "dt1"  , &op->dt1,   1);
1435 			state_save_register_UINT32 (buf1, i, "mul"  , &op->mul,   1);
1436 			state_save_register_UINT32 (buf1, i, "dt1_i", &op->dt1_i, 1);
1437 			state_save_register_UINT32 (buf1, i, "dt2"  , &op->dt2,   1);
1438 			/* operators connection is saved in chip data block */
1439 			state_save_register_INT32  (buf1, i, "mem_v" ,&op->mem_value,1);
1440 
1441 			state_save_register_UINT32 (buf1, i, "fb_sh", &op->fb_shift,   1);
1442 			state_save_register_INT32  (buf1, i, "fb_c" , &op->fb_out_curr,1);
1443 			state_save_register_INT32  (buf1, i, "fb_p" , &op->fb_out_prev,1);
1444 			state_save_register_UINT32 (buf1, i, "kc"   , &op->kc,    1);
1445 			state_save_register_UINT32 (buf1, i, "kc_i" , &op->kc_i,  1);
1446 			state_save_register_UINT32 (buf1, i, "pms"  , &op->pms,   1);
1447 			state_save_register_UINT32 (buf1, i, "ams"  , &op->ams,   1);
1448 			state_save_register_UINT32 (buf1, i, "AMmask",&op->AMmask,1);
1449 
1450 			state_save_register_UINT32 (buf1, i, "state" ,&op->state,     1);
1451 			state_save_register_UINT8  (buf1, i, "e_shAR",&op->eg_sh_ar,  1);
1452 			state_save_register_UINT8  (buf1, i, "e_slAR",&op->eg_sel_ar, 1);
1453 			state_save_register_UINT32 (buf1, i, "tl"    ,&op->tl,        1);
1454 			state_save_register_INT32  (buf1, i, "volume",&op->volume,    1);
1455 			state_save_register_UINT8  (buf1, i, "e_shD1",&op->eg_sh_d1r, 1);
1456 			state_save_register_UINT8  (buf1, i, "e_slD1",&op->eg_sel_d1r,1);
1457 			state_save_register_UINT32 (buf1, i, "d1l"   ,&op->d1l,       1);
1458 			state_save_register_UINT8  (buf1, i, "e_shD2",&op->eg_sh_d2r, 1);
1459 			state_save_register_UINT8  (buf1, i, "e_slD2",&op->eg_sel_d2r,1);
1460 			state_save_register_UINT8  (buf1, i, "e_shRR",&op->eg_sh_rr,  1);
1461 			state_save_register_UINT8  (buf1, i, "e_slRR",&op->eg_sel_rr, 1);
1462 
1463 			state_save_register_UINT32 (buf1, i, "key"   ,&op->key, 1);
1464 			state_save_register_UINT32 (buf1, i, "ks"    ,&op->ks,  1);
1465 			state_save_register_UINT32 (buf1, i, "ar"    ,&op->ar,  1);
1466 			state_save_register_UINT32 (buf1, i, "d1r"   ,&op->d1r, 1);
1467 			state_save_register_UINT32 (buf1, i, "d2r"   ,&op->d2r, 1);
1468 			state_save_register_UINT32 (buf1, i, "rr"    ,&op->rr,  1);
1469 
1470 			state_save_register_UINT32 (buf1, i, "rsrvd0",&op->reserved0, 1);
1471 			state_save_register_UINT32 (buf1, i, "rsrvd1",&op->reserved1, 1);
1472 		}
1473 
1474 		sprintf(buf1,"YM2151.registers");
1475 
1476 		state_save_register_UINT32 (buf1, i, "pan"     , &YMPSG[i].pan[0], 16);
1477 
1478 		state_save_register_UINT32 (buf1, i, "eg_cnt"  , &YMPSG[i].eg_cnt,           1);
1479 		state_save_register_UINT32 (buf1, i, "eg_tmr"  , &YMPSG[i].eg_timer,         1);
1480 		state_save_register_UINT32 (buf1, i, "eg_tmra" , &YMPSG[i].eg_timer_add,     1);
1481 		state_save_register_UINT32 (buf1, i, "eg_ovr"  , &YMPSG[i].eg_timer_overflow,1);
1482 
1483 		state_save_register_UINT32 (buf1, i, "lfo_phas", &YMPSG[i].lfo_phase,      1);
1484 		state_save_register_UINT32 (buf1, i, "lfo_tmr" , &YMPSG[i].lfo_timer,      1);
1485 		state_save_register_UINT32 (buf1, i, "lfo_tmra", &YMPSG[i].lfo_timer_add,  1);
1486 		state_save_register_UINT32 (buf1, i, "lfo_ovr" , &YMPSG[i].lfo_overflow,   1);
1487 		state_save_register_UINT32 (buf1, i, "lfo_ctr" , &YMPSG[i].lfo_counter,    1);
1488 		state_save_register_UINT32 (buf1, i, "lfo_ctra", &YMPSG[i].lfo_counter_add,1);
1489 		state_save_register_UINT8  (buf1, i, "lfo_wsel", &YMPSG[i].lfo_wsel, 1);
1490 		state_save_register_UINT8  (buf1, i, "amd"     , &YMPSG[i].amd, 1);
1491 		state_save_register_INT8   (buf1, i, "pmd"     , &YMPSG[i].pmd, 1);
1492 		state_save_register_UINT32 (buf1, i, "lfa"     , &YMPSG[i].lfa, 1);
1493 		state_save_register_INT32  (buf1, i, "lfp"     , &YMPSG[i].lfp, 1);
1494 
1495 		state_save_register_UINT8  (buf1, i, "test"    , &YMPSG[i].test,1);
1496 		state_save_register_UINT8  (buf1, i, "ct"      , &YMPSG[i].ct,  1);
1497 
1498 		state_save_register_UINT32 (buf1, i, "noise"   , &YMPSG[i].noise,     1);
1499 		state_save_register_UINT32 (buf1, i, "noiseRNG", &YMPSG[i].noise_rng, 1);
1500 		state_save_register_UINT32 (buf1, i, "noise_p" , &YMPSG[i].noise_p,   1);
1501 		state_save_register_UINT32 (buf1, i, "noise_f" , &YMPSG[i].noise_f,   1);
1502 
1503 		state_save_register_UINT32 (buf1, i, "csm_req" , &YMPSG[i].csm_req,   1);
1504 		state_save_register_UINT32 (buf1, i, "irq_ena" , &YMPSG[i].irq_enable,1);
1505 		state_save_register_UINT32 (buf1, i, "status"  , &YMPSG[i].status,    1);
1506 
1507 		state_save_register_UINT32 (buf1, i, "TimAind" , &YMPSG[i].timer_A_index, 1);
1508 		state_save_register_UINT32 (buf1, i, "TimBind" , &YMPSG[i].timer_B_index, 1);
1509 		state_save_register_UINT32 (buf1, i, "TimAold" , &YMPSG[i].timer_A_index_old, 1);
1510 		state_save_register_UINT32 (buf1, i, "TimBold" , &YMPSG[i].timer_B_index_old, 1);
1511 
1512 		state_save_register_UINT8  (buf1, i, "connect" , &YMPSG[i].connect[0], 8);
1513 	}
1514 
1515 	state_save_register_func_postload(ym2151_postload_refresh);
1516 }
1517 #else
ym2151_state_save_register(int numchips)1518 static void ym2151_state_save_register( int numchips )
1519 {
1520 }
1521 #endif
1522 
ym2151_postload_refresh(void)1523 static void ym2151_postload_refresh(void)
1524 {
1525 	int i,j;
1526 
1527 	for (i=0; i<YMNumChips; i++)
1528 	{
1529 		for (j=0; j<8; j++)
1530 		{
1531 			set_connect(&YMPSG[i].oper[j*4], j, YMPSG[i].connect[j]);
1532 		}
1533 	}
1534 }
1535 
BurnYM2151Scan_int(INT32 nAction)1536 void BurnYM2151Scan_int(INT32 nAction)
1537 {
1538 	int i,j;
1539 
1540 	if ((nAction & ACB_DRIVER_DATA) == 0) {
1541 		return;
1542 	}
1543 
1544 	for (i=0; i<YMNumChips; i++)
1545 	{
1546 		/* save all 32 operators of chip #i */
1547 		for (j=0; j<32; j++)
1548 		{
1549 			YM2151Operator *op;
1550 
1551 			//sprintf(buf1,"YM2151.op%02i",j);
1552 			op = &YMPSG[i].oper[(j&7)*4+(j>>3)];
1553 
1554 			SCAN_VAR(op->phase);
1555 			SCAN_VAR(op->freq);
1556 			SCAN_VAR(op->dt1);
1557 			SCAN_VAR(op->mul);
1558 			SCAN_VAR(op->dt1_i);
1559 			SCAN_VAR(op->dt2);
1560 			SCAN_VAR(op->mem_value);
1561 
1562 			SCAN_VAR(op->fb_shift);
1563 			SCAN_VAR(op->fb_out_curr);
1564 			SCAN_VAR(op->fb_out_prev);
1565 			SCAN_VAR(op->kc);
1566 			SCAN_VAR(op->kc_i);
1567 			SCAN_VAR(op->pms);
1568 			SCAN_VAR(op->ams);
1569 			SCAN_VAR(op->AMmask);
1570 
1571 			SCAN_VAR(op->state);
1572 			SCAN_VAR(op->eg_sh_ar);
1573 			SCAN_VAR(op->eg_sel_ar);
1574 			SCAN_VAR(op->tl);
1575 			SCAN_VAR(op->volume);
1576 			SCAN_VAR(op->eg_sh_d1r);
1577 			SCAN_VAR(op->eg_sel_d1r);
1578 			SCAN_VAR(op->d1l);
1579 			SCAN_VAR(op->eg_sh_d2r);
1580 			SCAN_VAR(op->eg_sel_d2r);
1581 			SCAN_VAR(op->eg_sh_rr);
1582 			SCAN_VAR(op->eg_sel_rr);
1583 
1584 			SCAN_VAR(op->key);
1585 			SCAN_VAR(op->ks);
1586 			SCAN_VAR(op->ar);
1587 			SCAN_VAR(op->d1r);
1588 			SCAN_VAR(op->d2r);
1589 			SCAN_VAR(op->rr);
1590 
1591 			SCAN_VAR(op->reserved0);
1592 			SCAN_VAR(op->reserved1);
1593 		}
1594 
1595 		//sprintf(buf1,"YM2151.registers");
1596 		SCAN_VAR(YMPSG[i].pan);
1597 
1598 		SCAN_VAR(YMPSG[i].eg_cnt);
1599 		//SCAN_VAR(YMPSG[i].eg_timer);
1600 		YMPSG[i].eg_timer = 0;
1601 		//SCAN_VAR(YMPSG[i].eg_timer_add);
1602 		SCAN_VAR(YMPSG[i].eg_timer_overflow);
1603 
1604 		//SCAN_VAR(YMPSG[i].lfo_phase);
1605 		//SCAN_VAR(YMPSG[i].lfo_timer);
1606 		YMPSG[i].lfo_timer = 0;
1607 		YMPSG[i].lfo_phase = 0;
1608 		//SCAN_VAR(YMPSG[i].lfo_timer_add);
1609 		SCAN_VAR(YMPSG[i].lfo_overflow);
1610 		SCAN_VAR(YMPSG[i].lfo_counter);
1611 		SCAN_VAR(YMPSG[i].lfo_counter_add);
1612 		SCAN_VAR(YMPSG[i].lfo_wsel);
1613 		SCAN_VAR(YMPSG[i].amd);
1614 		SCAN_VAR(YMPSG[i].pmd);
1615 		SCAN_VAR(YMPSG[i].lfa);
1616 		SCAN_VAR(YMPSG[i].lfp);
1617 
1618 		SCAN_VAR(YMPSG[i].test);
1619 		SCAN_VAR(YMPSG[i].ct);
1620 
1621 		SCAN_VAR(YMPSG[i].noise);
1622 		SCAN_VAR(YMPSG[i].noise_rng);
1623 		SCAN_VAR(YMPSG[i].noise_p);
1624 		SCAN_VAR(YMPSG[i].noise_f);
1625 
1626 		SCAN_VAR(YMPSG[i].csm_req);
1627 		SCAN_VAR(YMPSG[i].irq_enable);
1628 		SCAN_VAR(YMPSG[i].status);
1629 
1630 		SCAN_VAR(YMPSG[i].timer_A); // burn_timer FM-timer_A enable/disable
1631 		SCAN_VAR(YMPSG[i].timer_B); // burn_timer FM-timer_B enable/disable
1632 		SCAN_VAR(YMPSG[i].timer_A_index);
1633 		SCAN_VAR(YMPSG[i].timer_B_index);
1634 		SCAN_VAR(YMPSG[i].timer_A_index_old);
1635 		SCAN_VAR(YMPSG[i].timer_B_index_old);
1636 
1637 		SCAN_VAR(YMPSG[i].connect);
1638 		SCAN_VAR(YMPSG[i].tim_A);
1639 		SCAN_VAR(YMPSG[i].tim_B);
1640 		/*SCAN_VAR(YMPSG[i].tim_A_val);
1641 		SCAN_VAR(YMPSG[i].tim_B_val);
1642 		SCAN_VAR(YMPSG[i].tim_A_tab);
1643 		SCAN_VAR(YMPSG[i].tim_B_tab);
1644 		SCAN_VAR(YMPSG[i].freq);
1645 		SCAN_VAR(YMPSG[i].dt1_freq);
1646 		SCAN_VAR(YMPSG[i].noise_tab);*/
1647 		if (nAction & ACB_WRITE) {
1648 			if (YMPSG[i].tim_B) {
1649 				YMPSG[i].tim_B_val = YMPSG[i].tim_B_tab[ YMPSG[i].timer_B_index ];
1650 			}
1651 			if (YMPSG[i].tim_A) {
1652 				YMPSG[i].tim_A_val = YMPSG[i].tim_A_tab[ YMPSG[i].timer_A_index ];
1653 			}
1654 			//init_chip_tables( &YMPSG[i] );
1655 
1656 		}
1657 	}
1658 #if 0
1659 	SCAN_VAR(chanout);
1660 	SCAN_VAR(m2);
1661 	SCAN_VAR(c1);
1662 	SCAN_VAR(c2); /* Phase Modulation input for operators 2,3,4 */
1663 	SCAN_VAR(mem);		/* one sample delay memory */
1664 #endif
1665 	if (nAction & ACB_WRITE) {
1666 		// state_save_register_func_postload(ym2151_postload_refresh);
1667 		ym2151_postload_refresh();
1668 	}
1669 }
1670 
YM2151SetTimerInterleave(double d)1671 void YM2151SetTimerInterleave(double d)
1672 {
1673 	YM2151 *chip = &YMPSG[0];
1674 
1675 	chip->timer_sync = d;
1676 
1677 	init_chip_tables(chip);
1678 }
1679 
1680 
1681 /*
1682 *	Initialize YM2151 emulator(s).
1683 *
1684 *	'num' is the number of virtual YM2151's to allocate
1685 *	'clock' is the chip clock in Hz
1686 *	'rate' is sampling rate
1687 */
YM2151Init(int num,int clock,int rate,void (* timer_cb)(INT32,double))1688 int YM2151Init(int num, int clock, int rate, void (*timer_cb)(INT32, double))
1689 {
1690 	int i;
1691 
1692 	if (YMPSG)
1693 		return -1;	/* duplicate init. */
1694 
1695 	YMNumChips = num;
1696 
1697 	YMPSG = (YM2151 *)malloc(sizeof(YM2151) * YMNumChips);
1698 	if (YMPSG == NULL)
1699 		return 1;
1700 
1701 	memset(YMPSG, 0, sizeof(YM2151) * YMNumChips);
1702 
1703 	ym2151_state_save_register( YMNumChips );
1704 
1705 	init_tables();
1706 
1707 	for (i=0 ; i<YMNumChips; i++)
1708 	{
1709 		YMPSG[i].clock = clock;
1710 		/*rate = clock/64;*/
1711 		YMPSG[i].sampfreq = rate ? rate : 44100;	/* avoid division by 0 in init_chip_tables() */
1712 		YMPSG[i].timer_sync = 0;
1713 		YMPSG[i].irqhandler = NULL;					/* interrupt handler  */
1714 		YMPSG[i].porthandler = NULL;				/* port write handler */
1715 		init_chip_tables( &YMPSG[i] );
1716 
1717 		YMPSG[i].lfo_timer_add = (1<<LFO_SH) * (clock/64.0) / YMPSG[i].sampfreq;
1718 
1719 		YMPSG[i].eg_timer_add  = (1<<EG_SH)  * (clock/64.0) / YMPSG[i].sampfreq;
1720 		YMPSG[i].eg_timer_overflow = ( 3 ) * (1<<EG_SH);
1721 		/*logerror("YM2151[init] eg_timer_add=%8x eg_timer_overflow=%8x\n", YMPSG[i].eg_timer_add, YMPSG[i].eg_timer_overflow);*/
1722 
1723 //#ifdef USE_MAME_TIMERS
1724 /* this must be done _before_ a call to YM2151ResetChip() */
1725 		YMPSG[i].timer_A = 0; //timer_alloc(timer_callback_a);
1726 		YMPSG[i].timer_B = 0; //timer_alloc(timer_callback_b);
1727 		if (timer_cb) {
1728 			YMPSG[i].UseBurnTimer = 1;
1729 			YMPSG[i].timer_callback = timer_cb;
1730 		}
1731 //#else
1732 		YMPSG[i].tim_A      = 0;
1733 		YMPSG[i].tim_B      = 0;
1734 //#endif
1735 		YM2151ResetChip(i);
1736 		/*logerror("YM2151[init] clock=%i sampfreq=%i\n", YMPSG[i].clock, YMPSG[i].sampfreq);*/
1737 	}
1738 
1739 #ifdef LOG_CYM_FILE
1740 	cymfile = fopen("2151_.cym","wb");
1741 	if (cymfile)
1742 		timer_pulse ( TIME_IN_HZ(110), 0, cymfile_callback); /*110 Hz pulse timer*/
1743 	else
1744 		logerror("Could not create file 2151_.cym\n");
1745 #endif
1746 
1747 	return 0;
1748 }
1749 
1750 
1751 
YM2151Shutdown()1752 void YM2151Shutdown()
1753 {
1754 	if (!YMPSG)
1755 		return;
1756 
1757 	free (YMPSG);
1758 	YMPSG = NULL;
1759 
1760 #ifdef LOG_CYM_FILE
1761 	fclose (cymfile);
1762 	cymfile = NULL;
1763 #endif
1764 
1765 #ifdef SAVE_SAMPLE
1766 	fclose(sample[8]);
1767 #endif
1768 #ifdef SAVE_SEPARATE_CHANNELS
1769 	fclose(sample[0]);
1770 	fclose(sample[1]);
1771 	fclose(sample[2]);
1772 	fclose(sample[3]);
1773 	fclose(sample[4]);
1774 	fclose(sample[5]);
1775 	fclose(sample[6]);
1776 	fclose(sample[7]);
1777 #endif
1778 }
1779 
1780 
1781 
1782 /*
1783 *	Reset chip number 'n'.
1784 */
YM2151ResetChip(int num)1785 void YM2151ResetChip(int num)
1786 {
1787 	int i;
1788 	YM2151 *chip = &YMPSG[num];
1789 
1790 
1791 	/* initialize hardware registers */
1792 	for (i=0; i<32; i++)
1793 	{
1794 		memset(&chip->oper[i],'\0',sizeof(YM2151Operator));
1795 		chip->oper[i].volume = MAX_ATT_INDEX;
1796 	        chip->oper[i].kc_i = 768; /* min kc_i value */
1797 	}
1798 
1799 	chip->eg_timer = 0;
1800 	chip->eg_cnt   = 0;
1801 
1802 	chip->lfo_timer  = 0;
1803 	chip->lfo_counter= 0;
1804 	chip->lfo_phase  = 0;
1805 	chip->lfo_wsel   = 0;
1806 	chip->pmd = 0;
1807 	chip->amd = 0;
1808 	chip->lfa = 0;
1809 	chip->lfp = 0;
1810 
1811 	chip->test= 0;
1812 
1813 	chip->irq_enable = 0;
1814 //#ifdef USE_MAME_TIMERS
1815 	/* ASG 980324 -- reset the timers before writing to the registers */
1816 	chip->timer_A = 0;
1817 	chip->timer_B = 0;
1818 	if (chip->UseBurnTimer) {
1819 		//chip->timer_callback(0, 0.0); // this is taken care of in burn_ym2151.cpp's reset function.
1820 		//chip->timer_callback(1, 0.0);
1821 		//timer_enable(chip->timer_A, 0);
1822 		//timer_enable(chip->timer_B, 0);
1823 	}
1824 //#else
1825 	chip->tim_A      = 0;
1826 	chip->tim_B      = 0;
1827 	chip->tim_A_val  = 0;
1828 	chip->tim_B_val  = 0;
1829 //#endif
1830 	chip->timer_A_index = 0;
1831 	chip->timer_B_index = 0;
1832 	chip->timer_A_index_old = 0;
1833 	chip->timer_B_index_old = 0;
1834 
1835 	chip->noise     = 0;
1836 	chip->noise_rng = 0;
1837 	chip->noise_p   = 0;
1838 	chip->noise_f   = chip->noise_tab[0];
1839 
1840 	chip->csm_req	= 0;
1841 	chip->status    = 0;
1842 
1843 	YM2151WriteReg(num, 0x1b, 0);	/* only because of CT1, CT2 output pins */
1844 	YM2151WriteReg(num, 0x18, 0);	/* set LFO frequency */
1845 	for (i=0x20; i<0x100; i++)		/* set the operators */
1846 	{
1847 		YM2151WriteReg(num, i, 0);
1848 	}
1849 }
1850 
1851 
1852 
op_calc(YM2151Operator * OP,unsigned int env,signed int pm)1853 INLINE signed int op_calc(YM2151Operator * OP, unsigned int env, signed int pm)
1854 {
1855 	UINT32 p;
1856 
1857 
1858 	p = (env<<3) + sin_tab[ ( ((signed int)((OP->phase & ~FREQ_MASK) + (pm<<15))) >> FREQ_SH ) & SIN_MASK ];
1859 
1860 	if (p >= TL_TAB_LEN)
1861 		return 0;
1862 
1863 	return tl_tab[p];
1864 }
1865 
op_calc1(YM2151Operator * OP,unsigned int env,signed int pm)1866 INLINE signed int op_calc1(YM2151Operator * OP, unsigned int env, signed int pm)
1867 {
1868 	UINT32 p;
1869 	INT32  i;
1870 
1871 
1872 	i = (OP->phase & ~FREQ_MASK) + pm;
1873 
1874 /*logerror("i=%08x (i>>16)&511=%8i phase=%i [pm=%08x] ",i, (i>>16)&511, OP->phase>>FREQ_SH, pm);*/
1875 
1876 	p = (env<<3) + sin_tab[ (i>>FREQ_SH) & SIN_MASK];
1877 
1878 /*logerror("(p&255=%i p>>8=%i) out= %i\n", p&255,p>>8, tl_tab[p&255]>>(p>>8) );*/
1879 
1880 	if (p >= TL_TAB_LEN)
1881 		return 0;
1882 
1883 	return tl_tab[p];
1884 }
1885 
1886 
1887 
1888 #define volume_calc(OP) ((OP)->tl + ((UINT32)(OP)->volume) + (AM & (OP)->AMmask))
1889 
chan_calc(unsigned int chan)1890 INLINE void chan_calc(unsigned int chan)
1891 {
1892 	YM2151Operator *op;
1893 	unsigned int env;
1894 	UINT32 AM = 0;
1895 
1896 	m2 = c1 = c2 = mem = 0;
1897 	op = &PSG->oper[chan*4];	/* M1 */
1898 
1899 	*op->mem_connect = op->mem_value;	/* restore delayed sample (MEM) value to m2 or c2 */
1900 
1901 	if (op->ams)
1902 		AM = PSG->lfa << (op->ams-1);
1903 	env = volume_calc(op);
1904 	{
1905 		INT32 out = op->fb_out_prev + op->fb_out_curr;
1906 		op->fb_out_prev = op->fb_out_curr;
1907 
1908 		if (!op->connect)
1909 			/* algorithm 5 */
1910 			mem = c1 = c2 = op->fb_out_prev;
1911 		else
1912 			/* other algorithms */
1913 			*op->connect = op->fb_out_prev;
1914 
1915 		op->fb_out_curr = 0;
1916 		if (env < ENV_QUIET)
1917 		{
1918 			if (!op->fb_shift)
1919 				out=0;
1920 			op->fb_out_curr = op_calc1(op, env, (out<<op->fb_shift) );
1921 		}
1922 	}
1923 
1924 	env = volume_calc(op+1);	/* M2 */
1925 	if (env < ENV_QUIET)
1926 		*(op+1)->connect += op_calc(op+1, env, m2);
1927 
1928 	env = volume_calc(op+2);	/* C1 */
1929 	if (env < ENV_QUIET)
1930 		*(op+2)->connect += op_calc(op+2, env, c1);
1931 
1932 	env = volume_calc(op+3);	/* C2 */
1933 	if (env < ENV_QUIET)
1934 		chanout[chan]    += op_calc(op+3, env, c2);
1935 
1936 	/* M1 */
1937 	op->mem_value = mem;
1938 }
chan7_calc(void)1939 INLINE void chan7_calc(void)
1940 {
1941 	YM2151Operator *op;
1942 	unsigned int env;
1943 	UINT32 AM = 0;
1944 
1945 	m2 = c1 = c2 = mem = 0;
1946 	op = &PSG->oper[7*4];		/* M1 */
1947 
1948 	*op->mem_connect = op->mem_value;	/* restore delayed sample (MEM) value to m2 or c2 */
1949 
1950 	if (op->ams)
1951 		AM = PSG->lfa << (op->ams-1);
1952 	env = volume_calc(op);
1953 	{
1954 		INT32 out = op->fb_out_prev + op->fb_out_curr;
1955 		op->fb_out_prev = op->fb_out_curr;
1956 
1957 		if (!op->connect)
1958 			/* algorithm 5 */
1959 			mem = c1 = c2 = op->fb_out_prev;
1960 		else
1961 			/* other algorithms */
1962 			*op->connect = op->fb_out_prev;
1963 
1964 		op->fb_out_curr = 0;
1965 		if (env < ENV_QUIET)
1966 		{
1967 			if (!op->fb_shift)
1968 				out=0;
1969 			op->fb_out_curr = op_calc1(op, env, (out<<op->fb_shift) );
1970 		}
1971 	}
1972 
1973 	env = volume_calc(op+1);	/* M2 */
1974 	if (env < ENV_QUIET)
1975 		*(op+1)->connect += op_calc(op+1, env, m2);
1976 
1977 	env = volume_calc(op+2);	/* C1 */
1978 	if (env < ENV_QUIET)
1979 		*(op+2)->connect += op_calc(op+2, env, c1);
1980 
1981 	env = volume_calc(op+3);	/* C2 */
1982 	if (PSG->noise & 0x80)
1983 	{
1984 		UINT32 noiseout;
1985 
1986 		noiseout = 0;
1987 		if (env < 0x3ff)
1988 			noiseout = (env ^ 0x3ff) * 2;	/* range of the YM2151 noise output is -2044 to 2040 */
1989 		chanout[7] += ((PSG->noise_rng&0x10000) ? noiseout: -noiseout); /* bit 16 -> output */
1990 	}
1991 	else
1992 	{
1993 		if (env < ENV_QUIET)
1994 			chanout[7] += op_calc(op+3, env, c2);
1995 	}
1996 	/* M1 */
1997 	op->mem_value = mem;
1998 }
1999 
2000 
2001 
2002 
2003 
2004 
2005 /*
2006 The 'rate' is calculated from following formula (example on decay rate):
2007   rks = notecode after key scaling (a value from 0 to 31)
2008   DR = value written to the chip register
2009   rate = 2*DR + rks; (max rate = 2*31+31 = 93)
2010 Four MSBs of the 'rate' above are the 'main' rate (from 00 to 15)
2011 Two LSBs of the 'rate' above are the value 'x' (the shape type).
2012 (eg. '11 2' means that 'rate' is 11*4+2=46)
2013 
2014 NOTE: A 'sample' in the description below is actually 3 output samples,
2015 thats because the Envelope Generator clock is equal to internal_clock/3.
2016 
2017 Single '-' (minus) character in the diagrams below represents one sample
2018 on the output; this is for rates 11 x (11 0, 11 1, 11 2 and 11 3)
2019 
2020 these 'main' rates:
2021 00 x: single '-' = 2048 samples; (ie. level can change every 2048 samples)
2022 01 x: single '-' = 1024 samples;
2023 02 x: single '-' = 512 samples;
2024 03 x: single '-' = 256 samples;
2025 04 x: single '-' = 128 samples;
2026 05 x: single '-' = 64 samples;
2027 06 x: single '-' = 32 samples;
2028 07 x: single '-' = 16 samples;
2029 08 x: single '-' = 8 samples;
2030 09 x: single '-' = 4 samples;
2031 10 x: single '-' = 2 samples;
2032 11 x: single '-' = 1 sample; (ie. level can change every 1 sample)
2033 
2034 Shapes for rates 11 x look like this:
2035 rate:		step:
2036 11 0        01234567
2037 
2038 level:
2039 0           --
2040 1             --
2041 2               --
2042 3                 --
2043 
2044 rate:		step:
2045 11 1        01234567
2046 
2047 level:
2048 0           --
2049 1             --
2050 2               -
2051 3                -
2052 4                 --
2053 
2054 rate:		step:
2055 11 2        01234567
2056 
2057 level:
2058 0           --
2059 1             -
2060 2              -
2061 3               --
2062 4                 -
2063 5                  -
2064 
2065 rate:		step:
2066 11 3        01234567
2067 
2068 level:
2069 0           --
2070 1             -
2071 2              -
2072 3               -
2073 4                -
2074 5                 -
2075 6                  -
2076 
2077 
2078 For rates 12 x, 13 x, 14 x and 15 x output level changes on every
2079 sample - this means that the waveform looks like this: (but the level
2080 changes by different values on different steps)
2081 12 3        01234567
2082 
2083 0           -
2084 2            -
2085 4             -
2086 8              -
2087 10              -
2088 12               -
2089 14                -
2090 18                 -
2091 20                  -
2092 
2093 Notes about the timing:
2094 ----------------------
2095 
2096 1. Synchronism
2097 
2098 Output level of each two (or more) voices running at the same 'main' rate
2099 (eg 11 0 and 11 1 in the diagram below) will always be changing in sync,
2100 even if there're started with some delay.
2101 
2102 Note that, in the diagram below, the decay phase in channel 0 starts at
2103 sample #2, while in channel 1 it starts at sample #6. Anyway, both channels
2104 will always change their levels at exactly the same (following) samples.
2105 
2106 (S - start point of this channel, A-attack phase, D-decay phase):
2107 
2108 step:
2109 01234567012345670123456
2110 
2111 channel 0:
2112   --
2113  |  --
2114  |    -
2115  |     -
2116  |      --
2117  |        --
2118 |           --
2119 |             -
2120 |              -
2121 |               --
2122 AADDDDDDDDDDDDDDDD
2123 S
2124 
2125 01234567012345670123456
2126 channel 1:
2127       -
2128      | -
2129      |  --
2130      |    --
2131      |      --
2132      |        -
2133     |          -
2134     |           --
2135     |             --
2136     |               --
2137     AADDDDDDDDDDDDDDDD
2138     S
2139 01234567012345670123456
2140 
2141 
2142 2. Shifted (delayed) synchronism
2143 
2144 Output of each two (or more) voices running at different 'main' rate
2145 (9 1, 10 1 and 11 1 in the diagrams below) will always be changing
2146 in 'delayed-sync' (even if there're started with some delay as in "1.")
2147 
2148 Note that the shapes are delayed by exactly one sample per one 'main' rate
2149 increment. (Normally one would expect them to start at the same samples.)
2150 
2151 See diagram below (* - start point of the shape).
2152 
2153 cycle:
2154 0123456701234567012345670123456701234567012345670123456701234567
2155 
2156 rate 09 1
2157 *-------
2158         --------
2159                 ----
2160                     ----
2161                         --------
2162                                 *-------
2163                                 |       --------
2164                                 |               ----
2165                                 |                   ----
2166                                 |                       --------
2167 rate 10 1                       |
2168 --                              |
2169   *---                          |
2170       ----                      |
2171           --                    |
2172             --                  |
2173               ----              |
2174                   *---          |
2175                   |   ----      |
2176                   |       --    | | <- one step (two samples) delay between 9 1 and 10 1
2177                   |         --  | |
2178                   |           ----|
2179                   |               *---
2180                   |                   ----
2181                   |                       --
2182                   |                         --
2183                   |                           ----
2184 rate 11 1         |
2185 -                 |
2186  --               |
2187    *-             |
2188      --           |
2189        -          |
2190         -         |
2191          --       |
2192            *-     |
2193              --   |
2194                -  || <- one step (one sample) delay between 10 1 and 11 1
2195                 - ||
2196                  --|
2197                    *-
2198                      --
2199                        -
2200                         -
2201                          --
2202                            *-
2203                              --
2204                                -
2205                                 -
2206                                  --
2207 */
2208 
advance_eg(void)2209 INLINE void advance_eg(void)
2210 {
2211 	YM2151Operator *op;
2212 	unsigned int i;
2213 
2214 
2215 
2216 	PSG->eg_timer += PSG->eg_timer_add;
2217 
2218 	while (PSG->eg_timer >= PSG->eg_timer_overflow)
2219 	{
2220 		PSG->eg_timer -= PSG->eg_timer_overflow;
2221 
2222 		PSG->eg_cnt++;
2223 
2224 		/* envelope generator */
2225 		op = &PSG->oper[0];	/* CH 0 M1 */
2226 		i = 32;
2227 		do
2228 		{
2229 			switch(op->state)
2230 			{
2231 			case EG_ATT:	/* attack phase */
2232 				if ( !(PSG->eg_cnt & ((1<<op->eg_sh_ar)-1) ) )
2233 				{
2234 					op->volume += (~op->volume *
2235                                    (eg_inc[op->eg_sel_ar + ((PSG->eg_cnt>>op->eg_sh_ar)&7)])
2236                                   ) >>4;
2237 
2238 					if (op->volume <= MIN_ATT_INDEX)
2239 					{
2240 						op->volume = MIN_ATT_INDEX;
2241 						op->state = EG_DEC;
2242 					}
2243 
2244 				}
2245 			break;
2246 
2247 			case EG_DEC:	/* decay phase */
2248 				if ( !(PSG->eg_cnt & ((1<<op->eg_sh_d1r)-1) ) )
2249 				{
2250 					op->volume += eg_inc[op->eg_sel_d1r + ((PSG->eg_cnt>>op->eg_sh_d1r)&7)];
2251 
2252 					if ( op->volume >= op->d1l )
2253 						op->state = EG_SUS;
2254 
2255 				}
2256 			break;
2257 
2258 			case EG_SUS:	/* sustain phase */
2259 				if ( !(PSG->eg_cnt & ((1<<op->eg_sh_d2r)-1) ) )
2260 				{
2261 					op->volume += eg_inc[op->eg_sel_d2r + ((PSG->eg_cnt>>op->eg_sh_d2r)&7)];
2262 
2263 					if ( op->volume >= MAX_ATT_INDEX )
2264 					{
2265 						op->volume = MAX_ATT_INDEX;
2266 						op->state = EG_OFF;
2267 					}
2268 
2269 				}
2270 			break;
2271 
2272 			case EG_REL:	/* release phase */
2273 				if ( !(PSG->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
2274 				{
2275 					op->volume += eg_inc[op->eg_sel_rr + ((PSG->eg_cnt>>op->eg_sh_rr)&7)];
2276 
2277 					if ( op->volume >= MAX_ATT_INDEX )
2278 					{
2279 						op->volume = MAX_ATT_INDEX;
2280 						op->state = EG_OFF;
2281 					}
2282 
2283 				}
2284 			break;
2285 			}
2286 			op++;
2287 			i--;
2288 		}while (i);
2289 	}
2290 }
2291 
2292 
advance(void)2293 INLINE void advance(void)
2294 {
2295 	YM2151Operator *op;
2296 	unsigned int i;
2297 	int a,p;
2298 
2299 	/* LFO */
2300 	if (PSG->test&2)
2301 		PSG->lfo_phase = 0;
2302 	else
2303 	{
2304 		PSG->lfo_timer += PSG->lfo_timer_add;
2305 		if (PSG->lfo_timer >= PSG->lfo_overflow)
2306 		{
2307 			PSG->lfo_timer   -= PSG->lfo_overflow;
2308 			PSG->lfo_counter += PSG->lfo_counter_add;
2309 			PSG->lfo_phase   += (PSG->lfo_counter>>4);
2310 			PSG->lfo_phase   &= 255;
2311 			PSG->lfo_counter &= 15;
2312 		}
2313 	}
2314 
2315 	i = PSG->lfo_phase;
2316 	/* calculate LFO AM and PM waveform value (all verified on real chip, except for noise algorithm which is impossible to analyse)*/
2317 	switch (PSG->lfo_wsel)
2318 	{
2319 	case 0:
2320 		/* saw */
2321 		/* AM: 255 down to 0 */
2322 		/* PM: 0 to 127, -127 to 0 (at PMD=127: LFP = 0 to 126, -126 to 0) */
2323 		a = 255 - i;
2324 		if (i<128)
2325 			p = i;
2326 		else
2327 			p = i - 255;
2328 		break;
2329 	case 1:
2330 		/* square */
2331 		/* AM: 255, 0 */
2332 		/* PM: 128,-128 (LFP = exactly +PMD, -PMD) */
2333 		if (i<128){
2334 			a = 255;
2335 			p = 128;
2336 		}else{
2337 			a = 0;
2338 			p = -128;
2339 		}
2340 		break;
2341 	case 2:
2342 		/* triangle */
2343 		/* AM: 255 down to 1 step -2; 0 up to 254 step +2 */
2344 		/* PM: 0 to 126 step +2, 127 to 1 step -2, 0 to -126 step -2, -127 to -1 step +2*/
2345 		if (i<128)
2346 			a = 255 - (i*2);
2347 		else
2348 			a = (i*2) - 256;
2349 
2350 		if (i<64)						/* i = 0..63 */
2351 			p = i*2;					/* 0 to 126 step +2 */
2352 		else if (i<128)					/* i = 64..127 */
2353 				p = 255 - i*2;			/* 127 to 1 step -2 */
2354 			else if (i<192)				/* i = 128..191 */
2355 					p = 256 - i*2;		/* 0 to -126 step -2*/
2356 				else					/* i = 192..255 */
2357 					p = i*2 - 511;		/*-127 to -1 step +2*/
2358 		break;
2359 	case 3:
2360 	default:	/*keep the compiler happy*/
2361 		/* random */
2362 		/* the real algorithm is unknown !!!
2363 			We just use a snapshot of data from real chip */
2364 
2365 		/* AM: range 0 to 255    */
2366 		/* PM: range -128 to 127 */
2367 
2368 		a = lfo_noise_waveform[i];
2369 		p = a-128;
2370 		break;
2371 	}
2372 	PSG->lfa = a * PSG->amd / 128;
2373 	PSG->lfp = p * PSG->pmd / 128;
2374 
2375 
2376 	/*	The Noise Generator of the YM2151 is 17-bit shift register.
2377 	*	Input to the bit16 is negated (bit0 XOR bit3) (EXNOR).
2378 	*	Output of the register is negated (bit0 XOR bit3).
2379 	*	Simply use bit16 as the noise output.
2380 	*/
2381 	PSG->noise_p += PSG->noise_f;
2382 	i = (PSG->noise_p>>16);		/* number of events (shifts of the shift register) */
2383 	PSG->noise_p &= 0xffff;
2384 	while (i)
2385 	{
2386 		UINT32 j;
2387 		j = ( (PSG->noise_rng ^ (PSG->noise_rng>>3) ) & 1) ^ 1;
2388 		PSG->noise_rng = (j<<16) | (PSG->noise_rng>>1);
2389 		i--;
2390 	}
2391 
2392 
2393 	/* phase generator */
2394 	op = &PSG->oper[0];	/* CH 0 M1 */
2395 	i = 8;
2396 	do
2397 	{
2398 		if (op->pms)	/* only when phase modulation from LFO is enabled for this channel */
2399 		{
2400 			INT32 mod_ind = PSG->lfp;		/* -128..+127 (8bits signed) */
2401 			if (op->pms < 6)
2402 				mod_ind >>= (6 - op->pms);
2403 			else
2404 				mod_ind <<= (op->pms - 5);
2405 
2406 			if (mod_ind)
2407 			{
2408 				UINT32 kc_channel =	op->kc_i + mod_ind;
2409 				(op+0)->phase += ( (PSG->freq[ kc_channel + (op+0)->dt2 ] + (op+0)->dt1) * (op+0)->mul ) >> 1;
2410 				(op+1)->phase += ( (PSG->freq[ kc_channel + (op+1)->dt2 ] + (op+1)->dt1) * (op+1)->mul ) >> 1;
2411 				(op+2)->phase += ( (PSG->freq[ kc_channel + (op+2)->dt2 ] + (op+2)->dt1) * (op+2)->mul ) >> 1;
2412 				(op+3)->phase += ( (PSG->freq[ kc_channel + (op+3)->dt2 ] + (op+3)->dt1) * (op+3)->mul ) >> 1;
2413 			}
2414 			else		/* phase modulation from LFO is equal to zero */
2415 			{
2416 				(op+0)->phase += (op+0)->freq;
2417 				(op+1)->phase += (op+1)->freq;
2418 				(op+2)->phase += (op+2)->freq;
2419 				(op+3)->phase += (op+3)->freq;
2420 			}
2421 		}
2422 		else			/* phase modulation from LFO is disabled */
2423 		{
2424 			(op+0)->phase += (op+0)->freq;
2425 			(op+1)->phase += (op+1)->freq;
2426 			(op+2)->phase += (op+2)->freq;
2427 			(op+3)->phase += (op+3)->freq;
2428 		}
2429 
2430 		op+=4;
2431 		i--;
2432 	}while (i);
2433 
2434 
2435 	/* CSM is calculated *after* the phase generator calculations (verified on real chip)
2436 	* CSM keyon line seems to be ORed with the KO line inside of the chip.
2437 	* The result is that it only works when KO (register 0x08) is off, ie. 0
2438 	*
2439 	* Interesting effect is that when timer A is set to 1023, the KEY ON happens
2440 	* on every sample, so there is no KEY OFF at all - the result is that
2441 	* the sound played is the same as after normal KEY ON.
2442 	*/
2443 
2444 	if (PSG->csm_req)			/* CSM KEYON/KEYOFF seqeunce request */
2445 	{
2446 		if (PSG->csm_req==2)	/* KEY ON */
2447 		{
2448 			op = &PSG->oper[0];	/* CH 0 M1 */
2449 			i = 32;
2450 			do
2451 			{
2452 				KEY_ON(op, 2);
2453 				op++;
2454 				i--;
2455 			}while (i);
2456 			PSG->csm_req = 1;
2457 		}
2458 		else					/* KEY OFF */
2459 		{
2460 			op = &PSG->oper[0];	/* CH 0 M1 */
2461 			i = 32;
2462 			do
2463 			{
2464 				KEY_OFF(op,~2);
2465 				op++;
2466 				i--;
2467 			}while (i);
2468 			PSG->csm_req = 0;
2469 		}
2470 	}
2471 }
2472 
2473 #if 0
2474 INLINE signed int acc_calc(signed int value)
2475 {
2476 	if (value>=0)
2477 	{
2478 		if (value < 0x0200)
2479 			return (value & ~0);
2480 		if (value < 0x0400)
2481 			return (value & ~1);
2482 		if (value < 0x0800)
2483 			return (value & ~3);
2484 		if (value < 0x1000)
2485 			return (value & ~7);
2486 		if (value < 0x2000)
2487 			return (value & ~15);
2488 		if (value < 0x4000)
2489 			return (value & ~31);
2490 		return (value & ~63);
2491 	}
2492 	/*else value < 0*/
2493 	if (value > -0x0200)
2494 		return (~abs(value) & ~0);
2495 	if (value > -0x0400)
2496 		return (~abs(value) & ~1);
2497 	if (value > -0x0800)
2498 		return (~abs(value) & ~3);
2499 	if (value > -0x1000)
2500 		return (~abs(value) & ~7);
2501 	if (value > -0x2000)
2502 		return (~abs(value) & ~15);
2503 	if (value > -0x4000)
2504 		return (~abs(value) & ~31);
2505 	return (~abs(value) & ~63);
2506 }
2507 #endif
2508 
2509 /* first macro saves left and right channels to mono file */
2510 /* second macro saves left and right channels to stereo file */
2511 #if 0	/*MONO*/
2512 	#ifdef SAVE_SEPARATE_CHANNELS
2513 	  #define SAVE_SINGLE_CHANNEL(j) \
2514 	  {	signed int pom= -(chanout[j] & PSG->pan[j*2]); \
2515 		if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
2516 		fputc((unsigned short)pom&0xff,sample[j]); \
2517 		fputc(((unsigned short)pom>>8)&0xff,sample[j]);  }
2518 	#else
2519 	  #define SAVE_SINGLE_CHANNEL(j)
2520 	#endif
2521 #else	/*STEREO*/
2522 	#ifdef SAVE_SEPARATE_CHANNELS
2523 	  #define SAVE_SINGLE_CHANNEL(j) \
2524 	  {	signed int pom = -(chanout[j] & PSG->pan[j*2]); \
2525 		if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
2526 		fputc((unsigned short)pom&0xff,sample[j]); \
2527 		fputc(((unsigned short)pom>>8)&0xff,sample[j]); \
2528 		pom = -(chanout[j] & PSG->pan[j*2+1]); \
2529 		if (pom > 32767) pom = 32767; else if (pom < -32768) pom = -32768; \
2530 		fputc((unsigned short)pom&0xff,sample[j]); \
2531 		fputc(((unsigned short)pom>>8)&0xff,sample[j]); \
2532 	  }
2533 	#else
2534 	  #define SAVE_SINGLE_CHANNEL(j)
2535 	#endif
2536 #endif
2537 
2538 /* first macro saves left and right channels to mono file */
2539 /* second macro saves left and right channels to stereo file */
2540 #if 1	/*MONO*/
2541 	#ifdef SAVE_SAMPLE
2542 	  #define SAVE_ALL_CHANNELS \
2543 	  {	signed int pom = outl; \
2544 		/*pom = acc_calc(pom);*/ \
2545 		/*fprintf(sample[8]," %i\n",pom);*/ \
2546 		fputc((unsigned short)pom&0xff,sample[8]); \
2547 		fputc(((unsigned short)pom>>8)&0xff,sample[8]); \
2548 	  }
2549 	#else
2550 	  #define SAVE_ALL_CHANNELS
2551 	#endif
2552 #else	/*STEREO*/
2553 	#ifdef SAVE_SAMPLE
2554 	  #define SAVE_ALL_CHANNELS \
2555 	  {	signed int pom = outl; \
2556 		fputc((unsigned short)pom&0xff,sample[8]); \
2557 		fputc(((unsigned short)pom>>8)&0xff,sample[8]); \
2558 		pom = outr; \
2559 		fputc((unsigned short)pom&0xff,sample[8]); \
2560 		fputc(((unsigned short)pom>>8)&0xff,sample[8]); \
2561 	  }
2562 	#else
2563 	  #define SAVE_ALL_CHANNELS
2564 	#endif
2565 #endif
2566 
2567 
2568 /*	Generate samples for one of the YM2151's
2569 *
2570 *	'num' is the number of virtual YM2151
2571 *	'**buffers' is table of pointers to the buffers: left and right
2572 *	'length' is the number of samples that should be generated
2573 */
YM2151UpdateOne(int num,INT16 ** buffers,int length)2574 void YM2151UpdateOne(int num, INT16 **buffers, int length)
2575 {
2576 	int i;
2577 	signed int outl,outr;
2578 	SAMP *bufL, *bufR;
2579 
2580 	bufL = buffers[0];
2581 	bufR = buffers[1];
2582 
2583 	PSG = &YMPSG[num];
2584 
2585 //#ifdef USE_MAME_TIMERS
2586 		/* ASG 980324 - handled by real timers now */
2587 //#else
2588 	if (PSG->UseBurnTimer == 0) {
2589 		if (PSG->tim_B)
2590 		{
2591 			if (PSG->timer_sync != 0)
2592 				PSG->tim_B_val -= ( 1 << TIMER_SH );
2593 			else
2594 				PSG->tim_B_val -= ( length << TIMER_SH );
2595 			if (PSG->tim_B_val<=0)
2596 			{
2597 				PSG->tim_B_val += PSG->tim_B_tab[ PSG->timer_B_index ];
2598 				if ( PSG->irq_enable & 0x08 )
2599 				{
2600 					int oldstate = PSG->status & 3;
2601 					PSG->status |= 2;
2602 					if ((!oldstate) && (PSG->irqhandler)) (*PSG->irqhandler)(1);
2603 				}
2604 			}
2605 		}
2606 	}
2607 //#endif
2608 
2609 	for (i=0; i<length; i++)
2610 	{
2611 		advance_eg();
2612 
2613 		chanout[0] = 0;
2614 		chanout[1] = 0;
2615 		chanout[2] = 0;
2616 		chanout[3] = 0;
2617 		chanout[4] = 0;
2618 		chanout[5] = 0;
2619 		chanout[6] = 0;
2620 		chanout[7] = 0;
2621 
2622 		chan_calc(0);
2623 		SAVE_SINGLE_CHANNEL(0)
2624 		chan_calc(1);
2625 		SAVE_SINGLE_CHANNEL(1)
2626 		chan_calc(2);
2627 		SAVE_SINGLE_CHANNEL(2)
2628 		chan_calc(3);
2629 		SAVE_SINGLE_CHANNEL(3)
2630 		chan_calc(4);
2631 		SAVE_SINGLE_CHANNEL(4)
2632 		chan_calc(5);
2633 		SAVE_SINGLE_CHANNEL(5)
2634 		chan_calc(6);
2635 		SAVE_SINGLE_CHANNEL(6)
2636 		chan7_calc();
2637 		SAVE_SINGLE_CHANNEL(7)
2638 
2639 		outl = chanout[0] & PSG->pan[0];
2640 		outr = chanout[0] & PSG->pan[1];
2641 		outl += (chanout[1] & PSG->pan[2]);
2642 		outr += (chanout[1] & PSG->pan[3]);
2643 		outl += (chanout[2] & PSG->pan[4]);
2644 		outr += (chanout[2] & PSG->pan[5]);
2645 		outl += (chanout[3] & PSG->pan[6]);
2646 		outr += (chanout[3] & PSG->pan[7]);
2647 		outl += (chanout[4] & PSG->pan[8]);
2648 		outr += (chanout[4] & PSG->pan[9]);
2649 		outl += (chanout[5] & PSG->pan[10]);
2650 		outr += (chanout[5] & PSG->pan[11]);
2651 		outl += (chanout[6] & PSG->pan[12]);
2652 		outr += (chanout[6] & PSG->pan[13]);
2653 		outl += (chanout[7] & PSG->pan[14]);
2654 		outr += (chanout[7] & PSG->pan[15]);
2655 
2656 		outl >>= FINAL_SH;
2657 		outr >>= FINAL_SH;
2658 		if (outl > MAXOUT) outl = MAXOUT;
2659 			else if (outl < MINOUT) outl = MINOUT;
2660 		if (outr > MAXOUT) outr = MAXOUT;
2661 			else if (outr < MINOUT) outr = MINOUT;
2662 		((SAMP*)bufL)[i] = (SAMP)outl;
2663 		((SAMP*)bufR)[i] = (SAMP)outr;
2664 
2665 		SAVE_ALL_CHANNELS
2666 
2667 //#ifdef USE_MAME_TIMERS
2668 		/* ASG 980324 - handled by real timers now */
2669 //#else
2670 		if (PSG->UseBurnTimer == 0)
2671 		{
2672 			/* calculate timer A */
2673 			if (PSG->tim_A)
2674 			{
2675 				PSG->tim_A_val -= ( 1 << TIMER_SH );
2676 				if (PSG->tim_A_val <= 0)
2677 				{
2678 					PSG->tim_A_val += PSG->tim_A_tab[ PSG->timer_A_index ];
2679 					if (PSG->irq_enable & 0x04)
2680 					{
2681 						int oldstate = PSG->status & 3;
2682 						PSG->status |= 1;
2683 						if ((!oldstate) && (PSG->irqhandler)) (*PSG->irqhandler)(1);
2684 					}
2685 					if (PSG->irq_enable & 0x80)
2686 						PSG->csm_req = 2;	/* request KEY ON / KEY OFF sequence */
2687 				}
2688 			}
2689 		}
2690 //#endif
2691 		advance();
2692 	}
2693 }
2694 
YM2151SetIrqHandler(int n,void (* handler)(int irq))2695 void YM2151SetIrqHandler(int n, void(*handler)(int irq))
2696 {
2697 	YMPSG[n].irqhandler = handler;
2698 }
2699 
YM2151SetPortWriteHandler(int n,write8_handler handler)2700 void YM2151SetPortWriteHandler(int n, write8_handler handler)
2701 {
2702 	YMPSG[n].porthandler = handler;
2703 }
2704 
2705