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 short 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  short 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  short 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 + 4] & 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  if (!(regs[reg] & 0x080)) {
604  keyOnHelper(slot);
605  }
606  break;
607  case 1: // tone off, damp
608  case 3: // tone on, damp
609  slot.state = EG_DMP;
610  break;
611  }
612  break;
613  case 5:
614  slot.vib = data & 0x7;
615  slot.set_lfo((data >> 3) & 0x7);
616  break;
617  case 6:
618  slot.AR = data >> 4;
619  slot.D1R = data & 0xF;
620  break;
621  case 7:
622  slot.DL = dl_tab[data >> 4];
623  slot.D2R = data & 0xF;
624  break;
625  case 8:
626  slot.RC = data >> 4;
627  slot.RR = data & 0xF;
628  break;
629  case 9:
630  slot.AM = data & 0x7;
631  break;
632  }
633  } else {
634  // All non-slot registers
635  switch (reg) {
636  case 0x00: // TEST
637  case 0x01:
638  break;
639 
640  case 0x02:
641  // wave-table-header / memory-type / memory-access-mode
642  // Simply store in regs[2]
643  break;
644 
645  case 0x03:
646  // Verified on real YMF278:
647  // * Don't update the 'memadr' variable on writes to
648  // reg 3 and 4. Only store the value in the 'regs'
649  // array for later use.
650  // * The upper 2 bits are not used to address the
651  // external memories (so from a HW pov they don't
652  // matter). But if you read back this register, the
653  // upper 2 bits always read as '0' (even if you wrote
654  // '1'). So we mask the bits here already.
655  data &= 0x3F;
656  break;
657 
658  case 0x04:
659  // See reg 3.
660  break;
661 
662  case 0x05:
663  // Verified on real YMF278: (see above)
664  // Only writes to reg 5 change the (full) 'memadr'.
665  memadr = (regs[3] << 16) | (regs[4] << 8) | data;
666  break;
667 
668  case 0x06: // memory data
669  if (regs[2] & 1) {
670  writeMem(memadr, data);
671  ++memadr; // no need to mask (again) here
672  } else {
673  // Verified on real YMF278:
674  // - writes are ignored
675  // - memadr is NOT increased
676  }
677  break;
678 
679  case 0xF8:
680  // TODO use these
681  fm_l = data & 0x7;
682  fm_r = (data >> 3) & 0x7;
683  break;
684 
685  case 0xF9:
686  pcm_l = data & 0x7;
687  pcm_r = (data >> 3) & 0x7;
688  break;
689  }
690  }
691 
692  regs[reg] = data;
693 }
694 
696 {
697  // no need to call updateStream(time)
698  byte result = peekReg(reg);
699  if (reg == 6) {
700  // Memory Data Register
701  if (regs[2] & 1) {
702  // Verified on real YMF278:
703  // memadr is only increased when 'regs[2] & 1'
704  ++memadr; // no need to mask (again) here
705  }
706  }
707  return result;
708 }
709 
711 {
712  byte result;
713  switch (reg) {
714  case 2: // 3 upper bits are device ID
715  result = (regs[2] & 0x1F) | 0x20;
716  break;
717 
718  case 6: // Memory Data Register
719  if (regs[2] & 1) {
720  result = readMem(memadr);
721  } else {
722  // Verified on real YMF278
723  result = 0xff;
724  }
725  break;
726 
727  default:
728  result = regs[reg];
729  break;
730  }
731  return result;
732 }
733 
734 YMF278::YMF278(const std::string& name, int ramSize_,
735  const DeviceConfig& config)
736  : ResampledSoundDevice(config.getMotherBoard(), name, "MoonSound wave-part",
737  24, true)
738  , motherBoard(config.getMotherBoard())
739  , debugRegisters(motherBoard, getName())
740  , debugMemory (motherBoard, getName())
741  , rom(name + " ROM", "rom", config)
742  , ramSize(ramSize_ * 1024) // in kB
743  , ram(ramSize)
744 {
745  if (rom.getSize() != 0x200000) { // 2MB
746  throw MSXException(
747  "Wrong ROM for MoonSound (YMF278). The ROM (usually "
748  "called yrw801.rom) should have a size of exactly 2MB.");
749  }
750  if ((ramSize_ != 0) && // - -
751  (ramSize_ != 128) && // 128kB -
752  (ramSize_ != 256) && // 128kB 128kB
753  (ramSize_ != 512) && // 512kB -
754  (ramSize_ != 640) && // 512kB 128kB
755  (ramSize_ != 1024) && // 512kB 512kB
756  (ramSize_ != 2048)) { // 512kB 512kB 512kB 512kB
758  "Wrong sampleram size for MoonSound (YMF278). "
759  "Got " << ramSize_ << ", but must be one of "
760  "0, 128, 256, 512, 640, 1024 or 2048.");
761  }
762 
763  memadr = 0; // avoid UMR
764 
765  setInputRate(44100);
766 
767  reset(motherBoard.getCurrentTime());
768  registerSound(config);
769 
770  // Volume table, 1 = -0.375dB, 8 = -3dB, 256 = -96dB
771  for (int i = 0; i < 256; ++i) {
772  volume[i] = int(32768.0 * exp2((-0.375 / 6) * i));
773  }
774  for (int i = 256; i < 256 * 4; ++i) {
775  volume[i] = 0;
776  }
777 }
778 
780 {
781  unregisterSound();
782 }
783 
785 {
786  memset(ram.data(), 0, ramSize);
787 }
788 
790 {
791  updateStream(time);
792 
793  eg_cnt = 0;
794 
795  for (auto& op : slots) {
796  op.reset();
797  }
798  regs[2] = 0; // avoid UMR
799  for (int i = 255; i >= 0; --i) { // reverse order to avoid UMR
800  writeRegDirect(i, 0, time);
801  }
802  memadr = 0;
803  fm_l = fm_r = pcm_l = pcm_r = 0;
804 }
805 
806 // This routine translates an address from the (upper) MoonSound address space
807 // to an address inside the (linearized) SRAM address space.
808 //
809 // The following info is based on measurements on a real MoonSound (v2.0)
810 // PCB. This PCB can have several possible SRAM configurations:
811 // 128kB:
812 // 1 SRAM chip of 128kB, chip enable (/CE) of this SRAM chip is connected to
813 // the 1Y0 output of a 74LS139 (2-to-4 decoder). The enable input of the
814 // 74LS139 is connected to YMF278 pin /MCS6 and the 74LS139 1B:1A inputs are
815 // connected to YMF278 pins MA18:MA17. So the SRAM is selected when /MC6 is
816 // active and MA18:MA17 == 0:0.
817 // 256kB:
818 // 2 SRAM chips of 128kB. First one connected as above. Second one has /CE
819 // connected to 74LS139 pin 1Y1. So SRAM2 is selected when /MSC6 is active
820 // and MA18:MA17 == 0:1.
821 // 512kB:
822 // 1 SRAM chip of 512kB, /CE connected to /MCS6
823 // 640kB:
824 // 1 SRAM chip of 512kB, /CE connected to /MCS6
825 // 1 SRAM chip of 128kB, /CE connected to /MCS7.
826 // (This means SRAM2 is potentially mirrored over a 512kB region)
827 // 1024kB:
828 // 1 SRAM chip of 512kB, /CE connected to /MCS6
829 // 1 SRAM chip of 512kB, /CE connected to /MCS7
830 // 2048kB:
831 // 1 SRAM chip of 512kB, /CE connected to /MCS6
832 // 1 SRAM chip of 512kB, /CE connected to /MCS7
833 // 1 SRAM chip of 512kB, /CE connected to /MCS8
834 // 1 SRAM chip of 512kB, /CE connected to /MCS9
835 // This configuration is not so easy to create on the v2.0 PCB. So it's
836 // very rare.
837 //
838 // So the /MCS6 and /MCS7 (and /MCS8 and /MCS9 in case of 2048kB) signals are
839 // used to select the different SRAM chips. The meaning of these signals
840 // depends on the 'memory access mode'. This mode can be changed at run-time
841 // via bit 1 in register 2. The following table indicates for which regions
842 // these signals are active (normally MoonSound should be used with mode=0):
843 // mode=0 mode=1
844 // /MCS6 0x200000-0x27FFFF 0x380000-0x39FFFF
845 // /MCS7 0x280000-0x2FFFFF 0x3A0000-0x3BFFFF
846 // /MCS8 0x300000-0x37FFFF 0x3C0000-0x3DFFFF
847 // /MCS9 0x380000-0x3FFFFF 0x3E0000-0x3FFFFF
848 //
849 // (For completeness) MoonSound also has 2MB ROM (YRW801), /CE of this ROM is
850 // connected to YMF278 /MCS0. In both mode=0 and mode=1 this signal is active
851 // for the region 0x000000-0x1FFFFF. (But this routine does not handle ROM).
852 unsigned YMF278::getRamAddress(unsigned addr) const
853 {
854  addr -= 0x200000; // RAM starts at 0x200000
855  if (unlikely(regs[2] & 2)) {
856  // Normally MoonSound is used in 'memory access mode = 0'. But
857  // in the rare case that mode=1 we adjust the address.
858  if ((0x180000 <= addr) && (addr <= 0x1FFFFF)) {
859  addr -= 0x180000;
860  switch (addr & 0x060000) {
861  case 0x000000: // [0x380000-0x39FFFF]
862  // 1st 128kB of SRAM1
863  break;
864  case 0x020000: // [0x3A0000-0x3BFFFF]
865  if (ramSize == 256 * 1024) {
866  // 2nd 128kB SRAM chip
867  } else {
868  // 2nd block of 128kB in SRAM2
869  // In case of 512+128, we use mirroring
870  addr += 0x080000;
871  }
872  break;
873  case 0x040000: // [0x3C0000-0x3DFFFF]
874  // 3rd 128kB block in SRAM3
875  addr += 0x100000;
876  break;
877  case 0x060000: // [0x3EFFFF-0x3FFFFF]
878  // 4th 128kB block in SRAM4
879  addr += 0x180000;
880  break;
881  }
882  } else {
883  addr = unsigned(-1); // unmapped
884  }
885  }
886  if (ramSize == 640 * 1024) {
887  // Verified on real MoonSound cartridge (v2.0): In case of
888  // 640kB (1x512kB + 1x128kB), the 128kB SRAM chip is 4 times
889  // visible. None of the other SRAM configurations show similar
890  // mirroring (because the others are powers of two).
891  if (addr > 0x080000) {
892  addr &= ~0x060000;
893  }
894  }
895  return addr;
896 }
897 
898 byte YMF278::readMem(unsigned address) const
899 {
900  // Verified on real YMF278: address space wraps at 4MB.
901  address &= 0x3FFFFF;
902  if (address < 0x200000) {
903  // ROM connected to /MCS0
904  return rom[address];
905  } else {
906  unsigned ramAddr = getRamAddress(address);
907  if (ramAddr < ramSize) {
908  return ram[ramAddr];
909  } else {
910  // unmapped region
911  return 255; // TODO check
912  }
913  }
914 }
915 
916 void YMF278::writeMem(unsigned address, byte value)
917 {
918  address &= 0x3FFFFF;
919  if (address < 0x200000) {
920  // can't write to ROM
921  } else {
922  unsigned ramAddr = getRamAddress(address);
923  if (ramAddr < ramSize) {
924  ram[ramAddr] = value;
925  } else {
926  // can't write to unmapped memory
927  }
928  }
929 }
930 
931 // version 1: initial version, some variables were saved as char
932 // version 2: serialization framework was fixed to save/load chars as numbers
933 // but for backwards compatibility we still load old savestates as
934 // characters
935 // version 3: 'step' is no longer stored (it is recalculated)
936 template<typename Archive>
937 void YMF278::Slot::serialize(Archive& ar, unsigned version)
938 {
939  // TODO restore more state from registers
940  ar.serialize("startaddr", startaddr);
941  ar.serialize("loopaddr", loopaddr);
942  ar.serialize("endaddr", endaddr);
943  ar.serialize("stepptr", stepptr);
944  ar.serialize("pos", pos);
945  ar.serialize("sample1", sample1);
946  ar.serialize("sample2", sample2);
947  ar.serialize("env_vol", env_vol);
948  ar.serialize("lfo_cnt", lfo_cnt);
949  ar.serialize("lfo_step", lfo_step);
950  ar.serialize("lfo_max", lfo_max);
951  ar.serialize("DL", DL);
952  ar.serialize("wave", wave);
953  ar.serialize("FN", FN);
954  if (ar.versionAtLeast(version, 2)) {
955  ar.serialize("OCT", OCT);
956  ar.serialize("PRVB", PRVB);
957  ar.serialize("LD", LD);
958  ar.serialize("TL", TL);
959  ar.serialize("pan", pan);
960  ar.serialize("lfo", lfo);
961  ar.serialize("vib", vib);
962  ar.serialize("AM", AM);
963  ar.serialize("AR", AR);
964  ar.serialize("D1R", D1R);
965  ar.serialize("D2R", D2R);
966  ar.serialize("RC", RC);
967  ar.serialize("RR", RR);
968  } else {
969  ar.serializeChar("OCT", OCT);
970  ar.serializeChar("PRVB", PRVB);
971  ar.serializeChar("LD", LD);
972  ar.serializeChar("TL", TL);
973  ar.serializeChar("pan", pan);
974  ar.serializeChar("lfo", lfo);
975  ar.serializeChar("vib", vib);
976  ar.serializeChar("AM", AM);
977  ar.serializeChar("AR", AR);
978  ar.serializeChar("D1R", D1R);
979  ar.serializeChar("D2R", D2R);
980  ar.serializeChar("RC", RC);
981  ar.serializeChar("RR", RR);
982  }
983  ar.serialize("bits", bits);
984  ar.serialize("active", active);
985  ar.serialize("state", state);
986  ar.serialize("lfo_active", lfo_active);
987 
988  // Recalculate redundant state
989  if (ar.isLoader()) {
990  step = calcStep(OCT, FN);
991  }
992 
993  // This old comment is NOT completely true:
994  // Older version also had "env_vol_step" and "env_vol_lim" but those
995  // members were nowhere used, so removed those in the current
996  // version (it's ok to remove members from the savestate without
997  // updating the version number).
998  // When you remove member variables without increasing the version
999  // number, new openMSX executables can still read old savestates. And
1000  // if you try to load a new savestate in an old openMSX version you do
1001  // get a (cryptic) error message. But if the version number is
1002  // increased the error message is much clearer.
1003 }
1004 
1005 // version 1: initial version
1006 // version 2: loadTime and busyTime moved to MSXMoonSound class
1007 // version 3: memadr cannot be restored from register values
1008 template<typename Archive>
1009 void YMF278::serialize(Archive& ar, unsigned version)
1010 {
1011  ar.serialize("slots", slots);
1012  ar.serialize("eg_cnt", eg_cnt);
1013  ar.serialize_blob("ram", ram.data(), ramSize);
1014  ar.serialize_blob("registers", regs, sizeof(regs));
1015  if (ar.versionAtLeast(version, 3)) { // must come after 'regs'
1016  ar.serialize("memadr", memadr);
1017  } else {
1018  assert(ar.isLoader());
1019  // Old formats didn't store 'memadr' so we also can't magically
1020  // restore the correct value. The best we can do is restore the
1021  // last set address.
1022  regs[3] &= 0x3F; // mask upper two bits
1023  memadr = (regs[3] << 16) | (regs[4] << 8) | regs[5];
1024  }
1025 
1026  // TODO restore more state from registers
1027  static const byte rewriteRegs[] = {
1028  0xf8, // fm_l, fm_r
1029  0xf9, // pcm_l, pcm_r
1030  };
1031  if (ar.isLoader()) {
1032  EmuTime::param time = motherBoard.getCurrentTime();
1033  for (auto r : rewriteRegs) {
1034  writeRegDirect(r, regs[r], time);
1035  }
1036  }
1037 }
1039 
1040 
1041 // class DebugRegisters
1042 
1043 YMF278::DebugRegisters::DebugRegisters(MSXMotherBoard& motherBoard,
1044  const std::string& name)
1045  : SimpleDebuggable(motherBoard, name + " regs",
1046  "OPL4 registers", 0x100)
1047 {
1048 }
1049 
1050 byte YMF278::DebugRegisters::read(unsigned address)
1051 {
1052  auto& ymf278 = OUTER(YMF278, debugRegisters);
1053  return ymf278.peekReg(address);
1054 }
1055 
1056 void YMF278::DebugRegisters::write(unsigned address, byte value, EmuTime::param time)
1057 {
1058  auto& ymf278 = OUTER(YMF278, debugRegisters);
1059  ymf278.writeReg(address, value, time);
1060 }
1061 
1062 
1063 // class DebugMemory
1064 
1065 YMF278::DebugMemory::DebugMemory(MSXMotherBoard& motherBoard,
1066  const std::string& name)
1067  : SimpleDebuggable(motherBoard, name + " mem",
1068  "OPL4 memory (includes both ROM and RAM)", 0x400000) // 4MB
1069 {
1070 }
1071 
1072 byte YMF278::DebugMemory::read(unsigned address)
1073 {
1074  auto& ymf278 = OUTER(YMF278, debugMemory);
1075  return ymf278.readMem(address);
1076 }
1077 
1078 void YMF278::DebugMemory::write(unsigned address, byte value)
1079 {
1080  auto& ymf278 = OUTER(YMF278, debugMemory);
1081  ymf278.writeMem(address, value);
1082 }
1083 
1084 } // namespace openmsx
void clearRam()
Definition: YMF278.cc:784
byte readMem(unsigned address) const
Definition: YMF278.cc:898
byte readReg(byte reg)
Definition: YMF278.cc:695
#define unlikely(x)
Definition: likely.hh:15
void unregisterSound()
Unregisters this sound device with the Mixer.
Definition: SoundDevice.cc:120
void writeReg(byte reg, byte data, EmuTime::param time)
Definition: YMF278.cc:510
void writeMem(unsigned address, byte value)
Definition: YMF278.cc:916
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:1009
void setInputRate(unsigned sampleRate)
Definition: SoundDevice.hh:79
#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:710
unsigned char byte
8 bit unsigned integer
Definition: openmsx.hh:25
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
Definition: serialize.hh:802
uint8_t * data()
YMF278(const std::string &name, int ramSize, const DeviceConfig &config)
Definition: YMF278.cc:734
EmuTime::param getCurrentTime()
Convenience method: This is the same as getScheduler().getCurrentTime().
const string getName(KeyCode keyCode)
Translate key code to key name.
Definition: Keys.cc:373
#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:91
void serialize(Archive &ar, T &t, unsigned version)
void reset(EmuTime::param time)
Definition: YMF278.cc:789
#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