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