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