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