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