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