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 
27 class DebugRegisters final : public SimpleDebuggable
28 {
29 public:
30  DebugRegisters(YMF278& ymf278, MSXMotherBoard& motherBoard,
31  const std::string& name);
32  byte read(unsigned address) override;
33  void write(unsigned address, byte value, EmuTime::param time) override;
34 private:
35  YMF278& ymf278;
36 };
37 
38 class DebugMemory final : public SimpleDebuggable
39 {
40 public:
41  DebugMemory(YMF278& ymf278, MSXMotherBoard& motherBoard,
42  const std::string& name);
43  byte read(unsigned address) override;
44  void write(unsigned address, byte value) override;
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 
104 class YMF278::Impl final : public ResampledSoundDevice
105 {
106 public:
107  Impl(YMF278& self, const std::string& name, int ramSize,
108  const DeviceConfig& config);
109  ~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  void generateChannels(int** bufs, unsigned num) override;
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 (auto& op : slots) {
393  if (op.lfo_active) {
394  op.lfo_cnt++;
395  if (op.lfo_cnt < op.lfo_max) {
396  op.lfo_step++;
397  } else if (op.lfo_cnt < (op.lfo_max * 3)) {
398  op.lfo_step--;
399  } else {
400  op.lfo_step++;
401  if (op.lfo_cnt == (op.lfo_max * 4)) {
402  op.lfo_cnt = 0;
403  }
404  }
405  }
406 
407  // Envelope Generator
408  switch(op.state) {
409  case EG_ATT: { // attack phase
410  byte rate = op.compute_rate(op.AR);
411  if (rate < 4) {
412  break;
413  }
414  byte shift = eg_rate_shift[rate];
415  if (!(eg_cnt & ((1 << shift) -1))) {
416  byte select = eg_rate_select[rate];
417  op.env_vol += (~op.env_vol * eg_inc[select + ((eg_cnt >> shift) & 7)]) >> 3;
418  if (op.env_vol <= MIN_ATT_INDEX) {
419  op.env_vol = MIN_ATT_INDEX;
420  if (op.DL) {
421  op.state = EG_DEC;
422  } else {
423  op.state = EG_SUS;
424  }
425  }
426  }
427  break;
428  }
429  case EG_DEC: { // decay phase
430  byte rate = op.compute_rate(op.D1R);
431  if (rate < 4) {
432  break;
433  }
434  byte shift = eg_rate_shift[rate];
435  if (!(eg_cnt & ((1 << shift) -1))) {
436  byte select = eg_rate_select[rate];
437  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
438 
439  if ((unsigned(op.env_vol) > dl_tab[6]) && op.PRVB) {
440  op.state = EG_REV;
441  } else {
442  if (op.env_vol >= op.DL) {
443  op.state = EG_SUS;
444  }
445  }
446  }
447  break;
448  }
449  case EG_SUS: { // sustain phase
450  byte rate = op.compute_rate(op.D2R);
451  if (rate < 4) {
452  break;
453  }
454  byte shift = eg_rate_shift[rate];
455  if (!(eg_cnt & ((1 << shift) -1))) {
456  byte select = eg_rate_select[rate];
457  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
458 
459  if ((unsigned(op.env_vol) > dl_tab[6]) && op.PRVB) {
460  op.state = EG_REV;
461  } else {
462  if (op.env_vol >= MAX_ATT_INDEX) {
463  op.env_vol = MAX_ATT_INDEX;
464  op.active = false;
465  }
466  }
467  }
468  break;
469  }
470  case EG_REL: { // release phase
471  byte rate = op.compute_rate(op.RR);
472  if (rate < 4) {
473  break;
474  }
475  byte shift = eg_rate_shift[rate];
476  if (!(eg_cnt & ((1 << shift) -1))) {
477  byte select = eg_rate_select[rate];
478  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
479 
480  if ((unsigned(op.env_vol) > dl_tab[6]) && op.PRVB) {
481  op.state = EG_REV;
482  } else {
483  if (op.env_vol >= MAX_ATT_INDEX) {
484  op.env_vol = MAX_ATT_INDEX;
485  op.active = false;
486  }
487  }
488  }
489  break;
490  }
491  case EG_REV: { // pseudo reverb
492  // TODO improve env_vol update
493  byte rate = op.compute_rate(5);
494  //if (rate < 4) {
495  // break;
496  //}
497  byte shift = eg_rate_shift[rate];
498  if (!(eg_cnt & ((1 << shift) - 1))) {
499  byte select = eg_rate_select[rate];
500  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
501 
502  if (op.env_vol >= MAX_ATT_INDEX) {
503  op.env_vol = MAX_ATT_INDEX;
504  op.active = false;
505  }
506  }
507  break;
508  }
509  case EG_DMP: { // damping
510  // TODO improve env_vol update, damp is just fastest decay now
511  byte rate = 56;
512  byte shift = eg_rate_shift[rate];
513  if (!(eg_cnt & ((1 << shift) - 1))) {
514  byte select = eg_rate_select[rate];
515  op.env_vol += eg_inc[select + ((eg_cnt >> shift) & 7)];
516 
517  if (op.env_vol >= MAX_ATT_INDEX) {
518  op.env_vol = MAX_ATT_INDEX;
519  op.active = false;
520  }
521  }
522  break;
523  }
524  case EG_OFF:
525  // nothing
526  break;
527 
528  default:
529  UNREACHABLE;
530  }
531  }
532 }
533 
534 short YMF278::Impl::getSample(YMF278Slot& op)
535 {
536  // TODO How does this behave when R#2 bit 0 = 1?
537  // As-if read returns 0xff? (Like for CPU memory reads.) Or is
538  // sound generation blocked at some higher level?
539  short sample;
540  switch (op.bits) {
541  case 0: {
542  // 8 bit
543  sample = readMem(op.startaddr + op.pos) << 8;
544  break;
545  }
546  case 1: {
547  // 12 bit
548  unsigned addr = op.startaddr + ((op.pos / 2) * 3);
549  if (op.pos & 1) {
550  sample = readMem(addr + 2) << 8 |
551  ((readMem(addr + 1) << 4) & 0xF0);
552  } else {
553  sample = readMem(addr + 0) << 8 |
554  (readMem(addr + 1) & 0xF0);
555  }
556  break;
557  }
558  case 2: {
559  // 16 bit
560  unsigned addr = op.startaddr + (op.pos * 2);
561  sample = (readMem(addr + 0) << 8) |
562  (readMem(addr + 1));
563  break;
564  }
565  default:
566  // TODO unspecified
567  sample = 0;
568  }
569  return sample;
570 }
571 
572 bool YMF278::Impl::anyActive()
573 {
574  for (auto& op : slots) {
575  if (op.active) return true;
576  }
577  return false;
578 }
579 
580 void YMF278::Impl::generateChannels(int** bufs, unsigned num)
581 {
582  if (!anyActive()) {
583  // TODO update internal state, even if muted
584  // TODO also mute individual channels
585  for (int i = 0; i < 24; ++i) {
586  bufs[i] = nullptr;
587  }
588  return;
589  }
590 
591  int vl = mix_level[pcm_l];
592  int vr = mix_level[pcm_r];
593  for (unsigned j = 0; j < num; ++j) {
594  for (int i = 0; i < 24; ++i) {
595  YMF278Slot& sl = slots[i];
596  if (!sl.active) {
597  //bufs[i][2 * j + 0] += 0;
598  //bufs[i][2 * j + 1] += 0;
599  continue;
600  }
601 
602  short sample = (sl.sample1 * (0x10000 - sl.stepptr) +
603  sl.sample2 * sl.stepptr) >> 16;
604  int vol = sl.TL + (sl.env_vol >> 2) + sl.compute_am();
605 
606  int volLeft = vol + pan_left [int(sl.pan)] + vl;
607  int volRight = vol + pan_right[int(sl.pan)] + vr;
608  // TODO prob doesn't happen in real chip
609  volLeft = std::max(0, volLeft);
610  volRight = std::max(0, volRight);
611 
612  bufs[i][2 * j + 0] += (sample * volume[volLeft] ) >> 14;
613  bufs[i][2 * j + 1] += (sample * volume[volRight]) >> 14;
614 
615  unsigned step = (sl.lfo_active && sl.vib)
616  ? calcStep(sl.OCT, sl.FN, sl.compute_vib())
617  : sl.step;
618  sl.stepptr += step;
619 
620  while (sl.stepptr >= 0x10000) {
621  sl.stepptr -= 0x10000;
622  sl.sample1 = sl.sample2;
623  sl.pos++;
624  if (sl.pos >= sl.endaddr) {
625  sl.pos = sl.loopaddr;
626  }
627  sl.sample2 = getSample(sl);
628  }
629  }
630  advance();
631  }
632 }
633 
634 void YMF278::Impl::keyOnHelper(YMF278Slot& slot)
635 {
636  slot.active = true;
637 
638  slot.state = EG_ATT;
639  slot.stepptr = 0;
640  slot.pos = 0;
641  slot.sample1 = getSample(slot);
642  slot.pos = 1;
643  slot.sample2 = getSample(slot);
644 }
645 
647 {
648  updateStream(time); // TODO optimize only for regs that directly influence sound
649  writeRegDirect(reg, data, time);
650 }
651 
652 void YMF278::Impl::writeRegDirect(byte reg, byte data, EmuTime::param time)
653 {
654  // Handle slot registers specifically
655  if (reg >= 0x08 && reg <= 0xF7) {
656  int snum = (reg - 8) % 24;
657  YMF278Slot& slot = slots[snum];
658  switch ((reg - 8) / 24) {
659  case 0: {
660  slot.wave = (slot.wave & 0x100) | data;
661  int wavetblhdr = (regs[2] >> 2) & 0x7;
662  int base = (slot.wave < 384 || !wavetblhdr) ?
663  (slot.wave * 12) :
664  (wavetblhdr * 0x80000 + ((slot.wave - 384) * 12));
665  byte buf[12];
666  for (int i = 0; i < 12; ++i) {
667  // TODO What if R#2 bit 0 = 1?
668  // See also getSample()
669  buf[i] = readMem(base + i);
670  }
671  slot.bits = (buf[0] & 0xC0) >> 6;
672  slot.startaddr = buf[2] | (buf[1] << 8) |
673  ((buf[0] & 0x3F) << 16);
674  slot.loopaddr = buf[4] + (buf[3] << 8);
675  slot.endaddr = (((buf[6] + (buf[5] << 8)) ^ 0xFFFF) + 1);
676  for (int i = 7; i < 12; ++i) {
677  // Verified on real YMF278:
678  // After tone loading, if you read these
679  // registers, their value actually has changed.
680  writeRegDirect(8 + snum + (i - 2) * 24, buf[i], time);
681  }
682  if ((regs[reg + 4] & 0x080)) {
683  keyOnHelper(slot);
684  }
685  break;
686  }
687  case 1: {
688  slot.wave = (slot.wave & 0xFF) | ((data & 0x1) << 8);
689  slot.FN = (slot.FN & 0x380) | (data >> 1);
690  slot.step = calcStep(slot.OCT, slot.FN);
691  break;
692  }
693  case 2: {
694  slot.FN = (slot.FN & 0x07F) | ((data & 0x07) << 7);
695  slot.PRVB = ((data & 0x08) >> 3);
696  slot.OCT = ((data & 0xF0) >> 4);
697  slot.step = calcStep(slot.OCT, slot.FN);
698  break;
699  }
700  case 3:
701  slot.TL = data >> 1;
702  slot.LD = data & 0x1;
703 
704  // TODO
705  if (slot.LD) {
706  // directly change volume
707  } else {
708  // interpolate volume
709  }
710  break;
711  case 4:
712  if (data & 0x10) {
713  // output to DO1 pin:
714  // this pin is not used in moonsound
715  // we emulate this by muting the sound
716  slot.pan = 8; // both left/right -inf dB
717  } else {
718  slot.pan = data & 0x0F;
719  }
720 
721  if (data & 0x020) {
722  // LFO reset
723  slot.lfo_active = false;
724  slot.lfo_cnt = 0;
725  slot.lfo_max = lfo_period[int(slot.vib)];
726  slot.lfo_step = 0;
727  } else {
728  // LFO activate
729  slot.lfo_active = true;
730  }
731 
732  switch (data >> 6) {
733  case 0: // tone off, no damp
734  if (slot.active && (slot.state != EG_REV) ) {
735  slot.state = EG_REL;
736  }
737  break;
738  case 2: // tone on, no damp
739  if (!(regs[reg] & 0x080)) {
740  keyOnHelper(slot);
741  }
742  break;
743  case 1: // tone off, damp
744  case 3: // tone on, damp
745  slot.state = EG_DMP;
746  break;
747  }
748  break;
749  case 5:
750  slot.vib = data & 0x7;
751  slot.set_lfo((data >> 3) & 0x7);
752  break;
753  case 6:
754  slot.AR = data >> 4;
755  slot.D1R = data & 0xF;
756  break;
757  case 7:
758  slot.DL = dl_tab[data >> 4];
759  slot.D2R = data & 0xF;
760  break;
761  case 8:
762  slot.RC = data >> 4;
763  slot.RR = data & 0xF;
764  break;
765  case 9:
766  slot.AM = data & 0x7;
767  break;
768  }
769  } else {
770  // All non-slot registers
771  switch (reg) {
772  case 0x00: // TEST
773  case 0x01:
774  break;
775 
776  case 0x02:
777  // wave-table-header / memory-type / memory-access-mode
778  // Simply store in regs[2]
779  break;
780 
781  case 0x03:
782  // Verified on real YMF278:
783  // * Don't update the 'memadr' variable on writes to
784  // reg 3 and 4. Only store the value in the 'regs'
785  // array for later use.
786  // * The upper 2 bits are not used to address the
787  // external memories (so from a HW pov they don't
788  // matter). But if you read back this register, the
789  // upper 2 bits always read as '0' (even if you wrote
790  // '1'). So we mask the bits here already.
791  data &= 0x3F;
792  break;
793 
794  case 0x04:
795  // See reg 3.
796  break;
797 
798  case 0x05:
799  // Verified on real YMF278: (see above)
800  // Only writes to reg 5 change the (full) 'memadr'.
801  memadr = (regs[3] << 16) | (regs[4] << 8) | data;
802  break;
803 
804  case 0x06: // memory data
805  if (regs[2] & 1) {
806  writeMem(memadr, data);
807  ++memadr; // no need to mask (again) here
808  } else {
809  // Verified on real YMF278:
810  // - writes are ignored
811  // - memadr is NOT increased
812  }
813  break;
814 
815  case 0xF8:
816  // TODO use these
817  fm_l = data & 0x7;
818  fm_r = (data >> 3) & 0x7;
819  break;
820 
821  case 0xF9:
822  pcm_l = data & 0x7;
823  pcm_r = (data >> 3) & 0x7;
824  break;
825  }
826  }
827 
828  regs[reg] = data;
829 }
830 
832 {
833  // no need to call updateStream(time)
834  byte result = peekReg(reg);
835  if (reg == 6) {
836  // Memory Data Register
837  if (regs[2] & 1) {
838  // Verified on real YMF278:
839  // memadr is only increased when 'regs[2] & 1'
840  ++memadr; // no need to mask (again) here
841  }
842  }
843  return result;
844 }
845 
847 {
848  byte result;
849  switch (reg) {
850  case 2: // 3 upper bits are device ID
851  result = (regs[2] & 0x1F) | 0x20;
852  break;
853 
854  case 6: // Memory Data Register
855  if (regs[2] & 1) {
856  result = readMem(memadr);
857  } else {
858  // Verified on real YMF278
859  result = 0xff;
860  }
861  break;
862 
863  default:
864  result = regs[reg];
865  break;
866  }
867  return result;
868 }
869 
870 YMF278::Impl::Impl(YMF278& self, const std::string& name, int ramSize,
871  const DeviceConfig& config)
872  : ResampledSoundDevice(config.getMotherBoard(), name, "MoonSound wave-part",
873  24, true)
874  , motherBoard(config.getMotherBoard())
875  , debugRegisters(make_unique<DebugRegisters>(
876  self, motherBoard, getName()))
877  , debugMemory(make_unique<DebugMemory>(
878  self, motherBoard, getName()))
879  , rom(make_unique<Rom>(name + " ROM", "rom", config))
880  , ram(ramSize * 1024) // in kB
881 {
882  if (rom->getSize() != 0x200000) { // 2MB
883  throw MSXException(
884  "Wrong ROM for MoonSound (YMF278). The ROM (usually "
885  "called yrw801.rom) should have a size of exactly 2MB.");
886  }
887  if ((ramSize != 0) && // - -
888  (ramSize != 128) && // 128kB -
889  (ramSize != 256) && // 128kB 128kB
890  (ramSize != 512) && // 512kB -
891  (ramSize != 640) && // 512kB 128kB
892  (ramSize != 1024) && // 512kB 512kB
893  (ramSize != 2048)) { // 512kB 512kB 512kB 512kB
895  "Wrong sampleram size for MoonSound (YMF278). "
896  "Got " << ramSize << ", but must be one of "
897  "0, 128, 256, 512, 640, 1024 or 2048.");
898  }
899 
900  memadr = 0; // avoid UMR
901 
902  setInputRate(44100);
903 
904  reset(motherBoard.getCurrentTime());
905  registerSound(config);
906 
907  // Volume table, 1 = -0.375dB, 8 = -3dB, 256 = -96dB
908  for (int i = 0; i < 256; ++i) {
909  volume[i] = int(32768.0 * pow(2.0, (-0.375 / 6) * i));
910  }
911  for (int i = 256; i < 256 * 4; ++i) {
912  volume[i] = 0;
913  }
914 }
915 
917 {
918  unregisterSound();
919 }
920 
922 {
923  memset(ram.data(), 0, ram.size());
924 }
925 
927 {
928  updateStream(time);
929 
930  eg_cnt = 0;
931 
932  for (auto& op : slots) {
933  op.reset();
934  }
935  regs[2] = 0; // avoid UMR
936  for (int i = 255; i >= 0; --i) { // reverse order to avoid UMR
937  writeRegDirect(i, 0, time);
938  }
939  memadr = 0;
940  fm_l = fm_r = pcm_l = pcm_r = 0;
941 }
942 
943 // This routine translates an address from the (upper) MoonSound address space
944 // to an address inside the (linearized) SRAM address space.
945 //
946 // The following info is based on measurements on a real MoonSound (v2.0)
947 // PCB. This PCB can have several possible SRAM configurations:
948 // 128kB:
949 // 1 SRAM chip of 128kB, chip enable (/CE) of this SRAM chip is connected to
950 // the 1Y0 output of a 74LS139 (2-to-4 decoder). The enable input of the
951 // 74LS139 is connected to YMF278 pin /MCS6 and the 74LS139 1B:1A inputs are
952 // connected to YMF278 pins MA18:MA17. So the SRAM is selected when /MC6 is
953 // active and MA18:MA17 == 0:0.
954 // 256kB:
955 // 2 SRAM chips of 128kB. First one connected as above. Second one has /CE
956 // connected to 74LS139 pin 1Y1. So SRAM2 is selected when /MSC6 is active
957 // and MA18:MA17 == 0:1.
958 // 512kB:
959 // 1 SRAM chip of 512kB, /CE connected to /MCS6
960 // 640kB:
961 // 1 SRAM chip of 512kB, /CE connected to /MCS6
962 // 1 SRAM chip of 128kB, /CE connected to /MCS7.
963 // (This means SRAM2 is potentially mirrored over a 512kB region)
964 // 1024kB:
965 // 1 SRAM chip of 512kB, /CE connected to /MCS6
966 // 1 SRAM chip of 512kB, /CE connected to /MCS7
967 // 2048kB:
968 // 1 SRAM chip of 512kB, /CE connected to /MCS6
969 // 1 SRAM chip of 512kB, /CE connected to /MCS7
970 // 1 SRAM chip of 512kB, /CE connected to /MCS8
971 // 1 SRAM chip of 512kB, /CE connected to /MCS9
972 // This configuration is not so easy to create on the v2.0 PCB. So it's
973 // very rare.
974 //
975 // So the /MCS6 and /MCS7 (and /MCS8 and /MCS9 in case of 2048kB) signals are
976 // used to select the different SRAM chips. The meaning of these signals
977 // depends on the 'memory access mode'. This mode can be changed at run-time
978 // via bit 1 in register 2. The following table indicates for which regions
979 // these signals are active (normally MoonSound should be used with mode=0):
980 // mode=0 mode=1
981 // /MCS6 0x200000-0x27FFFF 0x380000-0x39FFFF
982 // /MCS7 0x280000-0x2FFFFF 0x3A0000-0x3BFFFF
983 // /MCS8 0x300000-0x37FFFF 0x3C0000-0x3DFFFF
984 // /MCS9 0x380000-0x3FFFFF 0x3E0000-0x3FFFFF
985 //
986 // (For completeness) MoonSound also has 2MB ROM (YRW801), /CE of this ROM is
987 // connected to YMF278 /MCS0. In both mode=0 and mode=1 this signal is active
988 // for the region 0x000000-0x1FFFFF. (But this routine does not handle ROM).
989 unsigned YMF278::Impl::getRamAddress(unsigned addr) const
990 {
991  addr -= 0x200000; // RAM starts at 0x200000
992  if (unlikely(regs[2] & 2)) {
993  // Normally MoonSound is used in 'memory access mode = 0'. But
994  // in the rare case that mode=1 we adjust the address.
995  if ((0x180000 <= addr) && (addr <= 0x1FFFFF)) {
996  addr -= 0x180000;
997  switch (addr & 0x060000) {
998  case 0x000000: // [0x380000-0x39FFFF]
999  // 1st 128kB of SRAM1
1000  break;
1001  case 0x020000: // [0x3A0000-0x3BFFFF]
1002  if (ram.size() == 256*1024) {
1003  // 2nd 128kB SRAM chip
1004  } else {
1005  // 2nd block of 128kB in SRAM2
1006  // In case of 512+128, we use mirroring
1007  addr += 0x080000;
1008  }
1009  break;
1010  case 0x040000: // [0x3C0000-0x3DFFFF]
1011  // 3rd 128kB block in SRAM3
1012  addr += 0x100000;
1013  break;
1014  case 0x060000: // [0x3EFFFF-0x3FFFFF]
1015  // 4th 128kB block in SRAM4
1016  addr += 0x180000;
1017  break;
1018  }
1019  } else {
1020  addr = unsigned(-1); // unmapped
1021  }
1022  }
1023  if (ram.size() == 640*1024) {
1024  // Verified on real MoonSound cartridge (v2.0): In case of
1025  // 640kB (1x512kB + 1x128kB), the 128kB SRAM chip is 4 times
1026  // visible. None of the other SRAM configurations show similar
1027  // mirroring (because the others are powers of two).
1028  if (addr > 0x080000) {
1029  addr &= ~0x060000;
1030  }
1031  }
1032  return addr;
1033 }
1034 
1035 byte YMF278::Impl::readMem(unsigned address) const
1036 {
1037  // Verified on real YMF278: address space wraps at 4MB.
1038  address &= 0x3FFFFF;
1039  if (address < 0x200000) {
1040  // ROM connected to /MCS0
1041  return (*rom)[address];
1042  } else {
1043  unsigned ramAddr = getRamAddress(address);
1044  if (ramAddr < ram.size()) {
1045  return ram[ramAddr];
1046  } else {
1047  // unmapped region
1048  return 255; // TODO check
1049  }
1050  }
1051 }
1052 
1053 void YMF278::Impl::writeMem(unsigned address, byte value)
1054 {
1055  address &= 0x3FFFFF;
1056  if (address < 0x200000) {
1057  // can't write to ROM
1058  } else {
1059  unsigned ramAddr = getRamAddress(address);
1060  if (ramAddr < ram.size()) {
1061  ram[ramAddr] = value;
1062  } else {
1063  // can't write to unmapped memory
1064  }
1065  }
1066 }
1067 
1068 // version 1: initial version, some variables were saved as char
1069 // version 2: serialization framework was fixed to save/load chars as numbers
1070 // but for backwards compatibility we still load old savestates as
1071 // characters
1072 // version 3: 'step' is no longer stored (it is recalculated)
1073 template<typename Archive>
1074 void YMF278Slot::serialize(Archive& ar, unsigned version)
1075 {
1076  // TODO restore more state from registers
1077  ar.serialize("startaddr", startaddr);
1078  ar.serialize("loopaddr", loopaddr);
1079  ar.serialize("endaddr", endaddr);
1080  ar.serialize("stepptr", stepptr);
1081  ar.serialize("pos", pos);
1082  ar.serialize("sample1", sample1);
1083  ar.serialize("sample2", sample2);
1084  ar.serialize("env_vol", env_vol);
1085  ar.serialize("lfo_cnt", lfo_cnt);
1086  ar.serialize("lfo_step", lfo_step);
1087  ar.serialize("lfo_max", lfo_max);
1088  ar.serialize("DL", DL);
1089  ar.serialize("wave", wave);
1090  ar.serialize("FN", FN);
1091  if (ar.versionAtLeast(version, 2)) {
1092  ar.serialize("OCT", OCT);
1093  ar.serialize("PRVB", PRVB);
1094  ar.serialize("LD", LD);
1095  ar.serialize("TL", TL);
1096  ar.serialize("pan", pan);
1097  ar.serialize("lfo", lfo);
1098  ar.serialize("vib", vib);
1099  ar.serialize("AM", AM);
1100  ar.serialize("AR", AR);
1101  ar.serialize("D1R", D1R);
1102  ar.serialize("D2R", D2R);
1103  ar.serialize("RC", RC);
1104  ar.serialize("RR", RR);
1105  } else {
1106  ar.serializeChar("OCT", OCT);
1107  ar.serializeChar("PRVB", PRVB);
1108  ar.serializeChar("LD", LD);
1109  ar.serializeChar("TL", TL);
1110  ar.serializeChar("pan", pan);
1111  ar.serializeChar("lfo", lfo);
1112  ar.serializeChar("vib", vib);
1113  ar.serializeChar("AM", AM);
1114  ar.serializeChar("AR", AR);
1115  ar.serializeChar("D1R", D1R);
1116  ar.serializeChar("D2R", D2R);
1117  ar.serializeChar("RC", RC);
1118  ar.serializeChar("RR", RR);
1119  }
1120  ar.serialize("bits", bits);
1121  ar.serialize("active", active);
1122  ar.serialize("state", state);
1123  ar.serialize("lfo_active", lfo_active);
1124 
1125  // Recalculate redundant state
1126  if (ar.isLoader()) {
1127  step = calcStep(OCT, FN);
1128  }
1129 
1130  // This old comment is NOT completely true:
1131  // Older version also had "env_vol_step" and "env_vol_lim" but those
1132  // members were nowhere used, so removed those in the current
1133  // version (it's ok to remove members from the savestate without
1134  // updating the version number).
1135  // When you remove member variables without increasing the version
1136  // number, new openMSX executables can still read old savestates. And
1137  // if you try to load a new savestate in an old openMSX version you do
1138  // get a (cryptic) error message. But if the version number is
1139  // increased the error message is much clearer.
1140 }
1141 
1142 // version 1: initial version
1143 // version 2: loadTime and busyTime moved to MSXMoonSound class
1144 // version 3: memadr cannot be restored from register values
1145 template<typename Archive>
1146 void YMF278::Impl::serialize(Archive& ar, unsigned version)
1147 {
1148  ar.serialize("slots", slots);
1149  ar.serialize("eg_cnt", eg_cnt);
1150  ar.serialize_blob("ram", ram.data(), ram.size());
1151  ar.serialize_blob("registers", regs, sizeof(regs));
1152  if (ar.versionAtLeast(version, 3)) { // must come after 'regs'
1153  ar.serialize("memadr", memadr);
1154  } else {
1155  assert(ar.isLoader());
1156  // Old formats didn't store 'memadr' so we also can't magically
1157  // restore the correct value. The best we can do is restore the
1158  // last set address.
1159  regs[3] &= 0x3F; // mask upper two bits
1160  memadr = (regs[3] << 16) | (regs[4] << 8) | regs[5];
1161  }
1162 
1163  // TODO restore more state from registers
1164  static const byte rewriteRegs[] = {
1165  0xf8, // fm_l, fm_r
1166  0xf9, // pcm_l, pcm_r
1167  };
1168  if (ar.isLoader()) {
1169  EmuTime::param time = motherBoard.getCurrentTime();
1170  for (auto r : rewriteRegs) {
1171  writeRegDirect(r, regs[r], time);
1172  }
1173  }
1174 }
1175 
1176 
1177 // class DebugRegisters
1178 
1180  const std::string& name)
1181  : SimpleDebuggable(motherBoard, name + " regs",
1182  "OPL4 registers", 0x100)
1183  , ymf278(ymf278_)
1184 {
1185 }
1186 
1187 byte DebugRegisters::read(unsigned address)
1188 {
1189  return ymf278.peekReg(address);
1190 }
1191 
1192 void DebugRegisters::write(unsigned address, byte value, EmuTime::param time)
1193 {
1194  ymf278.writeReg(address, value, time);
1195 }
1196 
1197 
1198 // class DebugMemory
1199 
1201  const std::string& name)
1202  : SimpleDebuggable(motherBoard, name + " mem",
1203  "OPL4 memory (includes both ROM and RAM)", 0x400000) // 4MB
1204  , ymf278(ymf278_)
1205 {
1206 }
1207 
1208 byte DebugMemory::read(unsigned address)
1209 {
1210  return ymf278.readMem(address);
1211 }
1212 
1213 void DebugMemory::write(unsigned address, byte value)
1214 {
1215  ymf278.writeMem(address, value);
1216 }
1217 
1218 
1219 // class YMF278
1220 
1221 YMF278::YMF278(const std::string& name, int ramSize, const DeviceConfig& config)
1222  : pimpl(make_unique<Impl>(*this, name, ramSize, config))
1223 {
1224 }
1225 
1227 {
1228 }
1229 
1231 {
1232  pimpl->clearRam();
1233 }
1234 
1236 {
1237  pimpl->reset(time);
1238 }
1239 
1241 {
1242  pimpl->writeReg(reg, data, time);
1243 }
1244 
1246 {
1247  return pimpl->readReg(reg);
1248 }
1249 
1251 {
1252  return pimpl->peekReg(reg);
1253 }
1254 
1255 byte YMF278::readMem(unsigned address) const
1256 {
1257  return pimpl->readMem(address);
1258 }
1259 
1260 void YMF278::writeMem(unsigned address, byte value)
1261 {
1262  pimpl->writeMem(address, value);
1263 }
1264 
1265 template<typename Archive>
1266 void YMF278::serialize(Archive& ar, unsigned version)
1267 {
1268  pimpl->serialize(ar, version);
1269 }
1271 
1272 } // namespace openmsx
void clearRam()
Definition: YMF278.cc:1230
void writeMem(unsigned address, byte value)
Definition: YMF278.cc:1053
byte readMem(unsigned address) const
Definition: YMF278.cc:1255
void serialize(Archive &ar, unsigned version)
Definition: YMF278.cc:1146
byte readReg(byte reg)
Definition: YMF278.cc:1245
#define unlikely(x)
Definition: likely.hh:15
unsigned endaddr
Definition: YMF278.cc:66
unsigned char byte
8 bit unsigned integer
Definition: openmsx.hh:33
void serialize(Archive &ar, unsigned version)
Definition: YMF278.cc:1074
void write(unsigned address, byte value) override
Definition: YMF278.cc:1213
DebugRegisters(YMF278 &ymf278, MSXMotherBoard &motherBoard, const std::string &name)
Definition: YMF278.cc:1179
int compute_am() const
Definition: YMF278.cc:370
void reset(EmuTime::param time)
Definition: YMF278.cc:926
void writeReg(byte reg, byte data, EmuTime::param time)
Definition: YMF278.cc:1240
unsigned loopaddr
Definition: YMF278.cc:65
void writeMem(unsigned address, byte value)
Definition: YMF278.cc:1260
byte readReg(byte reg)
Definition: YMF278.cc:831
int compute_rate(int val) const
Definition: YMF278.cc:341
unsigned step
Definition: YMF278.cc:67
byte readMem(unsigned address) const
Definition: YMF278.cc:1035
void advance(octet_iterator &it, distance_type n, octet_iterator end)
unsigned decay_rate(int num, int sample_rate)
void set_lfo(int newlfo)
Definition: YMF278.cc:379
void serialize(Archive &ar, unsigned version)
Definition: YMF278.cc:1266
SERIALIZE_CLASS_VERSION(CassettePlayer, 2)
void setInputRate(unsigned sampleRate)
Definition: SoundDevice.hh:79
DebugMemory(YMF278 &ymf278, MSXMotherBoard &motherBoard, const std::string &name)
Definition: YMF278.cc:1200
unsigned stepptr
Definition: YMF278.cc:69
byte read(unsigned address) override
Definition: YMF278.cc:1208
void writeReg(byte reg, byte data, EmuTime::param time)
Definition: YMF278.cc:646
#define O(a)
Definition: YMF278.cc:280
unsigned startaddr
Definition: YMF278.cc:64
byte peekReg(byte reg) const
Definition: YMF278.cc:1250
byte peekReg(byte reg) const
Definition: YMF278.cc:846
byte read(unsigned address) override
Definition: YMF278.cc:1187
#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:1221
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
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:1235
Impl(YMF278 &self, const std::string &name, int ramSize, const DeviceConfig &config)
Definition: YMF278.cc:870
#define SC(db)
Definition: YMF278.cc:288
void registerSound(const DeviceConfig &config)
Registers this sound device with the Mixer.
Definition: SoundDevice.cc:81
#define UNREACHABLE
Definition: unreachable.hh:56
void write(unsigned address, byte value, EmuTime::param time) override
Definition: YMF278.cc:1192