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