openMSX
YMF262.cc
Go to the documentation of this file.
1 /*
2  *
3  * File: ymf262.c - software implementation of YMF262
4  * FM sound generator type OPL3
5  *
6  * Copyright (C) 2003 Jarek Burczynski
7  *
8  * Version 0.2
9  *
10  *
11  * Revision History:
12  *
13  * 03-03-2003: initial release
14  * - thanks to Olivier Galibert and Chris Hardy for YMF262 and YAC512 chips
15  * - thanks to Stiletto for the datasheets
16  *
17  *
18  *
19  * differences between OPL2 and OPL3 not documented in Yamaha datahasheets:
20  * - sinus table is a little different: the negative part is off by one...
21  *
22  * - in order to enable selection of four different waveforms on OPL2
23  * one must set bit 5 in register 0x01(test).
24  * on OPL3 this bit is ignored and 4-waveform select works *always*.
25  * (Don't confuse this with OPL3's 8-waveform select.)
26  *
27  * - Envelope Generator: all 15 x rates take zero time on OPL3
28  * (on OPL2 15 0 and 15 1 rates take some time while 15 2 and 15 3 rates
29  * take zero time)
30  *
31  * - channel calculations: output of operator 1 is in perfect sync with
32  * output of operator 2 on OPL3; on OPL and OPL2 output of operator 1
33  * is always delayed by one sample compared to output of operator 2
34  *
35  *
36  * differences between OPL2 and OPL3 shown in datasheets:
37  * - YMF262 does not support CSM mode
38  */
39 
40 #include "YMF262.hh"
41 #include "ResampledSoundDevice.hh"
42 #include "EmuTimer.hh"
43 #include "IRQHelper.hh"
44 #include "FixedPoint.hh"
45 #include "SimpleDebuggable.hh"
46 #include "DeviceConfig.hh"
47 #include "MSXMotherBoard.hh"
48 #include "serialize.hh"
49 #include "memory.hh"
50 #include <cmath>
51 #include <cstring>
52 
53 namespace openmsx {
54 
56 {
57 public:
58  YMF262Debuggable(MSXMotherBoard& motherBoard, YMF262& ymf262,
59  const std::string& name);
60  virtual byte read(unsigned address);
61  virtual void write(unsigned address, byte value, EmuTime::param time);
62 private:
63  YMF262& ymf262;
64 };
65 
66 
69 };
70 
72 
76 
77 static inline FreqIndex fnumToIncrement(unsigned block_fnum)
78 {
79  // opn phase increment counter = 20bit
80  // chip works with 10.10 fixed point, while we use 16.16
81  unsigned block = (block_fnum & 0x1C00) >> 10;
82  return FreqIndex(block_fnum & 0x03FF) >> (11 - block);
83 }
84 
86 {
87 public:
88  YMF262Slot();
89  inline int op_calc(unsigned phase, unsigned lfo_am) const;
90  inline void FM_KEYON(byte key_set);
91  inline void FM_KEYOFF(byte key_clr);
92  inline void advanceEnvelopeGenerator(unsigned eg_cnt);
93  inline void advancePhaseGenerator(YMF262Channel& ch, unsigned lfo_pm);
94  void update_ar_dr();
95  void update_rr();
96  void calc_fc(const YMF262Channel& ch);
97 
100  void setFeedbackShift(byte value) {
101  fb_shift = value ? 9 - value : 0;
102  }
103 
104  template<typename Archive>
105  void serialize(Archive& ar, unsigned version);
106 
107  // Phase Generator
108  FreqIndex Cnt; // frequency counter
109  FreqIndex Incr; // frequency counter step
110  int* connect; // slot output pointer
111  int op1_out[2]; // slot1 output for feedback
112 
113  // Envelope Generator
114  unsigned TL; // total level: TL << 2
115  int TLL; // adjusted now TL
116  int volume; // envelope counter
117  int sl; // sustain level: sl_tab[SL]
118 
119  unsigned* wavetable; // waveform select
120 
121  EnvelopeState state; // EG: phase type
122  unsigned eg_m_ar;// (attack state)
123  unsigned eg_m_dr;// (decay state)
124  unsigned eg_m_rr;// (release state)
125  byte eg_sh_ar; // (attack state)
126  byte eg_sel_ar; // (attack state)
127  byte eg_sh_dr; // (decay state)
128  byte eg_sel_dr; // (decay state)
129  byte eg_sh_rr; // (release state)
130  byte eg_sel_rr; // (release state)
131 
132  byte key; // 0 = KEY OFF, >0 = KEY ON
133 
134  byte fb_shift; // PG: feedback shift value
135  bool CON; // PG: connection (algorithm) type
136  bool eg_type; // EG: percussive/non-percussive mode
137 
138  // LFO
139  byte AMmask; // LFO Amplitude Modulation enable mask
140  bool vib; // LFO Phase Modulation enable flag (active high)
141 
142  byte ar; // attack rate: AR<<2
143  byte dr; // decay rate: DR<<2
144  byte rr; // release rate:RR<<2
145  byte KSR; // key scale rate
146  byte ksl; // keyscale level
147  byte ksr; // key scale rate: kcode>>KSR
148  byte mul; // multiple: mul_tab[ML]
149 };
150 
152 {
153 public:
154  YMF262Channel();
155  void chan_calc(unsigned lfo_am);
156  void chan_calc_ext(unsigned lfo_am);
157 
158  template<typename Archive>
159  void serialize(Archive& ar, unsigned version);
160 
162 
163  int block_fnum; // block+fnum
164  FreqIndex fc; // Freq. Increment base
165  int ksl_base; // KeyScaleLevel Base step
166  byte kcode; // key code (for key scaling)
167 
168  // there are 12 2-operator channels which can be combined in pairs
169  // to form six 4-operator channel, they are:
170  // 0 and 3,
171  // 1 and 4,
172  // 2 and 5,
173  // 9 and 12,
174  // 10 and 13,
175  // 11 and 14
176  bool extended; // set if this channel forms up a 4op channel with
177  // another channel (only used by first of pair of
178  // channels, ie 0,1,2 and 9,10,11)
179 };
180 
182 {
183 public:
184  Impl(YMF262& self, const std::string& name, const DeviceConfig& config,
185  bool isYMF278);
186  virtual ~Impl();
187 
188  void reset(EmuTime::param time);
189  void writeReg (unsigned r, byte v, EmuTime::param time);
190  void writeReg512(unsigned r, byte v, EmuTime::param time);
191  byte readReg(unsigned reg);
192  byte peekReg(unsigned reg) const;
193  byte readStatus();
194  byte peekStatus() const;
195 
196  template<typename Archive>
197  void serialize(Archive& ar, unsigned version);
198 
199 private:
200  // SoundDevice
201  virtual int getAmplificationFactor() const;
202  virtual void generateChannels(int** bufs, unsigned num);
203 
204  void callback(byte flag);
205 
206  void writeRegDirect(unsigned r, byte v, EmuTime::param time);
207  void init_tables();
208  void setStatus(byte flag);
209  void resetStatus(byte flag);
210  void changeStatusMask(byte flag);
211  void advance();
212 
213  inline int genPhaseHighHat();
214  inline int genPhaseSnare();
215  inline int genPhaseCymbal();
216 
217  void chan_calc_rhythm(unsigned lfo_am);
218  void set_mul(unsigned sl, byte v);
219  void set_ksl_tl(unsigned sl, byte v);
220  void set_ar_dr(unsigned sl, byte v);
221  void set_sl_rr(unsigned sl, byte v);
222  bool checkMuteHelper();
223 
224  inline bool isExtended(unsigned ch) const;
225  inline YMF262Channel& getFirstOfPair(unsigned ch);
226  inline YMF262Channel& getSecondOfPair(unsigned ch);
227 
228  const std::unique_ptr<YMF262Debuggable> debuggable;
229 
230  // Bitmask for register 0x04
231  static const int R04_ST1 = 0x01; // Timer1 Start
232  static const int R04_ST2 = 0x02; // Timer2 Start
233  static const int R04_MASK_T2 = 0x20; // Mask Timer2 flag
234  static const int R04_MASK_T1 = 0x40; // Mask Timer1 flag
235  static const int R04_IRQ_RESET = 0x80; // IRQ RESET
236 
237  // Bitmask for status register
238  static const int STATUS_T2 = R04_MASK_T2;
239  static const int STATUS_T1 = R04_MASK_T1;
240  // Timers (see EmuTimer class for details about timing)
241  const std::unique_ptr<EmuTimer> timer1; // 80.8us OPL4 ( 80.5us OPL3)
242  const std::unique_ptr<EmuTimer> timer2; // 323.1us OPL4 (321.8us OPL3)
243 
244  IRQHelper irq;
245 
246  int chanout[18]; // 18 channels
247 
248  byte reg[512];
249  YMF262Channel channel[18]; // OPL3 chips have 18 channels
250 
251  unsigned pan[18 * 4]; // channels output masks 4 per channel
252  // 0xffffffff = enable
253  unsigned eg_cnt; // global envelope generator counter
254  unsigned noise_rng; // 23 bit noise shift register
255 
256  // LFO
257  typedef FixedPoint< 6> LFOAMIndex;
258  typedef FixedPoint<10> LFOPMIndex;
259  LFOAMIndex lfo_am_cnt;
260  LFOPMIndex lfo_pm_cnt;
261  bool lfo_am_depth;
262  byte lfo_pm_depth_range;
263 
264  byte rhythm; // Rhythm mode
265  bool nts; // NTS (note select)
266  bool OPL3_mode; // OPL3 extension enable flag
267 
268  byte status; // status flag
269  byte status2;
270  byte statusMask; // status mask
271 
272  bool alreadySignaledNEW2;
273  const bool isYMF278; // true iff this is actually a YMF278
274  // ATM only used for NEW2 bit
275 };
276 
277 
278 // envelope output entries
279 static const int ENV_BITS = 10;
280 static const int ENV_LEN = 1 << ENV_BITS;
281 static const double ENV_STEP = 128.0 / ENV_LEN;
282 
283 static const int MAX_ATT_INDEX = (1 << (ENV_BITS - 1)) - 1; // 511
284 static const int MIN_ATT_INDEX = 0;
285 
286 // sinwave entries
287 static const int SIN_BITS = 10;
288 static const int SIN_LEN = 1 << SIN_BITS;
289 static const int SIN_MASK = SIN_LEN - 1;
290 
291 static const int TL_RES_LEN = 256; // 8 bits addressing (real chip)
292 
293 // register number to channel number , slot offset
294 static const byte MOD = 0;
295 static const byte CAR = 1;
296 
297 
298 // mapping of register number (offset) to slot number used by the emulator
299 static const int slot_array[32] = {
300  0, 2, 4, 1, 3, 5, -1, -1,
301  6, 8, 10, 7, 9, 11, -1, -1,
302  12, 14, 16, 13, 15, 17, -1, -1,
303  -1, -1, -1, -1, -1, -1, -1, -1
304 };
305 
306 
307 // key scale level
308 // table is 3dB/octave , DV converts this into 6dB/octave
309 // 0.1875 is bit 0 weight of the envelope counter (volume) expressed
310 // in the 'decibel' scale
311 #define DV(x) int(x / (0.1875 / 2.0))
312 static const unsigned ksl_tab[8 * 16] = {
313  // OCT 0
314  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
315  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
316  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
317  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
318  // OCT 1
319  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
320  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
321  DV( 0.000), DV( 0.750), DV( 1.125), DV( 1.500),
322  DV( 1.875), DV( 2.250), DV( 2.625), DV( 3.000),
323  // OCT 2
324  DV( 0.000), DV( 0.000), DV( 0.000), DV( 0.000),
325  DV( 0.000), DV( 1.125), DV( 1.875), DV( 2.625),
326  DV( 3.000), DV( 3.750), DV( 4.125), DV( 4.500),
327  DV( 4.875), DV( 5.250), DV( 5.625), DV( 6.000),
328  // OCT 3
329  DV( 0.000), DV( 0.000), DV( 0.000), DV( 1.875),
330  DV( 3.000), DV( 4.125), DV( 4.875), DV( 5.625),
331  DV( 6.000), DV( 6.750), DV( 7.125), DV( 7.500),
332  DV( 7.875), DV( 8.250), DV( 8.625), DV( 9.000),
333  // OCT 4
334  DV( 0.000), DV( 0.000), DV( 3.000), DV( 4.875),
335  DV( 6.000), DV( 7.125), DV( 7.875), DV( 8.625),
336  DV( 9.000), DV( 9.750), DV(10.125), DV(10.500),
337  DV(10.875), DV(11.250), DV(11.625), DV(12.000),
338  // OCT 5
339  DV( 0.000), DV( 3.000), DV( 6.000), DV( 7.875),
340  DV( 9.000), DV(10.125), DV(10.875), DV(11.625),
341  DV(12.000), DV(12.750), DV(13.125), DV(13.500),
342  DV(13.875), DV(14.250), DV(14.625), DV(15.000),
343  // OCT 6
344  DV( 0.000), DV( 6.000), DV( 9.000), DV(10.875),
345  DV(12.000), DV(13.125), DV(13.875), DV(14.625),
346  DV(15.000), DV(15.750), DV(16.125), DV(16.500),
347  DV(16.875), DV(17.250), DV(17.625), DV(18.000),
348  // OCT 7
349  DV( 0.000), DV( 9.000), DV(12.000), DV(13.875),
350  DV(15.000), DV(16.125), DV(16.875), DV(17.625),
351  DV(18.000), DV(18.750), DV(19.125), DV(19.500),
352  DV(19.875), DV(20.250), DV(20.625), DV(21.000)
353 };
354 #undef DV
355 
356 // sustain level table (3dB per step)
357 // 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,93 (dB)
358 #define SC(db) unsigned(db * (2.0 / ENV_STEP))
359 static const unsigned sl_tab[16] = {
360  SC( 0), SC( 1), SC( 2), SC(3 ), SC(4 ), SC(5 ), SC(6 ), SC( 7),
361  SC( 8), SC( 9), SC(10), SC(11), SC(12), SC(13), SC(14), SC(31)
362 };
363 #undef SC
364 
365 
366 static const byte RATE_STEPS = 8;
367 static const byte eg_inc[15 * RATE_STEPS] = {
368 //cycle:0 1 2 3 4 5 6 7
369  0,1, 0,1, 0,1, 0,1, // 0 rates 00..12 0 (increment by 0 or 1)
370  0,1, 0,1, 1,1, 0,1, // 1 rates 00..12 1
371  0,1, 1,1, 0,1, 1,1, // 2 rates 00..12 2
372  0,1, 1,1, 1,1, 1,1, // 3 rates 00..12 3
373 
374  1,1, 1,1, 1,1, 1,1, // 4 rate 13 0 (increment by 1)
375  1,1, 1,2, 1,1, 1,2, // 5 rate 13 1
376  1,2, 1,2, 1,2, 1,2, // 6 rate 13 2
377  1,2, 2,2, 1,2, 2,2, // 7 rate 13 3
378 
379  2,2, 2,2, 2,2, 2,2, // 8 rate 14 0 (increment by 2)
380  2,2, 2,4, 2,2, 2,4, // 9 rate 14 1
381  2,4, 2,4, 2,4, 2,4, // 10 rate 14 2
382  2,4, 4,4, 2,4, 4,4, // 11 rate 14 3
383 
384  4,4, 4,4, 4,4, 4,4, // 12 rates 15 0, 15 1, 15 2, 15 3 for decay
385  8,8, 8,8, 8,8, 8,8, // 13 rates 15 0, 15 1, 15 2, 15 3 for attack (zero time)
386  0,0, 0,0, 0,0, 0,0, // 14 infinity rates for attack and decay(s)
387 };
388 
389 
390 #define O(a) (a * RATE_STEPS)
391 // note that there is no O(13) in this table - it's directly in the code
392 static const byte eg_rate_select[16 + 64 + 16] = {
393  // Envelope Generator rates (16 + 64 rates + 16 RKS)
394  // 16 infinite time rates
395  O(14), O(14), O(14), O(14), O(14), O(14), O(14), O(14),
396  O(14), O(14), O(14), O(14), O(14), O(14), O(14), O(14),
397 
398  // rates 00-12
399  O( 0), O( 1), O( 2), O( 3),
400  O( 0), O( 1), O( 2), O( 3),
401  O( 0), O( 1), O( 2), O( 3),
402  O( 0), O( 1), O( 2), O( 3),
403  O( 0), O( 1), O( 2), O( 3),
404  O( 0), O( 1), O( 2), O( 3),
405  O( 0), O( 1), O( 2), O( 3),
406  O( 0), O( 1), O( 2), O( 3),
407  O( 0), O( 1), O( 2), O( 3),
408  O( 0), O( 1), O( 2), O( 3),
409  O( 0), O( 1), O( 2), O( 3),
410  O( 0), O( 1), O( 2), O( 3),
411  O( 0), O( 1), O( 2), O( 3),
412 
413  // rate 13
414  O( 4), O( 5), O( 6), O( 7),
415 
416  // rate 14
417  O( 8), O( 9), O(10), O(11),
418 
419  // rate 15
420  O(12), O(12), O(12), O(12),
421 
422  // 16 dummy rates (same as 15 3)
423  O(12), O(12), O(12), O(12), O(12), O(12), O(12), O(12),
424  O(12), O(12), O(12), O(12), O(12), O(12), O(12), O(12),
425 };
426 #undef O
427 
428 // rate 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
429 // shift 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0
430 // mask 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1, 0, 0, 0, 0
431 #define O(a) (a * 1)
432 static const byte eg_rate_shift[16 + 64 + 16] =
433 {
434  // Envelope Generator counter shifts (16 + 64 rates + 16 RKS)
435  // 16 infinite time rates
436  O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0),
437  O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0),
438 
439  // rates 00-15
440  O(12), O(12), O(12), O(12),
441  O(11), O(11), O(11), O(11),
442  O(10), O(10), O(10), O(10),
443  O( 9), O( 9), O( 9), O( 9),
444  O( 8), O( 8), O( 8), O( 8),
445  O( 7), O( 7), O( 7), O( 7),
446  O( 6), O( 6), O( 6), O( 6),
447  O( 5), O( 5), O( 5), O( 5),
448  O( 4), O( 4), O( 4), O( 4),
449  O( 3), O( 3), O( 3), O( 3),
450  O( 2), O( 2), O( 2), O( 2),
451  O( 1), O( 1), O( 1), O( 1),
452  O( 0), O( 0), O( 0), O( 0),
453  O( 0), O( 0), O( 0), O( 0),
454  O( 0), O( 0), O( 0), O( 0),
455  O( 0), O( 0), O( 0), O( 0),
456 
457  // 16 dummy rates (same as 15 3)
458  O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0),
459  O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0), O( 0),
460 };
461 #undef O
462 
463 
464 // multiple table
465 #define ML(x) byte(2 * x)
466 static const byte mul_tab[16] = {
467  // 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,10,12,12,15,15
468  ML( 0.5), ML( 1.0), ML( 2.0), ML( 3.0),
469  ML( 4.0), ML( 5.0), ML( 6.0), ML( 7.0),
470  ML( 8.0), ML( 9.0), ML(10.0), ML(10.0),
471  ML(12.0), ML(12.0), ML(15.0), ML(15.0)
472 };
473 #undef ML
474 
475 // TL_TAB_LEN is calculated as:
476 // (12+1)=13 - sinus amplitude bits (Y axis)
477 // additional 1: to compensate for calculations of negative part of waveform
478 // (if we don't add it then the greatest possible _negative_ value would be -2
479 // and we really need -1 for waveform #7)
480 // 2 - sinus sign bit (Y axis)
481 // TL_RES_LEN - sinus resolution (X axis)
482 
483 static const int TL_TAB_LEN = 13 * 2 * TL_RES_LEN;
484 static int tl_tab[TL_TAB_LEN];
485 static const int ENV_QUIET = TL_TAB_LEN >> 4;
486 
487 // sin waveform table in 'decibel' scale
488 // there are eight waveforms on OPL3 chips
489 static unsigned sin_tab[SIN_LEN * 8];
490 
491 // LFO Amplitude Modulation table (verified on real YM3812)
492 // 27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples
493 //
494 // Length: 210 elements
495 //
496 // Each of the elements has to be repeated
497 // exactly 64 times (on 64 consecutive samples).
498 // The whole table takes: 64 * 210 = 13440 samples.
499 //
500 // When AM = 1 data is used directly
501 // When AM = 0 data is divided by 4 before being used (loosing precision is important)
502 
503 static const unsigned LFO_AM_TAB_ELEMENTS = 210;
504 static const byte lfo_am_table[LFO_AM_TAB_ELEMENTS] = {
505  0, 0, 0,
506  0, 0, 0, 0,
507  1, 1, 1, 1,
508  2, 2, 2, 2,
509  3, 3, 3, 3,
510  4, 4, 4, 4,
511  5, 5, 5, 5,
512  6, 6, 6, 6,
513  7, 7, 7, 7,
514  8, 8, 8, 8,
515  9, 9, 9, 9,
516  10, 10, 10, 10,
517  11, 11, 11, 11,
518  12, 12, 12, 12,
519  13, 13, 13, 13,
520  14, 14, 14, 14,
521  15, 15, 15, 15,
522  16, 16, 16, 16,
523  17, 17, 17, 17,
524  18, 18, 18, 18,
525  19, 19, 19, 19,
526  20, 20, 20, 20,
527  21, 21, 21, 21,
528  22, 22, 22, 22,
529  23, 23, 23, 23,
530  24, 24, 24, 24,
531  25, 25, 25, 25,
532  26, 26, 26,
533  25, 25, 25, 25,
534  24, 24, 24, 24,
535  23, 23, 23, 23,
536  22, 22, 22, 22,
537  21, 21, 21, 21,
538  20, 20, 20, 20,
539  19, 19, 19, 19,
540  18, 18, 18, 18,
541  17, 17, 17, 17,
542  16, 16, 16, 16,
543  15, 15, 15, 15,
544  14, 14, 14, 14,
545  13, 13, 13, 13,
546  12, 12, 12, 12,
547  11, 11, 11, 11,
548  10, 10, 10, 10,
549  9, 9, 9, 9,
550  8, 8, 8, 8,
551  7, 7, 7, 7,
552  6, 6, 6, 6,
553  5, 5, 5, 5,
554  4, 4, 4, 4,
555  3, 3, 3, 3,
556  2, 2, 2, 2,
557  1, 1, 1, 1
558 };
559 
560 // LFO Phase Modulation table (verified on real YM3812)
561 static const signed char lfo_pm_table[8 * 8 * 2] = {
562  // FNUM2/FNUM = 00 0xxxxxxx (0x0000)
563  0, 0, 0, 0, 0, 0, 0, 0, // LFO PM depth = 0
564  0, 0, 0, 0, 0, 0, 0, 0, // LFO PM depth = 1
565 
566  // FNUM2/FNUM = 00 1xxxxxxx (0x0080)
567  0, 0, 0, 0, 0, 0, 0, 0, // LFO PM depth = 0
568  1, 0, 0, 0,-1, 0, 0, 0, // LFO PM depth = 1
569 
570  // FNUM2/FNUM = 01 0xxxxxxx (0x0100)
571  1, 0, 0, 0,-1, 0, 0, 0, // LFO PM depth = 0
572  2, 1, 0,-1,-2,-1, 0, 1, // LFO PM depth = 1
573 
574  // FNUM2/FNUM = 01 1xxxxxxx (0x0180)
575  1, 0, 0, 0,-1, 0, 0, 0, // LFO PM depth = 0
576  3, 1, 0,-1,-3,-1, 0, 1, // LFO PM depth = 1
577 
578  // FNUM2/FNUM = 10 0xxxxxxx (0x0200)
579  2, 1, 0,-1,-2,-1, 0, 1, // LFO PM depth = 0
580  4, 2, 0,-2,-4,-2, 0, 2, // LFO PM depth = 1
581 
582  // FNUM2/FNUM = 10 1xxxxxxx (0x0280)
583  2, 1, 0,-1,-2,-1, 0, 1, // LFO PM depth = 0
584  5, 2, 0,-2,-5,-2, 0, 2, // LFO PM depth = 1
585 
586  // FNUM2/FNUM = 11 0xxxxxxx (0x0300)
587  3, 1, 0,-1,-3,-1, 0, 1, // LFO PM depth = 0
588  6, 3, 0,-3,-6,-3, 0, 3, // LFO PM depth = 1
589 
590  // FNUM2/FNUM = 11 1xxxxxxx (0x0380)
591  3, 1, 0,-1,-3,-1, 0, 1, // LFO PM depth = 0
592  7, 3, 0,-3,-7,-3, 0, 3 // LFO PM depth = 1
593 };
594 
595 // TODO clean this up
596 static int phase_modulation; // phase modulation input (SLOT 2)
597 static int phase_modulation2; // phase modulation input (SLOT 3
598  // in 4 operator channels)
599 
600 
602  : Cnt(0), Incr(0)
603 {
604  ar = dr = rr = KSR = ksl = ksr = mul = 0;
605  fb_shift = op1_out[0] = op1_out[1] = 0;
606  CON = eg_type = vib = false;
607  connect = nullptr;
608  TL = TLL = volume = sl = 0;
609  state = EG_OFF;
612  key = AMmask = 0;
613  wavetable = &sin_tab[0 * SIN_LEN];
614 }
615 
617 {
618  block_fnum = ksl_base = kcode = 0;
619  extended = false;
620  fc = FreqIndex(0);
621 }
622 
623 
624 void YMF262::Impl::callback(byte flag)
625 {
626  setStatus(flag);
627 }
628 
629 // status set and IRQ handling
630 void YMF262::Impl::setStatus(byte flag)
631 {
632  // set status flag masking out disabled IRQs
633  status |= flag;
634  if (status & statusMask) {
635  status |= 0x80;
636  irq.set();
637  }
638 }
639 
640 // status reset and IRQ handling
641 void YMF262::Impl::resetStatus(byte flag)
642 {
643  // reset status flag
644  status &= ~flag;
645  if (!(status & statusMask)) {
646  status &= 0x7F;
647  irq.reset();
648  }
649 }
650 
651 // IRQ mask set
652 void YMF262::Impl::changeStatusMask(byte flag)
653 {
654  statusMask = flag;
655  status &= statusMask;
656  if (status) {
657  status |= 0x80;
658  irq.set();
659  } else {
660  status &= 0x7F;
661  irq.reset();
662  }
663 }
664 
665 
667 {
668  switch (state) {
669  case EG_ATTACK:
670  if (!(eg_cnt & eg_m_ar)) {
671  volume += (~volume * eg_inc[eg_sel_ar + ((eg_cnt >> eg_sh_ar) & 7)]) >> 3;
672  if (volume <= MIN_ATT_INDEX) {
673  volume = MIN_ATT_INDEX;
674  state = EG_DECAY;
675  }
676  }
677  break;
678 
679  case EG_DECAY:
680  if (!(eg_cnt & eg_m_dr)) {
681  volume += eg_inc[eg_sel_dr + ((eg_cnt >> eg_sh_dr) & 7)];
682  if (volume >= sl) {
683  state = EG_SUSTAIN;
684  }
685  }
686  break;
687 
688  case EG_SUSTAIN:
689  // this is important behaviour:
690  // one can change percusive/non-percussive
691  // modes on the fly and the chip will remain
692  // in sustain phase - verified on real YM3812
693  if (eg_type) {
694  // non-percussive mode
695  // do nothing
696  } else {
697  // percussive mode
698  // during sustain phase chip adds Release Rate (in percussive mode)
699  if (!(eg_cnt & eg_m_rr)) {
700  volume += eg_inc[eg_sel_rr + ((eg_cnt >> eg_sh_rr) & 7)];
701  if (volume >= MAX_ATT_INDEX) {
702  volume = MAX_ATT_INDEX;
703  }
704  } else {
705  // do nothing in sustain phase
706  }
707  }
708  break;
709 
710  case EG_RELEASE:
711  if (!(eg_cnt & eg_m_rr)) {
712  volume += eg_inc[eg_sel_rr + ((eg_cnt >> eg_sh_rr) & 7)];
713  if (volume >= MAX_ATT_INDEX) {
714  volume = MAX_ATT_INDEX;
715  state = EG_OFF;
716  }
717  }
718  break;
719 
720  default:
721  break;
722  }
723 }
724 
726 {
727  if (vib) {
728  // LFO phase modulation active
729  unsigned block_fnum = ch.block_fnum;
730  unsigned fnum_lfo = (block_fnum & 0x0380) >> 7;
731  int lfo_fn_table_index_offset = lfo_pm_table[lfo_pm + 16 * fnum_lfo];
732  Cnt += fnumToIncrement(block_fnum + lfo_fn_table_index_offset) * mul;
733  } else {
734  // LFO phase modulation disabled for this operator
735  Cnt += Incr;
736  }
737 }
738 
739 // advance to next sample
741 {
742  // Vibrato: 8 output levels (triangle waveform);
743  // 1 level takes 1024 samples
744  lfo_pm_cnt.addQuantum();
745  unsigned lfo_pm = (lfo_pm_cnt.toInt() & 7) | lfo_pm_depth_range;
746 
747  ++eg_cnt;
748  for (int c = 0; c < 18; ++c) {
749  YMF262Channel& ch = channel[c];
750  for (int s = 0; s < 2; ++s) {
751  YMF262Slot& op = ch.slot[s];
752  op.advanceEnvelopeGenerator(eg_cnt);
753  op.advancePhaseGenerator(ch, lfo_pm);
754  }
755  }
756 
757  // The Noise Generator of the YM3812 is 23-bit shift register.
758  // Period is equal to 2^23-2 samples.
759  // Register works at sampling frequency of the chip, so output
760  // can change on every sample.
761  //
762  // Output of the register and input to the bit 22 is:
763  // bit0 XOR bit14 XOR bit15 XOR bit22
764  //
765  // Simply use bit 22 as the noise output.
766  //
767  // unsigned j = ((noise_rng >> 0) ^ (noise_rng >> 14) ^
768  // (noise_rng >> 15) ^ (noise_rng >> 22)) & 1;
769  // noise_rng = (j << 22) | (noise_rng >> 1);
770  //
771  // Instead of doing all the logic operations above, we
772  // use a trick here (and use bit 0 as the noise output).
773  // The difference is only that the noise bit changes one
774  // step ahead. This doesn't matter since we don't know
775  // what is real state of the noise_rng after the reset.
776  if (noise_rng & 1) {
777  noise_rng ^= 0x800302;
778  }
779  noise_rng >>= 1;
780 }
781 
782 
783 inline int YMF262Slot::op_calc(unsigned phase, unsigned lfo_am) const
784 {
785  unsigned env = (TLL + volume + (lfo_am & AMmask)) << 4;
786  int p = env + wavetable[phase & SIN_MASK];
787  return (p < TL_TAB_LEN) ? tl_tab[p] : 0;
788 }
789 
790 // calculate output of a standard 2 operator channel
791 // (or 1st part of a 4-op channel)
792 void YMF262Channel::chan_calc(unsigned lfo_am)
793 {
794  // !! something is wrong with this, it caused bug
795  // !! [2823673] moonsound 4 operator FM fail
796  // !! optimization disabled for now
797  // !! TODO investigate
798  // !! maybe this micro optimization isn't worth the trouble/risk
799  // !!
800  // - mod.connect can point to 'phase_modulation' or 'ch0-output'
801  // - car.connect can point to 'phase_modulation2' or 'ch0-output'
802  // (see register #C0-#C8 writes)
803  // - phase_modulation2 is only used in 4op mode
804  // - mod.connect and car.connect can point to the same thing, so we need
805  // an addition for car.connect (and initialize phase_modulation2 to
806  // zero). For mod.connect we can directly assign the value.
807 
808  // ?? is this paragraph correct ??
809  // phase_modulation should be initialized to zero here. But there seems
810  // to be an optimization bug in gcc-4.2: it *seems* that when we
811  // initialize phase_modulation to zero in this function, the optimizer
812  // assumes it still has value zero at the end of this function (where
813  // it's used to calculate car.connect). As a workaround we initialize
814  // phase_modulation each time before calling this function.
815  phase_modulation = 0;
816  phase_modulation2 = 0;
817 
818  YMF262Slot& mod = slot[MOD];
819  int out = mod.fb_shift
820  ? mod.op1_out[0] + mod.op1_out[1]
821  : 0;
822  mod.op1_out[0] = mod.op1_out[1];
823  mod.op1_out[1] = mod.op_calc(mod.Cnt.toInt() + (out >> mod.fb_shift), lfo_am);
824  *mod.connect += mod.op1_out[1];
825 
826  YMF262Slot& car = slot[CAR];
827  *car.connect += car.op_calc(car.Cnt.toInt() + phase_modulation, lfo_am);
828 }
829 
830 // calculate output of a 2nd part of 4-op channel
831 void YMF262Channel::chan_calc_ext(unsigned lfo_am)
832 {
833  // !! see remark in chan_cal(), something is wrong with this
834  // !! optimization disabled for now
835  // !!
836  // - mod.connect can point to 'phase_modulation' or 'ch3-output'
837  // - car.connect always points to 'ch3-output' (always 4op-mode)
838  // (see register #C0-#C8 writes)
839  // - mod.connect and car.connect can point to the same thing, so we need
840  // an addition for car.connect. For mod.connect we can directly assign
841  // the value.
842 
843  phase_modulation = 0;
844 
845  YMF262Slot& mod = slot[MOD];
846  *mod.connect += mod.op_calc(mod.Cnt.toInt() + phase_modulation2, lfo_am);
847 
848  YMF262Slot& car = slot[CAR];
849  *car.connect += car.op_calc(car.Cnt.toInt() + phase_modulation, lfo_am);
850 }
851 
852 // operators used in the rhythm sounds generation process:
853 //
854 // Envelope Generator:
855 //
856 // channel operator register number Bass High Snare Tom Top
857 // / slot number TL ARDR SLRR Wave Drum Hat Drum Tom Cymbal
858 // 6 / 0 12 50 70 90 f0 +
859 // 6 / 1 15 53 73 93 f3 +
860 // 7 / 0 13 51 71 91 f1 +
861 // 7 / 1 16 54 74 94 f4 +
862 // 8 / 0 14 52 72 92 f2 +
863 // 8 / 1 17 55 75 95 f5 +
864 //
865 // Phase Generator:
866 //
867 // channel operator register number Bass High Snare Tom Top
868 // / slot number MULTIPLE Drum Hat Drum Tom Cymbal
869 // 6 / 0 12 30 +
870 // 6 / 1 15 33 +
871 // 7 / 0 13 31 + + +
872 // 7 / 1 16 34 ----- n o t u s e d -----
873 // 8 / 0 14 32 +
874 // 8 / 1 17 35 + +
875 //
876 // channel operator register number Bass High Snare Tom Top
877 // number number BLK/FNUM2 FNUM Drum Hat Drum Tom Cymbal
878 // 6 12,15 B6 A6 +
879 //
880 // 7 13,16 B7 A7 + + +
881 //
882 // 8 14,17 B8 A8 + + +
883 
884 // The following formulas can be well optimized.
885 // I leave them in direct form for now (in case I've missed something).
886 
887 inline int YMF262::Impl::genPhaseHighHat()
888 {
889  // high hat phase generation (verified on real YM3812):
890  // phase = d0 or 234 (based on frequency only)
891  // phase = 34 or 2d0 (based on noise)
892 
893  // base frequency derived from operator 1 in channel 7
894  int op71phase = channel[7].slot[MOD].Cnt.toInt();
895  bool bit7 = (op71phase & 0x80) != 0;
896  bool bit3 = (op71phase & 0x08) != 0;
897  bool bit2 = (op71phase & 0x04) != 0;
898  bool res1 = (bit2 ^ bit7) | bit3;
899  // when res1 = 0 phase = 0x000 | 0xd0;
900  // when res1 = 1 phase = 0x200 | (0xd0>>2);
901  unsigned phase = res1 ? (0x200 | (0xd0 >> 2)) : 0xd0;
902 
903  // enable gate based on frequency of operator 2 in channel 8
904  int op82phase = channel[8].slot[CAR].Cnt.toInt();
905  bool bit5e= (op82phase & 0x20) != 0;
906  bool bit3e= (op82phase & 0x08) != 0;
907  bool res2 = (bit3e ^ bit5e);
908  // when res2 = 0 pass the phase from calculation above (res1);
909  // when res2 = 1 phase = 0x200 | (0xd0>>2);
910  if (res2) {
911  phase = (0x200 | (0xd0 >> 2));
912  }
913 
914  // when phase & 0x200 is set and noise=1 then phase = 0x200|0xd0
915  // when phase & 0x200 is set and noise=0 then phase = 0x200|(0xd0>>2), ie no change
916  if (phase & 0x200) {
917  if (noise_rng & 1) {
918  phase = 0x200 | 0xd0;
919  }
920  } else {
921  // when phase & 0x200 is clear and noise=1 then phase = 0xd0>>2
922  // when phase & 0x200 is clear and noise=0 then phase = 0xd0, ie no change
923  if (noise_rng & 1) {
924  phase = 0xd0 >> 2;
925  }
926  }
927  return phase;
928 }
929 
930 inline int YMF262::Impl::genPhaseSnare()
931 {
932  // verified on real YM3812
933  // base frequency derived from operator 1 in channel 7
934  // noise bit XOR'es phase by 0x100
935  return ((channel[7].slot[MOD].Cnt.toInt() & 0x100) + 0x100)
936  ^ ((noise_rng & 1) << 8);
937 }
938 
939 inline int YMF262::Impl::genPhaseCymbal()
940 {
941  // verified on real YM3812
942  // enable gate based on frequency of operator 2 in channel 8
943  // NOTE: YM2413_2 uses bit5 | bit3, this core uses bit5 ^ bit3
944  // most likely only one of the two is correct
945  int op82phase = channel[8].slot[CAR].Cnt.toInt();
946  if ((op82phase ^ (op82phase << 2)) & 0x20) { // bit5 ^ bit3
947  return 0x300;
948  } else {
949  // base frequency derived from operator 1 in channel 7
950  int op71phase = channel[7].slot[MOD].Cnt.toInt();
951  bool bit7 = (op71phase & 0x80) != 0;
952  bool bit3 = (op71phase & 0x08) != 0;
953  bool bit2 = (op71phase & 0x04) != 0;
954  return ((bit2 != bit7) || bit3) ? 0x300 : 0x100;
955  }
956 }
957 
958 // calculate rhythm
959 void YMF262::Impl::chan_calc_rhythm(unsigned lfo_am)
960 {
961  // Bass Drum (verified on real YM3812):
962  // - depends on the channel 6 'connect' register:
963  // when connect = 0 it works the same as in normal (non-rhythm)
964  // mode (op1->op2->out)
965  // when connect = 1 _only_ operator 2 is present on output
966  // (op2->out), operator 1 is ignored
967  // - output sample always is multiplied by 2
968  YMF262Slot& mod6 = channel[6].slot[MOD];
969  int out = mod6.fb_shift ? mod6.op1_out[0] + mod6.op1_out[1] : 0;
970  mod6.op1_out[0] = mod6.op1_out[1];
971  int pm = mod6.CON ? 0 : mod6.op1_out[0];
972  mod6.op1_out[1] = mod6.op_calc(mod6.Cnt.toInt() + (out >> mod6.fb_shift), lfo_am);
973  YMF262Slot& car6 = channel[6].slot[CAR];
974  chanout[6] += 2 * car6.op_calc(car6.Cnt.toInt() + pm, lfo_am);
975 
976  // Phase generation is based on:
977  // HH (13) channel 7->slot 1 combined with channel 8->slot 2
978  // (same combination as TOP CYMBAL but different output phases)
979  // SD (16) channel 7->slot 1
980  // TOM (14) channel 8->slot 1
981  // TOP (17) channel 7->slot 1 combined with channel 8->slot 2
982  // (same combination as HIGH HAT but different output phases)
983  //
984  // Envelope generation based on:
985  // HH channel 7->slot1
986  // SD channel 7->slot2
987  // TOM channel 8->slot1
988  // TOP channel 8->slot2
989  YMF262Slot& mod7 = channel[7].slot[MOD];
990  chanout[7] += 2 * mod7.op_calc(genPhaseHighHat(), lfo_am);
991  YMF262Slot& car7 = channel[7].slot[CAR];
992  chanout[7] += 2 * car7.op_calc(genPhaseSnare(), lfo_am);
993  YMF262Slot& mod8 = channel[8].slot[MOD];
994  chanout[8] += 2 * mod8.op_calc(mod8.Cnt.toInt(), lfo_am);
995  YMF262Slot& car8 = channel[8].slot[CAR];
996  chanout[8] += 2 * car8.op_calc(genPhaseCymbal(), lfo_am);
997 }
998 
999 
1000 // generic table initialize
1001 void YMF262::Impl::init_tables()
1002 {
1003  static bool alreadyInit = false;
1004  if (alreadyInit) return;
1005  alreadyInit = true;
1006 
1007  for (int x = 0; x < TL_RES_LEN; x++) {
1008  double m = (1 << 16) / pow(2, (x + 1) * (ENV_STEP / 4.0) / 8.0);
1009  m = floor(m);
1010 
1011  // we never reach (1<<16) here due to the (x+1)
1012  // result fits within 16 bits at maximum
1013  int n = int(m); // 16 bits here
1014  n >>= 4; // 12 bits here
1015  n = (n >> 1) + (n & 1); // round to nearest
1016  // 11 bits here (rounded)
1017  n <<= 1; // 12 bits here (as in real chip)
1018  tl_tab[x * 2 + 0] = n;
1019  tl_tab[x * 2 + 1] = ~tl_tab[x * 2 + 0]; // this _is_ different from OPL2 (verified on real YMF262)
1020 
1021  for (int i = 1; i < 13; i++) {
1022  tl_tab[x * 2 + 0 + i * 2 * TL_RES_LEN] = tl_tab[x * 2 + 0] >> i;
1023  tl_tab[x * 2 + 1 + i * 2 * TL_RES_LEN] = ~tl_tab[x * 2 + 0 + i * 2 * TL_RES_LEN]; // this _is_ different from OPL2 (verified on real YMF262)
1024  }
1025  }
1026 
1027  const double LOG2 = ::log(2.0);
1028  for (int i = 0; i < SIN_LEN; i++) {
1029  // non-standard sinus
1030  double m = sin(((i * 2) + 1) * M_PI / SIN_LEN); // checked against the real chip
1031  // we never reach zero here due to ((i * 2) + 1)
1032  double o = (m > 0.0) ?
1033  8 * ::log( 1.0 / m) / LOG2: // convert to 'decibels'
1034  8 * ::log(-1.0 / m) / LOG2; // convert to 'decibels'
1035  o = o / (ENV_STEP / 4);
1036 
1037  int n = int(2 * o);
1038  n = (n >> 1) + (n & 1); // round to nearest
1039  sin_tab[i] = n * 2 + (m >= 0.0 ? 0 : 1);
1040  }
1041 
1042  for (int i = 0; i < SIN_LEN; ++i) {
1043  // these 'pictures' represent _two_ cycles
1044  // waveform 1: __ __
1045  // / \____/ \____
1046  // output only first half of the sinus waveform (positive one)
1047  sin_tab[1 * SIN_LEN + i] = (i & (1 << (SIN_BITS - 1)))
1048  ? TL_TAB_LEN
1049  : sin_tab[i];
1050 
1051  // waveform 2: __ __ __ __
1052  // / \/ \/ \/ \.
1053  // abs(sin)
1054  sin_tab[2 * SIN_LEN + i] = sin_tab[i & (SIN_MASK >> 1)];
1055 
1056  // waveform 3: _ _ _ _
1057  // / |_/ |_/ |_/ |_
1058  // abs(output only first quarter of the sinus waveform)
1059  sin_tab[3 * SIN_LEN + i] = (i & (1 << (SIN_BITS - 2)))
1060  ? TL_TAB_LEN
1061  : sin_tab[i & (SIN_MASK>>2)];
1062 
1063  // waveform 4: /\ ____/\ ____
1064  // \/ \/
1065  // output whole sinus waveform in half the cycle(step=2)
1066  // and output 0 on the other half of cycle
1067  sin_tab[4 * SIN_LEN + i] = (i & (1 << (SIN_BITS - 1)))
1068  ? TL_TAB_LEN
1069  : sin_tab[i * 2];
1070 
1071  // waveform 5: /\/\____/\/\____
1072  //
1073  // output abs(whole sinus) waveform in half the cycle(step=2)
1074  // and output 0 on the other half of cycle
1075  sin_tab[5 * SIN_LEN + i] = (i & (1 << (SIN_BITS - 1)))
1076  ? TL_TAB_LEN
1077  : sin_tab[(i * 2) & (SIN_MASK >> 1)];
1078 
1079  // waveform 6: ____ ____
1080  // ____ ____
1081  // output maximum in half the cycle and output minimum
1082  // on the other half of cycle
1083  sin_tab[6 * SIN_LEN + i] = (i & (1 << (SIN_BITS - 1)))
1084  ? 1 // negative
1085  : 0; // positive
1086 
1087  // waveform 7:|\____ |\____
1088  // \| \|
1089  // output sawtooth waveform
1090  int x = (i & (1 << (SIN_BITS - 1)))
1091  ? ((SIN_LEN - 1) - i) * 16 + 1 // negative: from 8177 to 1
1092  : i * 16; // positive: from 0 to 8176
1093  x = std::min(x, TL_TAB_LEN); // clip to the allowed range
1094  sin_tab[7 * SIN_LEN + i] = x;
1095  }
1096 }
1097 
1098 
1100 {
1101  if (!key) {
1102  // restart Phase Generator
1103  Cnt = FreqIndex(0);
1104  // phase -> Attack
1105  state = EG_ATTACK;
1106  }
1107  key |= key_set;
1108 }
1109 
1111 {
1112  if (key) {
1113  key &= ~key_clr;
1114  if (!key) {
1115  // phase -> Release
1116  if (state != EG_OFF) {
1117  state = EG_RELEASE;
1118  }
1119  }
1120  }
1121 }
1122 
1124 {
1125  if ((ar + ksr) < 16 + 60) {
1126  // verified on real YMF262 - all 15 x rates take "zero" time
1127  eg_sh_ar = eg_rate_shift [ar + ksr];
1128  eg_sel_ar = eg_rate_select[ar + ksr];
1129  } else {
1130  eg_sh_ar = 0;
1131  eg_sel_ar = 13 * RATE_STEPS;
1132  }
1133  eg_m_ar = (1 << eg_sh_ar) - 1;
1134  eg_sh_dr = eg_rate_shift [dr + ksr];
1135  eg_sel_dr = eg_rate_select[dr + ksr];
1136  eg_m_dr = (1 << eg_sh_dr) - 1;
1137 }
1139 {
1140  eg_sh_rr = eg_rate_shift [rr + ksr];
1141  eg_sel_rr = eg_rate_select[rr + ksr];
1142  eg_m_rr = (1 << eg_sh_rr) - 1;
1143 }
1144 
1145 // update phase increment counter of operator (also update the EG rates if necessary)
1147 {
1148  // (frequency) phase increment counter
1149  Incr = ch.fc * mul;
1150 
1151  int newKsr = ch.kcode >> KSR;
1152  if (ksr == newKsr) return;
1153  ksr = newKsr;
1154 
1155  // calculate envelope generator rates
1156  update_ar_dr();
1157  update_rr();
1158 }
1159 
1160 static const unsigned channelPairTab[18] = {
1161  0, 1, 2, 0, 1, 2, unsigned(~0), unsigned(~0), unsigned(~0),
1162  9, 10, 11, 9, 10, 11, unsigned(~0), unsigned(~0), unsigned(~0),
1163 };
1164 inline bool YMF262::Impl::isExtended(unsigned ch) const
1165 {
1166  assert(ch < 18);
1167  if (!OPL3_mode) return false;
1168  if (channelPairTab[ch] == unsigned(~0)) return false;
1169  return channel[channelPairTab[ch]].extended;
1170 }
1171 static inline unsigned getFirstOfPairNum(unsigned ch)
1172 {
1173  assert((ch < 18) && (channelPairTab[ch] != unsigned(~0)));
1174  return channelPairTab[ch];
1175 }
1176 inline YMF262Channel& YMF262::Impl::getFirstOfPair(unsigned ch)
1177 {
1178  return channel[getFirstOfPairNum(ch) + 0];
1179 }
1180 inline YMF262Channel& YMF262::Impl::getSecondOfPair(unsigned ch)
1181 {
1182  return channel[getFirstOfPairNum(ch) + 3];
1183 }
1184 
1185 // set multi,am,vib,EG-TYP,KSR,mul
1186 void YMF262::Impl::set_mul(unsigned sl, byte v)
1187 {
1188  unsigned chan_no = sl / 2;
1189  YMF262Channel& ch = channel[chan_no];
1190  YMF262Slot& slot = ch.slot[sl & 1];
1191 
1192  slot.mul = mul_tab[v & 0x0f];
1193  slot.KSR = (v & 0x10) ? 0 : 2;
1194  slot.eg_type = (v & 0x20) != 0;
1195  slot.vib = (v & 0x40) != 0;
1196  slot.AMmask = (v & 0x80) ? ~0 : 0;
1197 
1198  if (isExtended(chan_no)) {
1199  // 4op mode
1200  // update this slot using frequency data for 1st channel of a pair
1201  slot.calc_fc(getFirstOfPair(chan_no));
1202  } else {
1203  // normal (OPL2 mode or 2op mode)
1204  slot.calc_fc(ch);
1205  }
1206 }
1207 
1208 // set ksl & tl
1209 void YMF262::Impl::set_ksl_tl(unsigned sl, byte v)
1210 {
1211  unsigned chan_no = sl / 2;
1212  YMF262Channel& ch = channel[chan_no];
1213  YMF262Slot& slot = ch.slot[sl & 1];
1214 
1215  int ksl = v >> 6; // 0 / 1.5 / 3.0 / 6.0 dB/OCT
1216  slot.ksl = ksl ? 3 - ksl : 31;
1217  slot.TL = (v & 0x3F) << (ENV_BITS - 1 - 7); // 7 bits TL (bit 6 = always 0)
1218 
1219  if (isExtended(chan_no)) {
1220  // update this slot using frequency data for 1st channel of a pair
1221  YMF262Channel& ch0 = getFirstOfPair(chan_no);
1222  slot.TLL = slot.TL + (ch0.ksl_base >> slot.ksl);
1223  } else {
1224  // normal
1225  slot.TLL = slot.TL + (ch.ksl_base >> slot.ksl);
1226  }
1227 }
1228 
1229 // set attack rate & decay rate
1230 void YMF262::Impl::set_ar_dr(unsigned sl, byte v)
1231 {
1232  YMF262Channel& ch = channel[sl / 2];
1233  YMF262Slot& slot = ch.slot[sl & 1];
1234 
1235  slot.ar = (v >> 4) ? 16 + ((v >> 4) << 2) : 0;
1236  slot.dr = (v & 0x0F) ? 16 + ((v & 0x0F) << 2) : 0;
1237  slot.update_ar_dr();
1238 }
1239 
1240 // set sustain level & release rate
1241 void YMF262::Impl::set_sl_rr(unsigned sl, byte v)
1242 {
1243  YMF262Channel& ch = channel[sl / 2];
1244  YMF262Slot& slot = ch.slot[sl & 1];
1245 
1246  slot.sl = sl_tab[v >> 4];
1247  slot.rr = (v & 0x0F) ? 16 + ((v & 0x0F) << 2) : 0;
1248  slot.update_rr();
1249 }
1250 
1252 {
1253  // no need to call updateStream(time)
1254  return peekReg(r);
1255 }
1256 
1257 byte YMF262::Impl::peekReg(unsigned r) const
1258 {
1259  return reg[r];
1260 }
1261 
1262 void YMF262::Impl::writeReg(unsigned r, byte v, EmuTime::param time)
1263 {
1264  if (!OPL3_mode && (r != 0x105)) {
1265  // in OPL2 mode the only accessible in set #2 is register 0x05
1266  r &= ~0x100;
1267  }
1268  writeReg512(r, v, time);
1269 }
1271 {
1272  updateStream(time); // TODO optimize only for regs that directly influence sound
1273  writeRegDirect(r, v, time);
1274 }
1275 void YMF262::Impl::writeRegDirect(unsigned r, byte v, EmuTime::param time)
1276 {
1277  reg[r] = v;
1278 
1279  switch (r) {
1280  case 0x104:
1281  // 6 channels enable
1282  channel[ 0].extended = (v & 0x01) != 0;
1283  channel[ 1].extended = (v & 0x02) != 0;
1284  channel[ 2].extended = (v & 0x04) != 0;
1285  channel[ 9].extended = (v & 0x08) != 0;
1286  channel[10].extended = (v & 0x10) != 0;
1287  channel[11].extended = (v & 0x20) != 0;
1288  return;
1289 
1290  case 0x105:
1291  // OPL3 mode when bit0=1 otherwise it is OPL2 mode
1292  OPL3_mode = v & 0x01;
1293 
1294  // When NEW2 bit is first set, a read from the status register
1295  // (once) returns bit 1 set (0x02). This only happens once after
1296  // reset, so clearing NEW2 and setting it again doesn't cause
1297  // another change in the status register.
1298  // This seems strange behaviour to me, but it is what I saw on
1299  // a real YMF278. Also see page 10 in the 'OPL4 YMF278B
1300  // Application Manual' (though it's not clear on the details).
1301  if ((v & 0x02) && !alreadySignaledNEW2 && isYMF278) {
1302  status2 = 0x02;
1303  alreadySignaledNEW2 = true;
1304  }
1305 
1306  // following behaviour was tested on real YMF262,
1307  // switching OPL3/OPL2 modes on the fly:
1308  // - does not change the waveform previously selected
1309  // (unless when ....)
1310  // - does not update CH.A, CH.B, CH.C and CH.D output
1311  // selectors (registers c0-c8) (unless when ....)
1312  // - does not disable channels 9-17 on OPL3->OPL2 switch
1313  // - does not switch 4 operator channels back to 2
1314  // operator channels
1315  return;
1316  }
1317 
1318  unsigned ch_offset = (r & 0x100) ? 9 : 0;
1319  switch (r & 0xE0) {
1320  case 0x00: // 00-1F:control
1321  switch (r & 0x1F) {
1322  case 0x01: // test register
1323  break;
1324 
1325  case 0x02: // Timer 1
1326  timer1->setValue(v);
1327  break;
1328 
1329  case 0x03: // Timer 2
1330  timer2->setValue(v);
1331  break;
1332 
1333  case 0x04: // IRQ clear / mask and Timer enable
1334  if (v & 0x80) {
1335  // IRQ flags clear
1336  resetStatus(0x60);
1337  } else {
1338  changeStatusMask((~v) & 0x60);
1339  timer1->setStart((v & R04_ST1) != 0, time);
1340  timer2->setStart((v & R04_ST2) != 0, time);
1341  }
1342  break;
1343 
1344  case 0x08: // x,NTS,x,x, x,x,x,x
1345  nts = (v & 0x40) != 0;
1346  break;
1347 
1348  default:
1349  break;
1350  }
1351  break;
1352 
1353  case 0x20: { // am ON, vib ON, ksr, eg_type, mul
1354  int slot = slot_array[r & 0x1F];
1355  if (slot < 0) return;
1356  set_mul(slot + ch_offset * 2, v);
1357  break;
1358  }
1359  case 0x40: {
1360  int slot = slot_array[r & 0x1F];
1361  if (slot < 0) return;
1362  set_ksl_tl(slot + ch_offset * 2, v);
1363  break;
1364  }
1365  case 0x60: {
1366  int slot = slot_array[r & 0x1F];
1367  if (slot < 0) return;
1368  set_ar_dr(slot + ch_offset * 2, v);
1369  break;
1370  }
1371  case 0x80: {
1372  int slot = slot_array[r & 0x1F];
1373  if (slot < 0) return;
1374  set_sl_rr(slot + ch_offset * 2, v);
1375  break;
1376  }
1377  case 0xA0: {
1378  // note: not r != 0x1BD, only first register block
1379  if (r == 0xBD) {
1380  // am depth, vibrato depth, r,bd,sd,tom,tc,hh
1381  lfo_am_depth = (v & 0x80) != 0;
1382  lfo_pm_depth_range = (v & 0x40) ? 8 : 0;
1383  rhythm = v & 0x3F;
1384 
1385  if (rhythm & 0x20) {
1386  // BD key on/off
1387  if (v & 0x10) {
1388  channel[6].slot[MOD].FM_KEYON (2);
1389  channel[6].slot[CAR].FM_KEYON (2);
1390  } else {
1391  channel[6].slot[MOD].FM_KEYOFF(2);
1392  channel[6].slot[CAR].FM_KEYOFF(2);
1393  }
1394  // HH key on/off
1395  if (v & 0x01) {
1396  channel[7].slot[MOD].FM_KEYON (2);
1397  } else {
1398  channel[7].slot[MOD].FM_KEYOFF(2);
1399  }
1400  // SD key on/off
1401  if (v & 0x08) {
1402  channel[7].slot[CAR].FM_KEYON (2);
1403  } else {
1404  channel[7].slot[CAR].FM_KEYOFF(2);
1405  }
1406  // TOM key on/off
1407  if (v & 0x04) {
1408  channel[8].slot[MOD].FM_KEYON (2);
1409  } else {
1410  channel[8].slot[MOD].FM_KEYOFF(2);
1411  }
1412  // TOP-CY key on/off
1413  if (v & 0x02) {
1414  channel[8].slot[CAR].FM_KEYON (2);
1415  } else {
1416  channel[8].slot[CAR].FM_KEYOFF(2);
1417  }
1418  } else {
1419  // BD key off
1420  channel[6].slot[MOD].FM_KEYOFF(2);
1421  channel[6].slot[CAR].FM_KEYOFF(2);
1422  // HH key off
1423  channel[7].slot[MOD].FM_KEYOFF(2);
1424  // SD key off
1425  channel[7].slot[CAR].FM_KEYOFF(2);
1426  // TOM key off
1427  channel[8].slot[MOD].FM_KEYOFF(2);
1428  // TOP-CY off
1429  channel[8].slot[CAR].FM_KEYOFF(2);
1430  }
1431  return;
1432  }
1433 
1434  // keyon,block,fnum
1435  if ((r & 0x0F) > 8) {
1436  return;
1437  }
1438  unsigned chan_no = (r & 0x0F) + ch_offset;
1439  YMF262Channel& ch = channel[chan_no];
1440  int block_fnum;
1441  if (!(r & 0x10)) {
1442  // a0-a8
1443  block_fnum = (ch.block_fnum & 0x1F00) | v;
1444  } else {
1445  // b0-b8
1446  block_fnum = ((v & 0x1F) << 8) | (ch.block_fnum & 0xFF);
1447  if (isExtended(chan_no)) {
1448  if (getFirstOfPairNum(chan_no) == chan_no) {
1449  // keyon/off slots of both channels
1450  // forming a 4-op channel
1451  YMF262Channel& ch0 = getFirstOfPair(chan_no);
1452  YMF262Channel& ch3 = getSecondOfPair(chan_no);
1453  if (v & 0x20) {
1454  ch0.slot[MOD].FM_KEYON(1);
1455  ch0.slot[CAR].FM_KEYON(1);
1456  ch3.slot[MOD].FM_KEYON(1);
1457  ch3.slot[CAR].FM_KEYON(1);
1458  } else {
1459  ch0.slot[MOD].FM_KEYOFF(1);
1460  ch0.slot[CAR].FM_KEYOFF(1);
1461  ch3.slot[MOD].FM_KEYOFF(1);
1462  ch3.slot[CAR].FM_KEYOFF(1);
1463  }
1464  } else {
1465  // do nothing
1466  }
1467  } else {
1468  // 2 operator function keyon/off
1469  if (v & 0x20) {
1470  ch.slot[MOD].FM_KEYON (1);
1471  ch.slot[CAR].FM_KEYON (1);
1472  } else {
1473  ch.slot[MOD].FM_KEYOFF(1);
1474  ch.slot[CAR].FM_KEYOFF(1);
1475  }
1476  }
1477  }
1478  // update
1479  if (ch.block_fnum != block_fnum) {
1480  ch.block_fnum = block_fnum;
1481  ch.ksl_base = ksl_tab[block_fnum >> 6];
1482  ch.fc = fnumToIncrement(block_fnum);
1483 
1484  // BLK 2,1,0 bits -> bits 3,2,1 of kcode
1485  ch.kcode = (ch.block_fnum & 0x1C00) >> 9;
1486 
1487  // the info below is actually opposite to what is stated
1488  // in the Manuals (verifed on real YMF262)
1489  // if notesel == 0 -> lsb of kcode is bit 10 (MSB) of fnum
1490  // if notesel == 1 -> lsb of kcode is bit 9 (MSB-1) of fnum
1491  if (nts) {
1492  ch.kcode |= (ch.block_fnum & 0x100) >> 8; // notesel == 1
1493  } else {
1494  ch.kcode |= (ch.block_fnum & 0x200) >> 9; // notesel == 0
1495  }
1496  if (isExtended(chan_no)) {
1497  if (getFirstOfPairNum(chan_no) == chan_no) {
1498  // update slots of both channels
1499  // forming up 4-op channel
1500  // refresh Total Level
1501  YMF262Channel& ch0 = getFirstOfPair(chan_no);
1502  YMF262Channel& ch3 = getSecondOfPair(chan_no);
1503  ch0.slot[MOD].TLL = ch0.slot[MOD].TL + (ch.ksl_base >> ch0.slot[MOD].ksl);
1504  ch0.slot[CAR].TLL = ch0.slot[CAR].TL + (ch.ksl_base >> ch0.slot[CAR].ksl);
1505  ch3.slot[MOD].TLL = ch3.slot[MOD].TL + (ch.ksl_base >> ch3.slot[MOD].ksl);
1506  ch3.slot[CAR].TLL = ch3.slot[CAR].TL + (ch.ksl_base >> ch3.slot[CAR].ksl);
1507 
1508  // refresh frequency counter
1509  ch0.slot[MOD].calc_fc(ch);
1510  ch0.slot[CAR].calc_fc(ch);
1511  ch3.slot[MOD].calc_fc(ch);
1512  ch3.slot[CAR].calc_fc(ch);
1513  } else {
1514  // nothing
1515  }
1516  } else {
1517  // refresh Total Level in both SLOTs of this channel
1518  ch.slot[MOD].TLL = ch.slot[MOD].TL + (ch.ksl_base >> ch.slot[MOD].ksl);
1519  ch.slot[CAR].TLL = ch.slot[CAR].TL + (ch.ksl_base >> ch.slot[CAR].ksl);
1520 
1521  // refresh frequency counter in both SLOTs of this channel
1522  ch.slot[MOD].calc_fc(ch);
1523  ch.slot[CAR].calc_fc(ch);
1524  }
1525  }
1526  break;
1527  }
1528  case 0xC0: {
1529  // CH.D, CH.C, CH.B, CH.A, FB(3bits), C
1530  if ((r & 0xF) > 8) {
1531  return;
1532  }
1533  unsigned chan_no = (r & 0x0F) + ch_offset;
1534  YMF262Channel& ch = channel[chan_no];
1535 
1536  unsigned base = chan_no * 4;
1537  if (OPL3_mode) {
1538  // OPL3 mode
1539  pan[base + 0] = (v & 0x10) ? unsigned(~0) : 0; // ch.A
1540  pan[base + 1] = (v & 0x20) ? unsigned(~0) : 0; // ch.B
1541  pan[base + 2] = (v & 0x40) ? unsigned(~0) : 0; // ch.C
1542  pan[base + 3] = (v & 0x80) ? unsigned(~0) : 0; // ch.D
1543  } else {
1544  // OPL2 mode - always enabled
1545  pan[base + 0] = unsigned(~0); // ch.A
1546  pan[base + 1] = unsigned(~0); // ch.B
1547  pan[base + 2] = unsigned(~0); // ch.C
1548  pan[base + 3] = unsigned(~0); // ch.D
1549  }
1550 
1551  ch.slot[MOD].setFeedbackShift((v >> 1) & 7);
1552  ch.slot[MOD].CON = v & 1;
1553 
1554  if (isExtended(chan_no)) {
1555  unsigned chan_no0 = getFirstOfPairNum(chan_no);
1556  unsigned chan_no3 = chan_no0 + 3;
1557  YMF262Channel& ch0 = getFirstOfPair(chan_no);
1558  YMF262Channel& ch3 = getSecondOfPair(chan_no);
1559  switch ((ch0.slot[MOD].CON ? 2:0) | (ch3.slot[MOD].CON ? 1:0)) {
1560  case 0:
1561  // 1 -> 2 -> 3 -> 4 -> out
1562  ch0.slot[MOD].connect = &phase_modulation;
1563  ch0.slot[CAR].connect = &phase_modulation2;
1564  ch3.slot[MOD].connect = &phase_modulation;
1565  ch3.slot[CAR].connect = &chanout[chan_no3];
1566  break;
1567  case 1:
1568  // 1 -> 2 -\.
1569  // 3 -> 4 --+-> out
1570  ch0.slot[MOD].connect = &phase_modulation;
1571  ch0.slot[CAR].connect = &chanout[chan_no0];
1572  ch3.slot[MOD].connect = &phase_modulation;
1573  ch3.slot[CAR].connect = &chanout[chan_no3];
1574  break;
1575  case 2:
1576  // 1 ----------\.
1577  // 2 -> 3 -> 4 -+-> out
1578  ch0.slot[MOD].connect = &chanout[chan_no0];
1579  ch0.slot[CAR].connect = &phase_modulation2;
1580  ch3.slot[MOD].connect = &phase_modulation;
1581  ch3.slot[CAR].connect = &chanout[chan_no3];
1582  break;
1583  case 3:
1584  // 1 -----\.
1585  // 2 -> 3 -+-> out
1586  // 4 -----/
1587  ch0.slot[MOD].connect = &chanout[chan_no0];
1588  ch0.slot[CAR].connect = &phase_modulation2;
1589  ch3.slot[MOD].connect = &chanout[chan_no3];
1590  ch3.slot[CAR].connect = &chanout[chan_no3];
1591  break;
1592  }
1593  } else {
1594  // 2 operators mode
1595  ch.slot[MOD].connect = ch.slot[MOD].CON
1596  ? &chanout[chan_no]
1597  : &phase_modulation;
1598  ch.slot[CAR].connect = &chanout[chan_no];
1599  }
1600  break;
1601  }
1602  case 0xE0: {
1603  // waveform select
1604  int slot = slot_array[r & 0x1f];
1605  if (slot < 0) return;
1606  slot += ch_offset * 2;
1607  YMF262Channel& ch = channel[slot / 2];
1608 
1609  // store 3-bit value written regardless of current OPL2 or OPL3
1610  // mode... (verified on real YMF262)
1611  v &= 7;
1612  // ... but select only waveforms 0-3 in OPL2 mode
1613  if (!OPL3_mode) {
1614  v &= 3;
1615  }
1616  ch.slot[slot & 1].wavetable = &sin_tab[v * SIN_LEN];
1617  break;
1618  }
1619  }
1620 }
1621 
1622 
1624 {
1625  eg_cnt = 0;
1626 
1627  noise_rng = 1; // noise shift register
1628  nts = false; // note split
1629  alreadySignaledNEW2 = false;
1630  resetStatus(0x60);
1631 
1632  // reset with register write
1633  writeRegDirect(0x01, 0, time); // test register
1634  writeRegDirect(0x02, 0, time); // Timer1
1635  writeRegDirect(0x03, 0, time); // Timer2
1636  writeRegDirect(0x04, 0, time); // IRQ mask clear
1637 
1638  // FIX IT registers 101, 104 and 105
1639  // FIX IT (dont change CH.D, CH.C, CH.B and CH.A in C0-C8 registers)
1640  for (int c = 0xFF; c >= 0x20; c--) {
1641  writeRegDirect(c, 0, time);
1642  }
1643  // FIX IT (dont change CH.D, CH.C, CH.B and CH.A in C0-C8 registers)
1644  for (int c = 0x1FF; c >= 0x120; c--) {
1645  writeRegDirect(c, 0, time);
1646  }
1647 
1648  // reset operator parameters
1649  for (int c = 0; c < 9 * 2; c++) {
1650  YMF262Channel& ch = channel[c];
1651  for (int s = 0; s < 2; s++) {
1652  ch.slot[s].state = EG_OFF;
1653  ch.slot[s].volume = MAX_ATT_INDEX;
1654  }
1655  }
1656 }
1657 
1658 YMF262::Impl::Impl(YMF262& self, const std::string& name,
1659  const DeviceConfig& config, bool isYMF278_)
1660  : ResampledSoundDevice(config.getMotherBoard(), name, "MoonSound FM-part",
1661  18, true)
1662  , debuggable(make_unique<YMF262Debuggable>(
1663  config.getMotherBoard(), self, getName()))
1664  , timer1(isYMF278_
1665  ? EmuTimer::createOPL4_1(config.getScheduler(), *this)
1666  : EmuTimer::createOPL3_1(config.getScheduler(), *this))
1667  , timer2(isYMF278_
1668  ? EmuTimer::createOPL4_2(config.getScheduler(), *this)
1669  : EmuTimer::createOPL3_2(config.getScheduler(), *this))
1670  , irq(config.getMotherBoard(), getName() + ".IRQ")
1671  , lfo_am_cnt(0), lfo_pm_cnt(0)
1672  , isYMF278(isYMF278_)
1673 {
1674  lfo_am_depth = false;
1675  lfo_pm_depth_range = 0;
1676  rhythm = 0;
1677  OPL3_mode = false;
1678  status = status2 = statusMask = 0;
1679 
1680  // avoid (harmless) UMR in serialize()
1681  memset(chanout, 0, sizeof(chanout));
1682  memset(reg, 0, sizeof(reg));
1683 
1684  init_tables();
1685 
1686  double input = isYMF278
1687  ? 33868800.0 / (19 * 36)
1688  : 4 * 3579545.0 / ( 8 * 36);
1689  setInputRate(int(input + 0.5));
1690 
1691  reset(config.getMotherBoard().getCurrentTime());
1692  registerSound(config);
1693 }
1694 
1696 {
1697  unregisterSound();
1698 }
1699 
1701 {
1702  // no need to call updateStream(time)
1703  byte result = status | status2;
1704  status2 = 0;
1705  return result;
1706 }
1707 
1709 {
1710  return status | status2;
1711 }
1712 
1713 bool YMF262::Impl::checkMuteHelper()
1714 {
1715  // TODO this doesn't always mute when possible
1716  for (int i = 0; i < 18; i++) {
1717  for (int j = 0; j < 2; j++) {
1718  YMF262Slot& sl = channel[i].slot[j];
1719  if (!((sl.state == EG_OFF) ||
1720  ((sl.state == EG_RELEASE) &&
1721  ((sl.TLL + sl.volume) >= ENV_QUIET)))) {
1722  return false;
1723  }
1724  }
1725  }
1726  return true;
1727 }
1728 
1729 int YMF262::Impl::getAmplificationFactor() const
1730 {
1731  return 1 << 2;
1732 }
1733 
1734 void YMF262::Impl::generateChannels(int** bufs, unsigned num)
1735 {
1736  // TODO implement per-channel mute (instead of all-or-nothing)
1737  // TODO output rhythm on separate channels?
1738  if (checkMuteHelper()) {
1739  // TODO update internal state, even if muted
1740  for (int i = 0; i < 18; ++i) {
1741  bufs[i] = nullptr;
1742  }
1743  return;
1744  }
1745 
1746  bool rhythmEnabled = (rhythm & 0x20) != 0;
1747 
1748  for (unsigned j = 0; j < num; ++j) {
1749  // Amplitude modulation: 27 output levels (triangle waveform);
1750  // 1 level takes one of: 192, 256 or 448 samples
1751  // One entry from LFO_AM_TABLE lasts for 64 samples
1752  lfo_am_cnt.addQuantum();
1753  if (lfo_am_cnt == LFOAMIndex(LFO_AM_TAB_ELEMENTS)) {
1754  // lfo_am_table is 210 elements long
1755  lfo_am_cnt = LFOAMIndex(0);
1756  }
1757  unsigned tmp = lfo_am_table[lfo_am_cnt.toInt()];
1758  unsigned lfo_am = lfo_am_depth ? tmp : tmp / 4;
1759 
1760  // clear channel outputs
1761  memset(chanout, 0, sizeof(chanout));
1762 
1763  // channels 0,3 1,4 2,5 9,12 10,13 11,14
1764  // in either 2op or 4op mode
1765  for (int k = 0; k <= 9; k += 9) {
1766  for (int i = 0; i < 3; ++i) {
1767  YMF262Channel& ch0 = channel[k + i + 0];
1768  YMF262Channel& ch3 = channel[k + i + 3];
1769  // extended 4op ch#0 part 1 or 2op ch#0
1770  ch0.chan_calc(lfo_am);
1771  if (ch0.extended) {
1772  // extended 4op ch#0 part 2
1773  ch3.chan_calc_ext(lfo_am);
1774  } else {
1775  // standard 2op ch#3
1776  ch3.chan_calc(lfo_am);
1777  }
1778  }
1779  }
1780 
1781  // channels 6,7,8 rhythm or 2op mode
1782  if (!rhythmEnabled) {
1783  channel[6].chan_calc(lfo_am);
1784  channel[7].chan_calc(lfo_am);
1785  channel[8].chan_calc(lfo_am);
1786  } else {
1787  // Rhythm part
1788  chan_calc_rhythm(lfo_am);
1789  }
1790 
1791  // channels 15,16,17 are fixed 2-operator channels only
1792  channel[15].chan_calc(lfo_am);
1793  channel[16].chan_calc(lfo_am);
1794  channel[17].chan_calc(lfo_am);
1795 
1796  for (int i = 0; i < 18; ++i) {
1797  bufs[i][2 * j + 0] += chanout[i] & pan[4 * i + 0];
1798  bufs[i][2 * j + 1] += chanout[i] & pan[4 * i + 1];
1799  // unused c += chanout[i] & pan[4 * i + 2];
1800  // unused d += chanout[i] & pan[4 * i + 3];
1801  }
1802 
1803  advance();
1804  }
1805 }
1806 
1807 
1808 static enum_string<EnvelopeState> envelopeStateInfo[]= {
1809  { "ATTACK", EG_ATTACK },
1810  { "DECAY", EG_DECAY },
1811  { "SUSTAIN", EG_SUSTAIN },
1812  { "RELEASE", EG_RELEASE },
1813  { "OFF", EG_OFF }
1814 };
1815 SERIALIZE_ENUM(EnvelopeState, envelopeStateInfo);
1816 
1817 template<typename Archive>
1818 void YMF262Slot::serialize(Archive& ar, unsigned /*version*/)
1819 {
1820  // wavetable
1821  unsigned waveform = unsigned((wavetable - sin_tab) / SIN_LEN);
1822  ar.serialize("waveform", waveform);
1823  if (ar.isLoader()) {
1824  wavetable = &sin_tab[waveform * SIN_LEN];
1825  }
1826 
1827  // done by rewriting registers:
1828  // connect, fb_shift, CON
1829  // TODO handle more state like this
1830 
1831  ar.serialize("Cnt", Cnt);
1832  ar.serialize("Incr", Incr);
1833  ar.serialize("op1_out", op1_out);
1834  ar.serialize("TL", TL);
1835  ar.serialize("TLL", TLL);
1836  ar.serialize("volume", volume);
1837  ar.serialize("sl", sl);
1838  ar.serialize("state", state);
1839  ar.serialize("eg_m_ar", eg_m_ar);
1840  ar.serialize("eg_m_dr", eg_m_dr);
1841  ar.serialize("eg_m_rr", eg_m_rr);
1842  ar.serialize("eg_sh_ar", eg_sh_ar);
1843  ar.serialize("eg_sel_ar", eg_sel_ar);
1844  ar.serialize("eg_sh_dr", eg_sh_dr);
1845  ar.serialize("eg_sel_dr", eg_sel_dr);
1846  ar.serialize("eg_sh_rr", eg_sh_rr);
1847  ar.serialize("eg_sel_rr", eg_sel_rr);
1848  ar.serialize("key", key);
1849  ar.serialize("eg_type", eg_type);
1850  ar.serialize("AMmask", AMmask);
1851  ar.serialize("vib", vib);
1852  ar.serialize("ar", this->ar);
1853  ar.serialize("dr", dr);
1854  ar.serialize("rr", rr);
1855  ar.serialize("KSR", KSR);
1856  ar.serialize("ksl", ksl);
1857  ar.serialize("ksr", ksr);
1858  ar.serialize("mul", mul);
1859 }
1860 
1861 template<typename Archive>
1862 void YMF262Channel::serialize(Archive& ar, unsigned /*version*/)
1863 {
1864  ar.serialize("slots", slot);
1865  ar.serialize("block_fnum", block_fnum);
1866  ar.serialize("fc", fc);
1867  ar.serialize("ksl_base", ksl_base);
1868  ar.serialize("kcode", kcode);
1869  ar.serialize("extended", extended);
1870 }
1871 
1872 // version 1: initial version
1873 // version 2: added alreadySignaledNEW2
1874 template<typename Archive>
1875 void YMF262::Impl::serialize(Archive& ar, unsigned version)
1876 {
1877  ar.serialize("timer1", *timer1);
1878  ar.serialize("timer2", *timer2);
1879  ar.serialize("irq", irq);
1880  ar.serialize("chanout", chanout);
1881  ar.serialize_blob("registers", reg, sizeof(reg));
1882  ar.serialize("channels", channel);
1883  ar.serialize("eg_cnt", eg_cnt);
1884  ar.serialize("noise_rng", noise_rng);
1885  ar.serialize("lfo_am_cnt", lfo_am_cnt);
1886  ar.serialize("lfo_pm_cnt", lfo_pm_cnt);
1887  ar.serialize("lfo_am_depth", lfo_am_depth);
1888  ar.serialize("lfo_pm_depth_range", lfo_pm_depth_range);
1889  ar.serialize("rhythm", rhythm);
1890  ar.serialize("nts", nts);
1891  ar.serialize("OPL3_mode", OPL3_mode);
1892  ar.serialize("status", status);
1893  ar.serialize("status2", status2);
1894  ar.serialize("statusMask", statusMask);
1895  if (ar.versionAtLeast(version, 2)) {
1896  ar.serialize("alreadySignaledNEW2", alreadySignaledNEW2);
1897  }
1898 
1899  // TODO restore more state by rewriting register values
1900  // this handles pan
1901  EmuTime::param time = timer1->getCurrentTime();
1902  for (int i = 0xC0; i <= 0xC8; ++i) {
1903  writeRegDirect(i + 0x000, reg[i + 0x000], time);
1904  writeRegDirect(i + 0x100, reg[i + 0x100], time);
1905  }
1906 }
1907 
1908 
1909 // SimpleDebuggable
1910 
1912  const std::string& name)
1913  : SimpleDebuggable(motherBoard, name + " regs",
1914  "MoonSound FM-part registers", 0x200)
1915  , ymf262(ymf262_)
1916 {
1917 }
1918 
1919 byte YMF262Debuggable::read(unsigned address)
1920 {
1921  return ymf262.peekReg(address);
1922 }
1923 
1924 void YMF262Debuggable::write(unsigned address, byte value, EmuTime::param time)
1925 {
1926  ymf262.writeReg512(address, value, time);
1927 }
1928 
1929 // class YMF262
1930 
1931 YMF262::YMF262(const std::string& name, const DeviceConfig& config, bool isYMF278)
1932  : pimpl(make_unique<Impl>(*this, name, config, isYMF278))
1933 {
1934 }
1935 
1937 {
1938 }
1939 
1941 {
1942  pimpl->reset(time);
1943 }
1944 
1945 void YMF262::writeReg(unsigned r, byte v, EmuTime::param time)
1946 {
1947  pimpl->writeReg(r, v, time);
1948 }
1949 
1950 void YMF262::writeReg512(unsigned r, byte v, EmuTime::param time)
1951 {
1952  pimpl->writeReg512(r, v, time);
1953 }
1954 
1955 byte YMF262::readReg(unsigned reg)
1956 {
1957  return pimpl->readReg(reg);
1958 }
1959 
1960 byte YMF262::peekReg(unsigned reg) const
1961 {
1962  return pimpl->peekReg(reg);
1963 }
1964 
1966 {
1967  return pimpl->readStatus();
1968 }
1969 
1971 {
1972  return pimpl->peekStatus();
1973 }
1974 
1975 template<typename Archive>
1976 void YMF262::serialize(Archive& ar, unsigned version)
1977 {
1978  pimpl->serialize(ar, version);
1979 }
1981 
1982 } // namespace openmsx