openMSX
YMF278.cc
Go to the documentation of this file.
1 // Based on ymf278b.c written by R. Belmont and O. Galibert
2 
3 // This class doesn't model a full YMF278b chip. Instead it only models the
4 // wave part. The FM part in modeled in YMF262 (it's almost 100% compatible,
5 // the small differences are handled in YMF262). The status register and
6 // interaction with the FM registers (e.g. the NEW2 bit) is currently handled
7 // in the MSXMoonSound class.
8 
9 #include "YMF278.hh"
10 #include "DeviceConfig.hh"
11 #include "MSXMotherBoard.hh"
12 #include "MSXException.hh"
13 #include "StringOp.hh"
14 #include "serialize.hh"
15 #include "likely.hh"
16 #include "outer.hh"
17 #include <algorithm>
18 #include <cmath>
19 #include <cstring>
20 
21 namespace openmsx {
22 
23 static const int EG_SH = 16; // 16.16 fixed point (EG timing)
24 static const unsigned EG_TIMER_OVERFLOW = 1 << EG_SH;
25 
26 // envelope output entries
27 static const int ENV_BITS = 10;
28 static const int ENV_LEN = 1 << ENV_BITS;
29 static const float ENV_STEP = 128.0f / ENV_LEN;
30 static const int MAX_ATT_INDEX = (1 << (ENV_BITS - 1)) - 1; // 511
31 static const int MIN_ATT_INDEX = 0;
32 
33 // Envelope Generator phases
34 static const int EG_ATT = 4;
35 static const int EG_DEC = 3;
36 static const int EG_SUS = 2;
37 static const int EG_REL = 1;
38 static const int EG_OFF = 0;
39 
40 static const int EG_REV = 5; // pseudo reverb
41 static const int EG_DMP = 6; // damp
42 
43 // Pan values, units are -3dB, i.e. 8.
44 static const int pan_left[16] = {
45  0, 8, 16, 24, 32, 40, 48, 256, 256, 0, 0, 0, 0, 0, 0, 0
46 };
47 static const int pan_right[16] = {
48  0, 0, 0, 0, 0, 0, 0, 0, 256, 256, 48, 40, 32, 24, 16, 8
49 };
50 
51 // Mixing levels, units are -3dB, and add some marging to avoid clipping
52 static const int mix_level[8] = {
53  8, 16, 24, 32, 40, 48, 56, 256
54 };
55 
56 // decay level table (3dB per step)
57 // 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,93 (dB)
58 #define SC(db) unsigned(db * (2.0f / ENV_STEP))
59 static const unsigned dl_tab[16] = {
60  SC( 0), SC( 1), SC( 2), SC(3 ), SC(4 ), SC(5 ), SC(6 ), SC( 7),
61  SC( 8), SC( 9), SC(10), SC(11), SC(12), SC(13), SC(14), SC(31)
62 };
63 #undef SC
64 
65 static const byte RATE_STEPS = 8;
66 static const byte eg_inc[15 * RATE_STEPS] = {
67 //cycle:0 1 2 3 4 5 6 7
68  0, 1, 0, 1, 0, 1, 0, 1, // 0 rates 00..12 0 (increment by 0 or 1)
69  0, 1, 0, 1, 1, 1, 0, 1, // 1 rates 00..12 1
70  0, 1, 1, 1, 0, 1, 1, 1, // 2 rates 00..12 2
71  0, 1, 1, 1, 1, 1, 1, 1, // 3 rates 00..12 3
72 
73  1, 1, 1, 1, 1, 1, 1, 1, // 4 rate 13 0 (increment by 1)
74  1, 1, 1, 2, 1, 1, 1, 2, // 5 rate 13 1
75  1, 2, 1, 2, 1, 2, 1, 2, // 6 rate 13 2
76  1, 2, 2, 2, 1, 2, 2, 2, // 7 rate 13 3
77 
78  2, 2, 2, 2, 2, 2, 2, 2, // 8 rate 14 0 (increment by 2)
79  2, 2, 2, 4, 2, 2, 2, 4, // 9 rate 14 1
80  2, 4, 2, 4, 2, 4, 2, 4, // 10 rate 14 2
81  2, 4, 4, 4, 2, 4, 4, 4, // 11 rate 14 3
82 
83  4, 4, 4, 4, 4, 4, 4, 4, // 12 rates 15 0, 15 1, 15 2, 15 3 for decay
84  8, 8, 8, 8, 8, 8, 8, 8, // 13 rates 15 0, 15 1, 15 2, 15 3 for attack (zero time)
85  0, 0, 0, 0, 0, 0, 0, 0, // 14 infinity rates for attack and decay(s)
86 };
87 
88 #define O(a) (a * RATE_STEPS)
89 static const byte eg_rate_select[64] = {
90  O( 0),O( 1),O( 2),O( 3),
91  O( 0),O( 1),O( 2),O( 3),
92  O( 0),O( 1),O( 2),O( 3),
93  O( 0),O( 1),O( 2),O( 3),
94  O( 0),O( 1),O( 2),O( 3),
95  O( 0),O( 1),O( 2),O( 3),
96  O( 0),O( 1),O( 2),O( 3),
97  O( 0),O( 1),O( 2),O( 3),
98  O( 0),O( 1),O( 2),O( 3),
99  O( 0),O( 1),O( 2),O( 3),
100  O( 0),O( 1),O( 2),O( 3),
101  O( 0),O( 1),O( 2),O( 3),
102  O( 0),O( 1),O( 2),O( 3),
103  O( 4),O( 5),O( 6),O( 7),
104  O( 8),O( 9),O(10),O(11),
105  O(12),O(12),O(12),O(12),
106 };
107 #undef O
108 
109 // rate 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
110 // shift 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0
111 // mask 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1, 0, 0, 0, 0
112 #define O(a) (a)
113 static const byte eg_rate_shift[64] = {
114  O(12),O(12),O(12),O(12),
115  O(11),O(11),O(11),O(11),
116  O(10),O(10),O(10),O(10),
117  O( 9),O( 9),O( 9),O( 9),
118  O( 8),O( 8),O( 8),O( 8),
119  O( 7),O( 7),O( 7),O( 7),
120  O( 6),O( 6),O( 6),O( 6),
121  O( 5),O( 5),O( 5),O( 5),
122  O( 4),O( 4),O( 4),O( 4),
123  O( 3),O( 3),O( 3),O( 3),
124  O( 2),O( 2),O( 2),O( 2),
125  O( 1),O( 1),O( 1),O( 1),
126  O( 0),O( 0),O( 0),O( 0),
127  O( 0),O( 0),O( 0),O( 0),
128  O( 0),O( 0),O( 0),O( 0),
129  O( 0),O( 0),O( 0),O( 0),
130 };
131 #undef O
132 
133 
134 // number of steps to take in quarter of lfo frequency
135 // TODO check if frequency matches real chip
136 #define O(a) int((EG_TIMER_OVERFLOW / a) / 6)
137 static const int lfo_period[8] = {
138  O(0.168f), O(2.019f), O(3.196f), O(4.206f),
139  O(5.215f), O(5.888f), O(6.224f), O(7.066f)
140 };
141 #undef O
142 
143 
144 #define O(a) int(a * 65536)
145 static const int vib_depth[8] = {
146  O( 0.0f ), O( 3.378f), O( 5.065f), O( 6.750f),
147  O(10.114f), O(20.170f), O(40.106f), O(79.307f)
148 };
149 #undef O
150 
151 
152 #define SC(db) int(db * (2.0f / ENV_STEP))
153 static const int am_depth[8] = {
154  SC(0.0f ), SC(1.781f), SC(2.906f), SC( 3.656f),
155  SC(4.406f), SC(5.906f), SC(7.406f), SC(11.91f )
156 };
157 #undef SC
158 
159 
160 YMF278::Slot::Slot()
161 {
162  reset();
163 }
164 
165 // Sign extend a 4-bit value to int (32-bit)
166 // require: x in range [0..15]
167 static inline int sign_extend_4(int x)
168 {
169  return (x ^ 8) - 8;
170 }
171 
172 // Params: oct in [0 .. 15]
173 // fn in [0 .. 1023]
174 // We want to interpret oct as a signed 4-bit number and calculate
175 // ((fn | 1024) + vib) << (5 + sign_extend_4(oct))
176 // Though in this formula the shift can go over a negative distance (in that
177 // case we should shift in the other direction).
178 static inline unsigned calcStep(unsigned oct, unsigned fn, unsigned vib = 0)
179 {
180  oct ^= 8; // [0..15] -> [8..15][0..7] == sign_extend_4(x) + 8
181  unsigned t = (fn + 1024 + vib) << oct; // use '+' iso '|' (generates slightly better code)
182  return t >> 3; // was shifted 3 positions too far
183 }
184 
185 void YMF278::Slot::reset()
186 {
187  wave = FN = OCT = PRVB = LD = TL = pan = lfo = vib = AM = 0;
188  AR = D1R = DL = D2R = RC = RR = 0;
189  stepptr = 0;
190  step = calcStep(OCT, FN);
191  bits = startaddr = loopaddr = endaddr = 0;
192  env_vol = MAX_ATT_INDEX;
193 
194  lfo_active = false;
195  lfo_cnt = lfo_step = 0;
196  lfo_max = lfo_period[0];
197 
198  state = EG_OFF;
199  active = false;
200 
201  // not strictly needed, but avoid UMR on savestate
202  pos = sample1 = sample2 = 0;
203 }
204 
205 int YMF278::Slot::compute_rate(int val) const
206 {
207  if (val == 0) {
208  return 0;
209  } else if (val == 15) {
210  return 63;
211  }
212  int res;
213  if (RC != 15) {
214  // TODO it may be faster to store 'OCT' sign extended
215  int oct = sign_extend_4(OCT);
216  res = (oct + RC) * 2 + (FN & 0x200 ? 1 : 0) + val * 4;
217  } else {
218  res = val * 4;
219  }
220  if (res < 0) {
221  res = 0;
222  } else if (res > 63) {
223  res = 63;
224  }
225  return res;
226 }
227 
228 int YMF278::Slot::compute_vib() const
229 {
230  return (((lfo_step << 8) / lfo_max) * vib_depth[int(vib)]) >> 24;
231 }
232 
233 
234 int YMF278::Slot::compute_am() const
235 {
236  if (lfo_active && AM) {
237  return (((lfo_step << 8) / lfo_max) * am_depth[int(AM)]) >> 12;
238  } else {
239  return 0;
240  }
241 }
242 
243 void YMF278::Slot::set_lfo(int newlfo)
244 {
245  lfo_step = (((lfo_step << 8) / lfo_max) * newlfo) >> 8;
246  lfo_cnt = (((lfo_cnt << 8) / lfo_max) * newlfo) >> 8;
247 
248  lfo = newlfo;
249  lfo_max = lfo_period[int(lfo)];
250 }
251 
252 
253 void YMF278::advance()
254 {
255  eg_cnt++;
256  for (auto& op : slots) {
257  if (op.lfo_active) {
258  op.lfo_cnt++;
259  if (op.lfo_cnt < op.lfo_max) {
260  op.lfo_step++;
261  } else if (op.lfo_cnt < (op.lfo_max * 3)) {
262  op.lfo_step--;
263  } else {
264  op.lfo_step++;
265  if (op.lfo_cnt == (op.lfo_max * 4)) {
266  op.lfo_cnt = 0;
267  }
268  }
269  }
270 
271  // Envelope Generator
272  switch(op.state) {
273  case EG_ATT: { // attack phase
274  byte rate = op.compute_rate(op.AR);
275  if (rate < 4) {
276  break;
277  }
278  byte shift = eg_rate_shift[rate];
279  if (!(eg_cnt & ((1 << shift) -1))) {
280  byte select = eg_rate_select[rate];
281  op.env_vol += (~op.env_vol * eg_inc[select + ((eg_cnt >> shift) & 7)]) >> 3;
282  if (op.env_vol <= MIN_ATT_INDEX) {
283  op.env_vol = MIN_ATT_INDEX;
284  if (op.DL) {
285  op.state = EG_DEC;
286  } else {
287  op.state = EG_SUS;
288  }
289  }
290  }
291  break;
292  }
293  case EG_DEC: { // decay phase
294  byte rate = op.compute_rate(op.D1R);
295  if (rate < 4) {
296  break;
297  }
298  byte shift = eg_rate_shift[rate];
299  if (!(eg_cnt & ((1 << shift) -1))) {
300  byte select = eg_rate_select[rate];
301  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
302 
303  if ((unsigned(op.env_vol) > dl_tab[6]) && op.PRVB) {
304  op.state = EG_REV;
305  } else {
306  if (op.env_vol >= op.DL) {
307  op.state = EG_SUS;
308  }
309  }
310  }
311  break;
312  }
313  case EG_SUS: { // sustain phase
314  byte rate = op.compute_rate(op.D2R);
315  if (rate < 4) {
316  break;
317  }
318  byte shift = eg_rate_shift[rate];
319  if (!(eg_cnt & ((1 << shift) -1))) {
320  byte select = eg_rate_select[rate];
321  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
322 
323  if ((unsigned(op.env_vol) > dl_tab[6]) && op.PRVB) {
324  op.state = EG_REV;
325  } else {
326  if (op.env_vol >= MAX_ATT_INDEX) {
327  op.env_vol = MAX_ATT_INDEX;
328  op.active = false;
329  }
330  }
331  }
332  break;
333  }
334  case EG_REL: { // release phase
335  byte rate = op.compute_rate(op.RR);
336  if (rate < 4) {
337  break;
338  }
339  byte shift = eg_rate_shift[rate];
340  if (!(eg_cnt & ((1 << shift) -1))) {
341  byte select = eg_rate_select[rate];
342  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
343 
344  if ((unsigned(op.env_vol) > dl_tab[6]) && op.PRVB) {
345  op.state = EG_REV;
346  } else {
347  if (op.env_vol >= MAX_ATT_INDEX) {
348  op.env_vol = MAX_ATT_INDEX;
349  op.active = false;
350  }
351  }
352  }
353  break;
354  }
355  case EG_REV: { // pseudo reverb
356  // TODO improve env_vol update
357  byte rate = op.compute_rate(5);
358  //if (rate < 4) {
359  // break;
360  //}
361  byte shift = eg_rate_shift[rate];
362  if (!(eg_cnt & ((1 << shift) - 1))) {
363  byte select = eg_rate_select[rate];
364  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
365 
366  if (op.env_vol >= MAX_ATT_INDEX) {
367  op.env_vol = MAX_ATT_INDEX;
368  op.active = false;
369  }
370  }
371  break;
372  }
373  case EG_DMP: { // damping
374  // TODO improve env_vol update, damp is just fastest decay now
375  byte rate = 56;
376  byte shift = eg_rate_shift[rate];
377  if (!(eg_cnt & ((1 << shift) - 1))) {
378  byte select = eg_rate_select[rate];
379  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
380 
381  if (op.env_vol >= MAX_ATT_INDEX) {
382  op.env_vol = MAX_ATT_INDEX;
383  op.active = false;
384  }
385  }
386  break;
387  }
388  case EG_OFF:
389  // nothing
390  break;
391 
392  default:
393  UNREACHABLE;
394  }
395  }
396 }
397 
398 int16_t YMF278::getSample(Slot& op)
399 {
400  // TODO How does this behave when R#2 bit 0 = 1?
401  // As-if read returns 0xff? (Like for CPU memory reads.) Or is
402  // sound generation blocked at some higher level?
403  int16_t sample;
404  switch (op.bits) {
405  case 0: {
406  // 8 bit
407  sample = readMem(op.startaddr + op.pos) << 8;
408  break;
409  }
410  case 1: {
411  // 12 bit
412  unsigned addr = op.startaddr + ((op.pos / 2) * 3);
413  if (op.pos & 1) {
414  sample = readMem(addr + 2) << 8 |
415  ((readMem(addr + 1) << 4) & 0xF0);
416  } else {
417  sample = readMem(addr + 0) << 8 |
418  (readMem(addr + 1) & 0xF0);
419  }
420  break;
421  }
422  case 2: {
423  // 16 bit
424  unsigned addr = op.startaddr + (op.pos * 2);
425  sample = (readMem(addr + 0) << 8) |
426  (readMem(addr + 1));
427  break;
428  }
429  default:
430  // TODO unspecified
431  sample = 0;
432  }
433  return sample;
434 }
435 
436 bool YMF278::anyActive()
437 {
438  for (auto& op : slots) {
439  if (op.active) return true;
440  }
441  return false;
442 }
443 
444 void YMF278::generateChannels(int** bufs, unsigned num)
445 {
446  if (!anyActive()) {
447  // TODO update internal state, even if muted
448  // TODO also mute individual channels
449  for (int i = 0; i < 24; ++i) {
450  bufs[i] = nullptr;
451  }
452  return;
453  }
454 
455  int vl = mix_level[pcm_l];
456  int vr = mix_level[pcm_r];
457  for (unsigned j = 0; j < num; ++j) {
458  for (int i = 0; i < 24; ++i) {
459  auto& sl = slots[i];
460  if (!sl.active) {
461  //bufs[i][2 * j + 0] += 0;
462  //bufs[i][2 * j + 1] += 0;
463  continue;
464  }
465 
466  int16_t sample = (sl.sample1 * (0x10000 - sl.stepptr) +
467  sl.sample2 * sl.stepptr) >> 16;
468  int vol = sl.TL + (sl.env_vol >> 2) + sl.compute_am();
469 
470  int volLeft = vol + pan_left [int(sl.pan)] + vl;
471  int volRight = vol + pan_right[int(sl.pan)] + vr;
472  // TODO prob doesn't happen in real chip
473  volLeft = std::max(0, volLeft);
474  volRight = std::max(0, volRight);
475 
476  bufs[i][2 * j + 0] += (sample * volume[volLeft] ) >> 14;
477  bufs[i][2 * j + 1] += (sample * volume[volRight]) >> 14;
478 
479  unsigned step = (sl.lfo_active && sl.vib)
480  ? calcStep(sl.OCT, sl.FN, sl.compute_vib())
481  : sl.step;
482  sl.stepptr += step;
483 
484  while (sl.stepptr >= 0x10000) {
485  sl.stepptr -= 0x10000;
486  sl.sample1 = sl.sample2;
487  sl.pos++;
488  if (sl.pos >= sl.endaddr) {
489  sl.pos = sl.loopaddr;
490  }
491  sl.sample2 = getSample(sl);
492  }
493  }
494  advance();
495  }
496 }
497 
498 void YMF278::keyOnHelper(YMF278::Slot& slot)
499 {
500  slot.active = true;
501 
502  slot.state = EG_ATT;
503  slot.stepptr = 0;
504  slot.pos = 0;
505  slot.sample1 = getSample(slot);
506  slot.pos = 1;
507  slot.sample2 = getSample(slot);
508 }
509 
511 {
512  updateStream(time); // TODO optimize only for regs that directly influence sound
513  writeRegDirect(reg, data, time);
514 }
515 
516 void YMF278::writeRegDirect(byte reg, byte data, EmuTime::param time)
517 {
518  // Handle slot registers specifically
519  if (reg >= 0x08 && reg <= 0xF7) {
520  int snum = (reg - 8) % 24;
521  auto& slot = slots[snum];
522  switch ((reg - 8) / 24) {
523  case 0: {
524  slot.wave = (slot.wave & 0x100) | data;
525  int wavetblhdr = (regs[2] >> 2) & 0x7;
526  int base = (slot.wave < 384 || !wavetblhdr) ?
527  (slot.wave * 12) :
528  (wavetblhdr * 0x80000 + ((slot.wave - 384) * 12));
529  byte buf[12];
530  for (int i = 0; i < 12; ++i) {
531  // TODO What if R#2 bit 0 = 1?
532  // See also getSample()
533  buf[i] = readMem(base + i);
534  }
535  slot.bits = (buf[0] & 0xC0) >> 6;
536  slot.startaddr = buf[2] | (buf[1] << 8) |
537  ((buf[0] & 0x3F) << 16);
538  slot.loopaddr = buf[4] + (buf[3] << 8);
539  slot.endaddr = (((buf[6] + (buf[5] << 8)) ^ 0xFFFF) + 1);
540  for (int i = 7; i < 12; ++i) {
541  // Verified on real YMF278:
542  // After tone loading, if you read these
543  // registers, their value actually has changed.
544  writeRegDirect(8 + snum + (i - 2) * 24, buf[i], time);
545  }
546  if ((regs[reg + 0x60] & 0x080)) {
547  keyOnHelper(slot);
548  }
549  break;
550  }
551  case 1: {
552  slot.wave = (slot.wave & 0xFF) | ((data & 0x1) << 8);
553  slot.FN = (slot.FN & 0x380) | (data >> 1);
554  slot.step = calcStep(slot.OCT, slot.FN);
555  break;
556  }
557  case 2: {
558  slot.FN = (slot.FN & 0x07F) | ((data & 0x07) << 7);
559  slot.PRVB = ((data & 0x08) >> 3);
560  slot.OCT = ((data & 0xF0) >> 4);
561  slot.step = calcStep(slot.OCT, slot.FN);
562  break;
563  }
564  case 3:
565  slot.TL = data >> 1;
566  slot.LD = data & 0x1;
567 
568  // TODO
569  if (slot.LD) {
570  // directly change volume
571  } else {
572  // interpolate volume
573  }
574  break;
575  case 4:
576  if (data & 0x10) {
577  // output to DO1 pin:
578  // this pin is not used in moonsound
579  // we emulate this by muting the sound
580  slot.pan = 8; // both left/right -inf dB
581  } else {
582  slot.pan = data & 0x0F;
583  }
584 
585  if (data & 0x020) {
586  // LFO reset
587  slot.lfo_active = false;
588  slot.lfo_cnt = 0;
589  slot.lfo_max = lfo_period[int(slot.vib)];
590  slot.lfo_step = 0;
591  } else {
592  // LFO activate
593  slot.lfo_active = true;
594  }
595 
596  switch (data >> 6) {
597  case 0: // tone off, no damp
598  if (slot.active && (slot.state != EG_REV) ) {
599  slot.state = EG_REL;
600  }
601  break;
602  case 2: // tone on, no damp
603  // 'Life on Mars' bug fix:
604  // In case KEY=ON + DAMP (value 0xc0) and we reach
605  // 'env_vol == MAX_ATT_INDEX' (-> slot.active = false)
606  // we didn't trigger keyOnHelper() because KEY didn't
607  // change OFF->ON. Fixed by also checking slot.state.
608  // TODO real HW is probably simpler because EG_DMP is not
609  // an actual state, nor is 'slot.active' stored.
610  if (!slot.active || !(regs[reg] & 0x080)) {
611  keyOnHelper(slot);
612  }
613  break;
614  case 1: // tone off, damp
615  case 3: // tone on, damp
616  slot.state = EG_DMP;
617  break;
618  }
619  break;
620  case 5:
621  slot.vib = data & 0x7;
622  slot.set_lfo((data >> 3) & 0x7);
623  break;
624  case 6:
625  slot.AR = data >> 4;
626  slot.D1R = data & 0xF;
627  break;
628  case 7:
629  slot.DL = dl_tab[data >> 4];
630  slot.D2R = data & 0xF;
631  break;
632  case 8:
633  slot.RC = data >> 4;
634  slot.RR = data & 0xF;
635  break;
636  case 9:
637  slot.AM = data & 0x7;
638  break;
639  }
640  } else {
641  // All non-slot registers
642  switch (reg) {
643  case 0x00: // TEST
644  case 0x01:
645  break;
646 
647  case 0x02:
648  // wave-table-header / memory-type / memory-access-mode
649  // Simply store in regs[2]
650  break;
651 
652  case 0x03:
653  // Verified on real YMF278:
654  // * Don't update the 'memadr' variable on writes to
655  // reg 3 and 4. Only store the value in the 'regs'
656  // array for later use.
657  // * The upper 2 bits are not used to address the
658  // external memories (so from a HW pov they don't
659  // matter). But if you read back this register, the
660  // upper 2 bits always read as '0' (even if you wrote
661  // '1'). So we mask the bits here already.
662  data &= 0x3F;
663  break;
664 
665  case 0x04:
666  // See reg 3.
667  break;
668 
669  case 0x05:
670  // Verified on real YMF278: (see above)
671  // Only writes to reg 5 change the (full) 'memadr'.
672  memadr = (regs[3] << 16) | (regs[4] << 8) | data;
673  break;
674 
675  case 0x06: // memory data
676  if (regs[2] & 1) {
677  writeMem(memadr, data);
678  ++memadr; // no need to mask (again) here
679  } else {
680  // Verified on real YMF278:
681  // - writes are ignored
682  // - memadr is NOT increased
683  }
684  break;
685 
686  case 0xF8:
687  // TODO use these
688  fm_l = data & 0x7;
689  fm_r = (data >> 3) & 0x7;
690  break;
691 
692  case 0xF9:
693  pcm_l = data & 0x7;
694  pcm_r = (data >> 3) & 0x7;
695  break;
696  }
697  }
698 
699  regs[reg] = data;
700 }
701 
703 {
704  // no need to call updateStream(time)
705  byte result = peekReg(reg);
706  if (reg == 6) {
707  // Memory Data Register
708  if (regs[2] & 1) {
709  // Verified on real YMF278:
710  // memadr is only increased when 'regs[2] & 1'
711  ++memadr; // no need to mask (again) here
712  }
713  }
714  return result;
715 }
716 
718 {
719  byte result;
720  switch (reg) {
721  case 2: // 3 upper bits are device ID
722  result = (regs[2] & 0x1F) | 0x20;
723  break;
724 
725  case 6: // Memory Data Register
726  if (regs[2] & 1) {
727  result = readMem(memadr);
728  } else {
729  // Verified on real YMF278
730  result = 0xff;
731  }
732  break;
733 
734  default:
735  result = regs[reg];
736  break;
737  }
738  return result;
739 }
740 
741 YMF278::YMF278(const std::string& name_, int ramSize_,
742  const DeviceConfig& config)
743  : ResampledSoundDevice(config.getMotherBoard(), name_, "MoonSound wave-part",
744  24, true)
745  , motherBoard(config.getMotherBoard())
746  , debugRegisters(motherBoard, getName())
747  , debugMemory (motherBoard, getName())
748  , rom(getName() + " ROM", "rom", config)
749  , ramSize(ramSize_ * 1024) // in kB
750  , ram(ramSize)
751 {
752  if (rom.getSize() != 0x200000) { // 2MB
753  throw MSXException(
754  "Wrong ROM for MoonSound (YMF278). The ROM (usually "
755  "called yrw801.rom) should have a size of exactly 2MB.");
756  }
757  if ((ramSize_ != 0) && // - -
758  (ramSize_ != 128) && // 128kB -
759  (ramSize_ != 256) && // 128kB 128kB
760  (ramSize_ != 512) && // 512kB -
761  (ramSize_ != 640) && // 512kB 128kB
762  (ramSize_ != 1024) && // 512kB 512kB
763  (ramSize_ != 2048)) { // 512kB 512kB 512kB 512kB
765  "Wrong sampleram size for MoonSound (YMF278). "
766  "Got " << ramSize_ << ", but must be one of "
767  "0, 128, 256, 512, 640, 1024 or 2048.");
768  }
769 
770  memadr = 0; // avoid UMR
771 
772  setInputRate(44100);
773 
774  reset(motherBoard.getCurrentTime());
775  registerSound(config);
776 
777  // Volume table, 1 = -0.375dB, 8 = -3dB, 256 = -96dB
778  for (int i = 0; i < 256; ++i) {
779  volume[i] = int(32768.0 * exp2((-0.375 / 6) * i));
780  }
781  for (int i = 256; i < 256 * 4; ++i) {
782  volume[i] = 0;
783  }
784 }
785 
787 {
788  unregisterSound();
789 }
790 
792 {
793  memset(ram.data(), 0, ramSize);
794 }
795 
797 {
798  updateStream(time);
799 
800  eg_cnt = 0;
801 
802  for (auto& op : slots) {
803  op.reset();
804  }
805  regs[2] = 0; // avoid UMR
806  for (int i = 255; i >= 0; --i) { // reverse order to avoid UMR
807  writeRegDirect(i, 0, time);
808  }
809  memadr = 0;
810  fm_l = fm_r = pcm_l = pcm_r = 0;
811 }
812 
813 // This routine translates an address from the (upper) MoonSound address space
814 // to an address inside the (linearized) SRAM address space.
815 //
816 // The following info is based on measurements on a real MoonSound (v2.0)
817 // PCB. This PCB can have several possible SRAM configurations:
818 // 128kB:
819 // 1 SRAM chip of 128kB, chip enable (/CE) of this SRAM chip is connected to
820 // the 1Y0 output of a 74LS139 (2-to-4 decoder). The enable input of the
821 // 74LS139 is connected to YMF278 pin /MCS6 and the 74LS139 1B:1A inputs are
822 // connected to YMF278 pins MA18:MA17. So the SRAM is selected when /MC6 is
823 // active and MA18:MA17 == 0:0.
824 // 256kB:
825 // 2 SRAM chips of 128kB. First one connected as above. Second one has /CE
826 // connected to 74LS139 pin 1Y1. So SRAM2 is selected when /MSC6 is active
827 // and MA18:MA17 == 0:1.
828 // 512kB:
829 // 1 SRAM chip of 512kB, /CE connected to /MCS6
830 // 640kB:
831 // 1 SRAM chip of 512kB, /CE connected to /MCS6
832 // 1 SRAM chip of 128kB, /CE connected to /MCS7.
833 // (This means SRAM2 is potentially mirrored over a 512kB region)
834 // 1024kB:
835 // 1 SRAM chip of 512kB, /CE connected to /MCS6
836 // 1 SRAM chip of 512kB, /CE connected to /MCS7
837 // 2048kB:
838 // 1 SRAM chip of 512kB, /CE connected to /MCS6
839 // 1 SRAM chip of 512kB, /CE connected to /MCS7
840 // 1 SRAM chip of 512kB, /CE connected to /MCS8
841 // 1 SRAM chip of 512kB, /CE connected to /MCS9
842 // This configuration is not so easy to create on the v2.0 PCB. So it's
843 // very rare.
844 //
845 // So the /MCS6 and /MCS7 (and /MCS8 and /MCS9 in case of 2048kB) signals are
846 // used to select the different SRAM chips. The meaning of these signals
847 // depends on the 'memory access mode'. This mode can be changed at run-time
848 // via bit 1 in register 2. The following table indicates for which regions
849 // these signals are active (normally MoonSound should be used with mode=0):
850 // mode=0 mode=1
851 // /MCS6 0x200000-0x27FFFF 0x380000-0x39FFFF
852 // /MCS7 0x280000-0x2FFFFF 0x3A0000-0x3BFFFF
853 // /MCS8 0x300000-0x37FFFF 0x3C0000-0x3DFFFF
854 // /MCS9 0x380000-0x3FFFFF 0x3E0000-0x3FFFFF
855 //
856 // (For completeness) MoonSound also has 2MB ROM (YRW801), /CE of this ROM is
857 // connected to YMF278 /MCS0. In both mode=0 and mode=1 this signal is active
858 // for the region 0x000000-0x1FFFFF. (But this routine does not handle ROM).
859 unsigned YMF278::getRamAddress(unsigned addr) const
860 {
861  addr -= 0x200000; // RAM starts at 0x200000
862  if (unlikely(regs[2] & 2)) {
863  // Normally MoonSound is used in 'memory access mode = 0'. But
864  // in the rare case that mode=1 we adjust the address.
865  if ((0x180000 <= addr) && (addr <= 0x1FFFFF)) {
866  addr -= 0x180000;
867  switch (addr & 0x060000) {
868  case 0x000000: // [0x380000-0x39FFFF]
869  // 1st 128kB of SRAM1
870  break;
871  case 0x020000: // [0x3A0000-0x3BFFFF]
872  if (ramSize == 256 * 1024) {
873  // 2nd 128kB SRAM chip
874  } else {
875  // 2nd block of 128kB in SRAM2
876  // In case of 512+128, we use mirroring
877  addr += 0x080000;
878  }
879  break;
880  case 0x040000: // [0x3C0000-0x3DFFFF]
881  // 3rd 128kB block in SRAM3
882  addr += 0x100000;
883  break;
884  case 0x060000: // [0x3EFFFF-0x3FFFFF]
885  // 4th 128kB block in SRAM4
886  addr += 0x180000;
887  break;
888  }
889  } else {
890  addr = unsigned(-1); // unmapped
891  }
892  }
893  if (ramSize == 640 * 1024) {
894  // Verified on real MoonSound cartridge (v2.0): In case of
895  // 640kB (1x512kB + 1x128kB), the 128kB SRAM chip is 4 times
896  // visible. None of the other SRAM configurations show similar
897  // mirroring (because the others are powers of two).
898  if (addr > 0x080000) {
899  addr &= ~0x060000;
900  }
901  }
902  return addr;
903 }
904 
905 byte YMF278::readMem(unsigned address) const
906 {
907  // Verified on real YMF278: address space wraps at 4MB.
908  address &= 0x3FFFFF;
909  if (address < 0x200000) {
910  // ROM connected to /MCS0
911  return rom[address];
912  } else {
913  unsigned ramAddr = getRamAddress(address);
914  if (ramAddr < ramSize) {
915  return ram[ramAddr];
916  } else {
917  // unmapped region
918  return 255; // TODO check
919  }
920  }
921 }
922 
923 void YMF278::writeMem(unsigned address, byte value)
924 {
925  address &= 0x3FFFFF;
926  if (address < 0x200000) {
927  // can't write to ROM
928  } else {
929  unsigned ramAddr = getRamAddress(address);
930  if (ramAddr < ramSize) {
931  ram[ramAddr] = value;
932  } else {
933  // can't write to unmapped memory
934  }
935  }
936 }
937 
938 // version 1: initial version, some variables were saved as char
939 // version 2: serialization framework was fixed to save/load chars as numbers
940 // but for backwards compatibility we still load old savestates as
941 // characters
942 // version 3: 'step' is no longer stored (it is recalculated)
943 template<typename Archive>
944 void YMF278::Slot::serialize(Archive& ar, unsigned version)
945 {
946  // TODO restore more state from registers
947  ar.serialize("startaddr", startaddr);
948  ar.serialize("loopaddr", loopaddr);
949  ar.serialize("endaddr", endaddr);
950  ar.serialize("stepptr", stepptr);
951  ar.serialize("pos", pos);
952  ar.serialize("sample1", sample1);
953  ar.serialize("sample2", sample2);
954  ar.serialize("env_vol", env_vol);
955  ar.serialize("lfo_cnt", lfo_cnt);
956  ar.serialize("lfo_step", lfo_step);
957  ar.serialize("lfo_max", lfo_max);
958  ar.serialize("DL", DL);
959  ar.serialize("wave", wave);
960  ar.serialize("FN", FN);
961  if (ar.versionAtLeast(version, 2)) {
962  ar.serialize("OCT", OCT);
963  ar.serialize("PRVB", PRVB);
964  ar.serialize("LD", LD);
965  ar.serialize("TL", TL);
966  ar.serialize("pan", pan);
967  ar.serialize("lfo", lfo);
968  ar.serialize("vib", vib);
969  ar.serialize("AM", AM);
970  ar.serialize("AR", AR);
971  ar.serialize("D1R", D1R);
972  ar.serialize("D2R", D2R);
973  ar.serialize("RC", RC);
974  ar.serialize("RR", RR);
975  } else {
976  ar.serializeChar("OCT", OCT);
977  ar.serializeChar("PRVB", PRVB);
978  ar.serializeChar("LD", LD);
979  ar.serializeChar("TL", TL);
980  ar.serializeChar("pan", pan);
981  ar.serializeChar("lfo", lfo);
982  ar.serializeChar("vib", vib);
983  ar.serializeChar("AM", AM);
984  ar.serializeChar("AR", AR);
985  ar.serializeChar("D1R", D1R);
986  ar.serializeChar("D2R", D2R);
987  ar.serializeChar("RC", RC);
988  ar.serializeChar("RR", RR);
989  }
990  ar.serialize("bits", bits);
991  ar.serialize("active", active);
992  ar.serialize("state", state);
993  ar.serialize("lfo_active", lfo_active);
994 
995  // Recalculate redundant state
996  if (ar.isLoader()) {
997  step = calcStep(OCT, FN);
998  }
999 
1000  // This old comment is NOT completely true:
1001  // Older version also had "env_vol_step" and "env_vol_lim" but those
1002  // members were nowhere used, so removed those in the current
1003  // version (it's ok to remove members from the savestate without
1004  // updating the version number).
1005  // When you remove member variables without increasing the version
1006  // number, new openMSX executables can still read old savestates. And
1007  // if you try to load a new savestate in an old openMSX version you do
1008  // get a (cryptic) error message. But if the version number is
1009  // increased the error message is much clearer.
1010 }
1011 
1012 // version 1: initial version
1013 // version 2: loadTime and busyTime moved to MSXMoonSound class
1014 // version 3: memadr cannot be restored from register values
1015 template<typename Archive>
1016 void YMF278::serialize(Archive& ar, unsigned version)
1017 {
1018  ar.serialize("slots", slots);
1019  ar.serialize("eg_cnt", eg_cnt);
1020  ar.serialize_blob("ram", ram.data(), ramSize);
1021  ar.serialize_blob("registers", regs, sizeof(regs));
1022  if (ar.versionAtLeast(version, 3)) { // must come after 'regs'
1023  ar.serialize("memadr", memadr);
1024  } else {
1025  assert(ar.isLoader());
1026  // Old formats didn't store 'memadr' so we also can't magically
1027  // restore the correct value. The best we can do is restore the
1028  // last set address.
1029  regs[3] &= 0x3F; // mask upper two bits
1030  memadr = (regs[3] << 16) | (regs[4] << 8) | regs[5];
1031  }
1032 
1033  // TODO restore more state from registers
1034  static const byte rewriteRegs[] = {
1035  0xf8, // fm_l, fm_r
1036  0xf9, // pcm_l, pcm_r
1037  };
1038  if (ar.isLoader()) {
1039  EmuTime::param time = motherBoard.getCurrentTime();
1040  for (auto r : rewriteRegs) {
1041  writeRegDirect(r, regs[r], time);
1042  }
1043  }
1044 }
1046 
1047 
1048 // class DebugRegisters
1049 
1050 YMF278::DebugRegisters::DebugRegisters(MSXMotherBoard& motherBoard_,
1051  const std::string& name_)
1052  : SimpleDebuggable(motherBoard_, name_ + " regs",
1053  "OPL4 registers", 0x100)
1054 {
1055 }
1056 
1057 byte YMF278::DebugRegisters::read(unsigned address)
1058 {
1059  auto& ymf278 = OUTER(YMF278, debugRegisters);
1060  return ymf278.peekReg(address);
1061 }
1062 
1063 void YMF278::DebugRegisters::write(unsigned address, byte value, EmuTime::param time)
1064 {
1065  auto& ymf278 = OUTER(YMF278, debugRegisters);
1066  ymf278.writeReg(address, value, time);
1067 }
1068 
1069 
1070 // class DebugMemory
1071 
1072 YMF278::DebugMemory::DebugMemory(MSXMotherBoard& motherBoard_,
1073  const std::string& name_)
1074  : SimpleDebuggable(motherBoard_, name_ + " mem",
1075  "OPL4 memory (includes both ROM and RAM)", 0x400000) // 4MB
1076 {
1077 }
1078 
1079 byte YMF278::DebugMemory::read(unsigned address)
1080 {
1081  auto& ymf278 = OUTER(YMF278, debugMemory);
1082  return ymf278.readMem(address);
1083 }
1084 
1085 void YMF278::DebugMemory::write(unsigned address, byte value)
1086 {
1087  auto& ymf278 = OUTER(YMF278, debugMemory);
1088  ymf278.writeMem(address, value);
1089 }
1090 
1091 } // namespace openmsx
void clearRam()
Definition: YMF278.cc:791
byte readMem(unsigned address) const
Definition: YMF278.cc:905
byte readReg(byte reg)
Definition: YMF278.cc:702
#define unlikely(x)
Definition: likely.hh:15
void unregisterSound()
Unregisters this sound device with the Mixer.
Definition: SoundDevice.cc:120
uint8_t byte
8 bit unsigned integer
Definition: openmsx.hh:26
void writeReg(byte reg, byte data, EmuTime::param time)
Definition: YMF278.cc:510
void writeMem(unsigned address, byte value)
Definition: YMF278.cc:923
vecN< N, T > max(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:266
void updateStream(EmuTime::param time)
Definition: SoundDevice.cc:125
void serialize(Archive &ar, unsigned version)
Definition: YMF278.cc:1016
void setInputRate(unsigned sampleRate)
Definition: SoundDevice.hh:78
#define O(a)
Definition: YMF278.cc:144
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
byte peekReg(byte reg) const
Definition: YMF278.cc:717
const std::string & getName() const
Get the unique name that identifies this sound device.
Definition: SoundDevice.hh:24
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
Definition: serialize.hh:817
uint8_t * data()
YMF278(const std::string &name, int ramSize, const DeviceConfig &config)
Definition: YMF278.cc:741
EmuTime::param getCurrentTime()
Convenience method: This is the same as getScheduler().getCurrentTime().
#define OUTER(type, member)
Definition: outer.hh:38
unsigned getSize() const
Definition: Rom.hh:32
const T * data() const
Returns pointer to the start of the memory buffer.
Definition: MemBuffer.hh:90
void serialize(Archive &ar, T &t, unsigned version)
void reset(EmuTime::param time)
Definition: YMF278.cc:796
#define SC(db)
Definition: YMF278.cc:152
void registerSound(const DeviceConfig &config)
Registers this sound device with the Mixer.
Definition: SoundDevice.cc:78
#define UNREACHABLE
Definition: unreachable.hh:35