1 // license:GPL-2.0+
2 // copyright-holders:Jarek Burczynski,Tatsuyuki Satoh
3 /*
4 
5 This file is based on fmopl.c from MAME. The non-YM3816 parts have been
6 ripped out in the interest of making this simpler, since Doom music doesn't
7 need them. I also made it render the sound a voice at a time instead of a
8 sample at a time, so unused voices don't waste time being calculated. If all
9 voices are playing, it's not much difference, but it does offer a big
10 improvement when only a few voices are playing.
11 
12 
13 
14 **
15 ** File: fmopl.c - software implementation of FM sound generator
16 **                                            types OPL and OPL2
17 **
18 ** Copyright Jarek Burczynski (bujar at mame dot net)
19 ** Copyright Tatsuyuki Satoh , MultiArcadeMachineEmulator development
20 **
21 ** Version 0.72
22 **
23 
24 Revision History:
25 
26 04-08-2003 Jarek Burczynski:
27  - removed BFRDY hack. BFRDY is busy flag, and it should be 0 only when the chip
28    handles memory read/write or during the adpcm synthesis when the chip
29    requests another byte of ADPCM data.
30 
31 24-07-2003 Jarek Burczynski:
32  - added a small hack for Y8950 status BFRDY flag (bit 3 should be set after
33    some (unknown) delay). Right now it's always set.
34 
35 14-06-2003 Jarek Burczynski:
36  - implemented all of the status register flags in Y8950 emulation
37  - renamed y8950_set_delta_t_memory() parameters from _rom_ to _mem_ since
38    they can be either RAM or ROM
39 
40 08-10-2002 Jarek Burczynski (thanks to Dox for the YM3526 chip)
41  - corrected ym3526_read() to always set bit 2 and bit 1
42    to HIGH state - identical to ym3812_read (verified on real YM3526)
43 
44 04-28-2002 Jarek Burczynski:
45  - binary exact Envelope Generator (verified on real YM3812);
46    compared to YM2151: the EG clock is equal to internal_clock,
47    rates are 2 times slower and volume resolution is one bit less
48  - modified interface functions (they no longer return pointer -
49    that's internal to the emulator now):
50     - new wrapper functions for OPLCreate: ym3526_init(), ym3812_init() and y8950_init()
51  - corrected 'off by one' error in feedback calculations (when feedback is off)
52  - enabled waveform usage (credit goes to Vlad Romascanu and zazzal22)
53  - speeded up noise generator calculations (Nicola Salmoria)
54 
55 03-24-2002 Jarek Burczynski (thanks to Dox for the YM3812 chip)
56  Complete rewrite (all verified on real YM3812):
57  - corrected sin_tab and tl_tab data
58  - corrected operator output calculations
59  - corrected waveform_select_enable register;
60    simply: ignore all writes to waveform_select register when
61    waveform_select_enable == 0 and do not change the waveform previously selected.
62  - corrected KSR handling
63  - corrected Envelope Generator: attack shape, Sustain mode and
64    Percussive/Non-percussive modes handling
65  - Envelope Generator rates are two times slower now
66  - LFO amplitude (tremolo) and phase modulation (vibrato)
67  - rhythm sounds phase generation
68  - white noise generator (big thanks to Olivier Galibert for mentioning Berlekamp-Massey algorithm)
69  - corrected key on/off handling (the 'key' signal is ORed from three sources: FM, rhythm and CSM)
70  - funky details (like ignoring output of operator 1 in BD rhythm sound when connect == 1)
71 
72 12-28-2001 Acho A. Tang
73  - reflected Delta-T EOS status on Y8950 status port.
74  - fixed subscription range of attack/decay tables
75 
76 
77     To do:
78         add delay before key off in CSM mode (see CSMKeyControll)
79         verify volume of the FM part on the Y8950
80 */
81 
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <string.h>
85 #include <math.h>
86 #include <stdint.h>
87 #include <string>
88 //#include "driver.h"		/* use M.A.M.E. */
89 #include "opl.h"
90 
91 /* compiler dependence */
92 #ifndef OSD_CPU_H
93 #define OSD_CPU_H
94 #endif
95 
96 #ifndef PI
97 #define PI 3.14159265358979323846
98 #endif
99 
100 #ifdef _MSC_VER
101 #pragma warning (disable: 4244)
102 #endif
103 
104 
105 #define FREQ_SH         16  /* 16.16 fixed point (frequency calculations) */
106 #define EG_SH           16  /* 16.16 fixed point (EG timing)              */
107 #define LFO_SH          24  /*  8.24 fixed point (LFO calculations)       */
108 #define TIMER_SH        16  /* 16.16 fixed point (timers calculations)    */
109 
110 #define FREQ_MASK       ((1<<FREQ_SH)-1)
111 
112 /* envelope output entries */
113 #define ENV_BITS        10
114 #define ENV_LEN         (1<<ENV_BITS)
115 #define ENV_STEP        (128.0/ENV_LEN)
116 
117 #define MAX_ATT_INDEX   ((1<<(ENV_BITS-1))-1) /*511*/
118 #define MIN_ATT_INDEX   (0)
119 
120 /* sinwave entries */
121 #define SIN_BITS        10
122 #define SIN_LEN         (1<<SIN_BITS)
123 #define SIN_MASK        (SIN_LEN-1)
124 
125 #define TL_RES_LEN      (256)   /* 8 bits addressing (real chip) */
126 
127 
128 
129 /* register number to channel number , slot offset */
130 #define SLOT1 0
131 #define SLOT2 1
132 
133 /* Envelope Generator phases */
134 
135 #define EG_ATT          4
136 #define EG_DEC          3
137 #define EG_SUS          2
138 #define EG_REL          1
139 #define EG_OFF          0
140 
141 
142 #define OPL_CLOCK		3579545						// master clock (Hz)
143 #define OPL_RATE		49716						// sampling rate (Hz)
144 #define OPL_TIMERBASE	(OPL_CLOCK / 72.0)			// Timer base time (==sampling time)
145 #define OPL_FREQBASE	(OPL_TIMERBASE / OPL_RATE)	// frequency base
146 
147 
148 /* Saving is necessary for member of the 'R' mark for suspend/resume */
149 
150 struct OPL_SLOT
151 {
152 	uint32_t  ar;         /* attack rate: AR<<2           */
153 	uint32_t  dr;         /* decay rate:  DR<<2           */
154 	uint32_t  rr;         /* release rate:RR<<2           */
155 	uint8_t   KSR;        /* key scale rate               */
156 	uint8_t   ksl;        /* keyscale level               */
157 	uint8_t   ksr;        /* key scale rate: kcode>>KSR   */
158 	uint8_t   mul;        /* multiple: mul_tab[ML]        */
159 
160 	/* Phase Generator */
161 	uint32_t  Cnt;        /* frequency counter            */
162 	uint32_t  Incr;       /* frequency counter step       */
163 	uint8_t   FB;         /* feedback shift value         */
164 	int32_t   *connect1;  /* slot1 output pointer         */
165 	int32_t   op1_out[2]; /* slot1 output for feedback    */
166 	uint8_t   CON;        /* connection (algorithm) type  */
167 
168 	/* Envelope Generator */
169 	uint8_t   eg_type;    /* percussive/non-percussive mode */
170 	uint8_t   state;      /* phase type                   */
171 	uint32_t  TL;         /* total level: TL << 2         */
172 	int32_t   TLL;        /* adjusted now TL              */
173 	int32_t   volume;     /* envelope counter             */
174 	uint32_t  sl;         /* sustain level: sl_tab[SL]    */
175 	uint8_t   eg_sh_ar;   /* (attack state)               */
176 	uint8_t   eg_sel_ar;  /* (attack state)               */
177 	uint8_t   eg_sh_dr;   /* (decay state)                */
178 	uint8_t   eg_sel_dr;  /* (decay state)                */
179 	uint8_t   eg_sh_rr;   /* (release state)              */
180 	uint8_t   eg_sel_rr;  /* (release state)              */
181 	uint32_t  key;        /* 0 = KEY OFF, >0 = KEY ON     */
182 
183 	/* LFO */
184 	uint32_t  AMmask;     /* LFO Amplitude Modulation enable mask */
185 	uint8_t   vib;        /* LFO Phase Modulation enable flag (active high)*/
186 
187 	/* waveform select */
188 	uint16_t  wavetable;
189 };
190 
191 struct OPL_CH
192 {
193 	OPL_SLOT SLOT[2];
194 	/* phase generator state */
195 	uint32_t  block_fnum; /* block+fnum                   */
196 	uint32_t  fc;         /* Freq. Increment base         */
197 	uint32_t  ksl_base;   /* KeyScaleLevel Base step      */
198 	uint8_t   kcode;      /* key code (for key scaling)   */
199 	float	LeftVol;	/* volumes for stereo panning	*/
200 	float	RightVol;
201 };
202 
203 /* OPL state */
204 struct FM_OPL
205 {
206 	/* FM channel slots */
207 	OPL_CH  P_CH[9];                /* OPL/OPL2 chips have 9 channels*/
208 
209 	uint32_t  eg_cnt;                 /* global envelope generator counter    */
210 	uint32_t  eg_timer;               /* global envelope generator counter works at frequency = chipclock/72 */
211 	uint32_t  eg_timer_add;           /* step of eg_timer                     */
212 	uint32_t  eg_timer_overflow;      /* envelope generator timer overflows every 1 sample (on real chip) */
213 
214 	uint8_t   rhythm;                 /* Rhythm mode                  */
215 
216 	uint32_t  fn_tab[1024];           /* fnumber->increment counter   */
217 
218 	/* LFO */
219 
220 	uint8_t   lfo_am_depth;
221 	uint8_t   lfo_pm_depth_range;
222 	uint32_t  lfo_am_cnt;
223 	uint32_t  lfo_am_inc;
224 	uint32_t  lfo_pm_cnt;
225 	uint32_t  lfo_pm_inc;
226 
227 	uint32_t  noise_rng;              /* 23 bit noise shift register  */
228 	uint32_t  noise_p;                /* current noise 'phase'        */
229 	uint32_t  noise_f;                /* current noise period         */
230 
231 	uint8_t   wavesel;                /* waveform select enable flag  */
232 
233 	int		T[2];					/* timer counters				*/
234 	uint8_t   st[2];                  /* timer enable                 */
235 
236 
237 	uint8_t address;                  /* address register             */
238 	uint8_t status;                   /* status flag                  */
239 	uint8_t statusmask;               /* status mask                  */
240 	uint8_t mode;                     /* Reg.08 : CSM,notesel,etc.    */
241 
242 	bool IsStereo;					/* Write stereo output			*/
243 };
244 
245 
246 
247 /* mapping of register number (offset) to slot number used by the emulator */
248 static const int slot_array[32]=
249 {
250 	 0, 2, 4, 1, 3, 5,-1,-1,
251 	 6, 8,10, 7, 9,11,-1,-1,
252 	12,14,16,13,15,17,-1,-1,
253 	-1,-1,-1,-1,-1,-1,-1,-1
254 };
255 
256 /* key scale level */
257 /* table is 3dB/octave , DV converts this into 6dB/octave */
258 /* 0.1875 is bit 0 weight of the envelope counter (volume) expressed in the 'decibel' scale */
259 #define DV (0.1875/2.0)
260 static const uint32_t ksl_tab[8*16]=
261 {
262 	/* OCT 0 */
263 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
264 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
265 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
266 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
267 	/* OCT 1 */
268 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
269 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
270 	 uint32_t(0.000/DV), uint32_t(0.750/DV), uint32_t(1.125/DV), uint32_t(1.500/DV),
271 	 uint32_t(1.875/DV), uint32_t(2.250/DV), uint32_t(2.625/DV), uint32_t(3.000/DV),
272 	/* OCT 2 */
273 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV),
274 	 uint32_t(0.000/DV), uint32_t(1.125/DV), uint32_t(1.875/DV), uint32_t(2.625/DV),
275 	 uint32_t(3.000/DV), uint32_t(3.750/DV), uint32_t(4.125/DV), uint32_t(4.500/DV),
276 	 uint32_t(4.875/DV), uint32_t(5.250/DV), uint32_t(5.625/DV), uint32_t(6.000/DV),
277 	/* OCT 3 */
278 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(1.875/DV),
279 	 uint32_t(3.000/DV), uint32_t(4.125/DV), uint32_t(4.875/DV), uint32_t(5.625/DV),
280 	 uint32_t(6.000/DV), uint32_t(6.750/DV), uint32_t(7.125/DV), uint32_t(7.500/DV),
281 	 uint32_t(7.875/DV), uint32_t(8.250/DV), uint32_t(8.625/DV), uint32_t(9.000/DV),
282 	/* OCT 4 */
283 	 uint32_t(0.000/DV), uint32_t(0.000/DV), uint32_t(3.000/DV), uint32_t(4.875/DV),
284 	 uint32_t(6.000/DV), uint32_t(7.125/DV), uint32_t(7.875/DV), uint32_t(8.625/DV),
285 	 uint32_t(9.000/DV), uint32_t(9.750/DV),uint32_t(10.125/DV),uint32_t(10.500/DV),
286 	uint32_t(10.875/DV),uint32_t(11.250/DV),uint32_t(11.625/DV),uint32_t(12.000/DV),
287 	/* OCT 5 */
288 	 uint32_t(0.000/DV), uint32_t(3.000/DV), uint32_t(6.000/DV), uint32_t(7.875/DV),
289 	 uint32_t(9.000/DV),uint32_t(10.125/DV),uint32_t(10.875/DV),uint32_t(11.625/DV),
290 	uint32_t(12.000/DV),uint32_t(12.750/DV),uint32_t(13.125/DV),uint32_t(13.500/DV),
291 	uint32_t(13.875/DV),uint32_t(14.250/DV),uint32_t(14.625/DV),uint32_t(15.000/DV),
292 	/* OCT 6 */
293 	 uint32_t(0.000/DV), uint32_t(6.000/DV), uint32_t(9.000/DV),uint32_t(10.875/DV),
294 	uint32_t(12.000/DV),uint32_t(13.125/DV),uint32_t(13.875/DV),uint32_t(14.625/DV),
295 	uint32_t(15.000/DV),uint32_t(15.750/DV),uint32_t(16.125/DV),uint32_t(16.500/DV),
296 	uint32_t(16.875/DV),uint32_t(17.250/DV),uint32_t(17.625/DV),uint32_t(18.000/DV),
297 	/* OCT 7 */
298 	 uint32_t(0.000/DV), uint32_t(9.000/DV),uint32_t(12.000/DV),uint32_t(13.875/DV),
299 	uint32_t(15.000/DV),uint32_t(16.125/DV),uint32_t(16.875/DV),uint32_t(17.625/DV),
300 	uint32_t(18.000/DV),uint32_t(18.750/DV),uint32_t(19.125/DV),uint32_t(19.500/DV),
301 	uint32_t(19.875/DV),uint32_t(20.250/DV),uint32_t(20.625/DV),uint32_t(21.000/DV)
302 };
303 #undef DV
304 
305 /* 0 / 3.0 / 1.5 / 6.0 dB/OCT */
306 static const uint32_t ksl_shift[4] = { 31, 1, 2, 0 };
307 
308 
309 /* sustain level table (3dB per step) */
310 /* 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,93 (dB)*/
311 #define SC(db) (uint32_t) ( db * (2.0/ENV_STEP) )
312 static const uint32_t sl_tab[16]={
313 	SC( 0),SC( 1),SC( 2),SC(3 ),SC(4 ),SC(5 ),SC(6 ),SC( 7),
314 	SC( 8),SC( 9),SC(10),SC(11),SC(12),SC(13),SC(14),SC(31)
315 };
316 #undef SC
317 
318 
319 #define RATE_STEPS (8)
320 static const unsigned char eg_inc[15*RATE_STEPS]={
321 /*cycle:0 1  2 3  4 5  6 7*/
322 
323 /* 0 */ 0,1, 0,1, 0,1, 0,1, /* rates 00..12 0 (increment by 0 or 1) */
324 /* 1 */ 0,1, 0,1, 1,1, 0,1, /* rates 00..12 1 */
325 /* 2 */ 0,1, 1,1, 0,1, 1,1, /* rates 00..12 2 */
326 /* 3 */ 0,1, 1,1, 1,1, 1,1, /* rates 00..12 3 */
327 
328 /* 4 */ 1,1, 1,1, 1,1, 1,1, /* rate 13 0 (increment by 1) */
329 /* 5 */ 1,1, 1,2, 1,1, 1,2, /* rate 13 1 */
330 /* 6 */ 1,2, 1,2, 1,2, 1,2, /* rate 13 2 */
331 /* 7 */ 1,2, 2,2, 1,2, 2,2, /* rate 13 3 */
332 
333 /* 8 */ 2,2, 2,2, 2,2, 2,2, /* rate 14 0 (increment by 2) */
334 /* 9 */ 2,2, 2,4, 2,2, 2,4, /* rate 14 1 */
335 /*10 */ 2,4, 2,4, 2,4, 2,4, /* rate 14 2 */
336 /*11 */ 2,4, 4,4, 2,4, 4,4, /* rate 14 3 */
337 
338 /*12 */ 4,4, 4,4, 4,4, 4,4, /* rates 15 0, 15 1, 15 2, 15 3 (increment by 4) */
339 /*13 */ 8,8, 8,8, 8,8, 8,8, /* rates 15 2, 15 3 for attack */
340 /*14 */ 0,0, 0,0, 0,0, 0,0, /* infinity rates for attack and decay(s) */
341 };
342 
343 
344 #define O(a) (a*RATE_STEPS)
345 
346 /*note that there is no O(13) in this table - it's directly in the code */
347 static const unsigned char eg_rate_select[16+64+16]={   /* Envelope Generator rates (16 + 64 rates + 16 RKS) */
348 /* 16 infinite time rates */
349 O(14),O(14),O(14),O(14),O(14),O(14),O(14),O(14),
350 O(14),O(14),O(14),O(14),O(14),O(14),O(14),O(14),
351 
352 /* rates 00-12 */
353 O( 0),O( 1),O( 2),O( 3),
354 O( 0),O( 1),O( 2),O( 3),
355 O( 0),O( 1),O( 2),O( 3),
356 O( 0),O( 1),O( 2),O( 3),
357 O( 0),O( 1),O( 2),O( 3),
358 O( 0),O( 1),O( 2),O( 3),
359 O( 0),O( 1),O( 2),O( 3),
360 O( 0),O( 1),O( 2),O( 3),
361 O( 0),O( 1),O( 2),O( 3),
362 O( 0),O( 1),O( 2),O( 3),
363 O( 0),O( 1),O( 2),O( 3),
364 O( 0),O( 1),O( 2),O( 3),
365 O( 0),O( 1),O( 2),O( 3),
366 
367 /* rate 13 */
368 O( 4),O( 5),O( 6),O( 7),
369 
370 /* rate 14 */
371 O( 8),O( 9),O(10),O(11),
372 
373 /* rate 15 */
374 O(12),O(12),O(12),O(12),
375 
376 /* 16 dummy rates (same as 15 3) */
377 O(12),O(12),O(12),O(12),O(12),O(12),O(12),O(12),
378 O(12),O(12),O(12),O(12),O(12),O(12),O(12),O(12),
379 
380 };
381 #undef O
382 
383 /*rate  0,    1,    2,    3,   4,   5,   6,  7,  8,  9,  10, 11, 12, 13, 14, 15 */
384 /*shift 12,   11,   10,   9,   8,   7,   6,  5,  4,  3,  2,  1,  0,  0,  0,  0  */
385 /*mask  4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7,  3,  1,  0,  0,  0,  0  */
386 
387 #define O(a) (a*1)
388 static const unsigned char eg_rate_shift[16+64+16]={    /* Envelope Generator counter shifts (16 + 64 rates + 16 RKS) */
389 /* 16 infinite time rates */
390 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
391 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
392 
393 /* rates 00-12 */
394 O(12),O(12),O(12),O(12),
395 O(11),O(11),O(11),O(11),
396 O(10),O(10),O(10),O(10),
397 O( 9),O( 9),O( 9),O( 9),
398 O( 8),O( 8),O( 8),O( 8),
399 O( 7),O( 7),O( 7),O( 7),
400 O( 6),O( 6),O( 6),O( 6),
401 O( 5),O( 5),O( 5),O( 5),
402 O( 4),O( 4),O( 4),O( 4),
403 O( 3),O( 3),O( 3),O( 3),
404 O( 2),O( 2),O( 2),O( 2),
405 O( 1),O( 1),O( 1),O( 1),
406 O( 0),O( 0),O( 0),O( 0),
407 
408 /* rate 13 */
409 O( 0),O( 0),O( 0),O( 0),
410 
411 /* rate 14 */
412 O( 0),O( 0),O( 0),O( 0),
413 
414 /* rate 15 */
415 O( 0),O( 0),O( 0),O( 0),
416 
417 /* 16 dummy rates (same as 15 3) */
418 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
419 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
420 
421 };
422 #undef O
423 
424 
425 /* multiple table */
426 #define ML 2
427 static const uint8_t mul_tab[16]= {
428 /* 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,10,12,12,15,15 */
429    uint8_t(0.50*ML), uint8_t(1.00*ML), uint8_t(2.00*ML), uint8_t(3.00*ML), uint8_t(4.00*ML), uint8_t(5.00*ML), uint8_t(6.00*ML), uint8_t(7.00*ML),
430    uint8_t(8.00*ML), uint8_t(9.00*ML),uint8_t(10.00*ML),uint8_t(10.00*ML),uint8_t(12.00*ML),uint8_t(12.00*ML),uint8_t(15.00*ML),uint8_t(15.00*ML)
431 };
432 #undef ML
433 
434 /*  TL_TAB_LEN is calculated as:
435 *   12 - sinus amplitude bits     (Y axis)
436 *   2  - sinus sign bit           (Y axis)
437 *   TL_RES_LEN - sinus resolution (X axis)
438 */
439 #define TL_TAB_LEN (12*2*TL_RES_LEN)
440 static signed int tl_tab[TL_TAB_LEN];
441 
442 #define ENV_QUIET       (TL_TAB_LEN>>4)
443 
444 /* sin waveform table in 'decibel' scale */
445 /* four waveforms on OPL2 type chips */
446 static unsigned int sin_tab[SIN_LEN * 4];
447 
448 
449 /* LFO Amplitude Modulation table (verified on real YM3812)
450    27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples
451 
452    Length: 210 elements.
453 
454     Each of the elements has to be repeated
455     exactly 64 times (on 64 consecutive samples).
456     The whole table takes: 64 * 210 = 13440 samples.
457 
458     When AM = 1 data is used directly
459     When AM = 0 data is divided by 4 before being used (losing precision is important)
460 */
461 
462 #define LFO_AM_TAB_ELEMENTS 210
463 
464 static const uint8_t lfo_am_table[LFO_AM_TAB_ELEMENTS] = {
465 0,0,0,0,0,0,0,
466 1,1,1,1,
467 2,2,2,2,
468 3,3,3,3,
469 4,4,4,4,
470 5,5,5,5,
471 6,6,6,6,
472 7,7,7,7,
473 8,8,8,8,
474 9,9,9,9,
475 10,10,10,10,
476 11,11,11,11,
477 12,12,12,12,
478 13,13,13,13,
479 14,14,14,14,
480 15,15,15,15,
481 16,16,16,16,
482 17,17,17,17,
483 18,18,18,18,
484 19,19,19,19,
485 20,20,20,20,
486 21,21,21,21,
487 22,22,22,22,
488 23,23,23,23,
489 24,24,24,24,
490 25,25,25,25,
491 26,26,26,
492 25,25,25,25,
493 24,24,24,24,
494 23,23,23,23,
495 22,22,22,22,
496 21,21,21,21,
497 20,20,20,20,
498 19,19,19,19,
499 18,18,18,18,
500 17,17,17,17,
501 16,16,16,16,
502 15,15,15,15,
503 14,14,14,14,
504 13,13,13,13,
505 12,12,12,12,
506 11,11,11,11,
507 10,10,10,10,
508 9,9,9,9,
509 8,8,8,8,
510 7,7,7,7,
511 6,6,6,6,
512 5,5,5,5,
513 4,4,4,4,
514 3,3,3,3,
515 2,2,2,2,
516 1,1,1,1
517 };
518 
519 /* LFO Phase Modulation table (verified on real YM3812) */
520 static const int8_t lfo_pm_table[8*8*2] = {
521 /* FNUM2/FNUM = 00 0xxxxxxx (0x0000) */
522 0, 0, 0, 0, 0, 0, 0, 0, /*LFO PM depth = 0*/
523 0, 0, 0, 0, 0, 0, 0, 0, /*LFO PM depth = 1*/
524 
525 /* FNUM2/FNUM = 00 1xxxxxxx (0x0080) */
526 0, 0, 0, 0, 0, 0, 0, 0, /*LFO PM depth = 0*/
527 1, 0, 0, 0,-1, 0, 0, 0, /*LFO PM depth = 1*/
528 
529 /* FNUM2/FNUM = 01 0xxxxxxx (0x0100) */
530 1, 0, 0, 0,-1, 0, 0, 0, /*LFO PM depth = 0*/
531 2, 1, 0,-1,-2,-1, 0, 1, /*LFO PM depth = 1*/
532 
533 /* FNUM2/FNUM = 01 1xxxxxxx (0x0180) */
534 1, 0, 0, 0,-1, 0, 0, 0, /*LFO PM depth = 0*/
535 3, 1, 0,-1,-3,-1, 0, 1, /*LFO PM depth = 1*/
536 
537 /* FNUM2/FNUM = 10 0xxxxxxx (0x0200) */
538 2, 1, 0,-1,-2,-1, 0, 1, /*LFO PM depth = 0*/
539 4, 2, 0,-2,-4,-2, 0, 2, /*LFO PM depth = 1*/
540 
541 /* FNUM2/FNUM = 10 1xxxxxxx (0x0280) */
542 2, 1, 0,-1,-2,-1, 0, 1, /*LFO PM depth = 0*/
543 5, 2, 0,-2,-5,-2, 0, 2, /*LFO PM depth = 1*/
544 
545 /* FNUM2/FNUM = 11 0xxxxxxx (0x0300) */
546 3, 1, 0,-1,-3,-1, 0, 1, /*LFO PM depth = 0*/
547 6, 3, 0,-3,-6,-3, 0, 3, /*LFO PM depth = 1*/
548 
549 /* FNUM2/FNUM = 11 1xxxxxxx (0x0380) */
550 3, 1, 0,-1,-3,-1, 0, 1, /*LFO PM depth = 0*/
551 7, 3, 0,-3,-7,-3, 0, 3  /*LFO PM depth = 1*/
552 };
553 
554 
555 
556 /* work table */
557 static signed int phase_modulation;		/* phase modulation input (SLOT 2) */
558 static signed int output;
559 
560 static uint32_t	LFO_AM;
561 static int32_t	LFO_PM;
562 
563 static bool CalcVoice (FM_OPL *OPL, int voice, float *buffer, int length);
564 static bool CalcRhythm (FM_OPL *OPL, float *buffer, int length);
565 
566 
567 
568 /* status set and IRQ handling */
OPL_STATUS_SET(FM_OPL * OPL,int flag)569 static inline void OPL_STATUS_SET(FM_OPL *OPL,int flag)
570 {
571 	/* set status flag */
572 	OPL->status |= flag;
573 	if(!(OPL->status & 0x80))
574 	{
575 		if(OPL->status & OPL->statusmask)
576 		{   /* IRQ on */
577 			OPL->status |= 0x80;
578 		}
579 	}
580 }
581 
582 /* status reset and IRQ handling */
OPL_STATUS_RESET(FM_OPL * OPL,int flag)583 static inline void OPL_STATUS_RESET(FM_OPL *OPL,int flag)
584 {
585 	/* reset status flag */
586 	OPL->status &=~flag;
587 	if((OPL->status & 0x80))
588 	{
589 		if (!(OPL->status & OPL->statusmask) )
590 		{
591 			OPL->status &= 0x7f;
592 		}
593 	}
594 }
595 
596 /* IRQ mask set */
OPL_STATUSMASK_SET(FM_OPL * OPL,int flag)597 static inline void OPL_STATUSMASK_SET(FM_OPL *OPL,int flag)
598 {
599 	OPL->statusmask = flag;
600 	/* IRQ handling check */
601 	OPL_STATUS_SET(OPL,0);
602 	OPL_STATUS_RESET(OPL,0);
603 }
604 
605 
606 /* advance LFO to next sample */
advance_lfo(FM_OPL * OPL)607 static inline void advance_lfo(FM_OPL *OPL)
608 {
609 	uint8_t tmp;
610 
611 	/* LFO */
612 	OPL->lfo_am_cnt += OPL->lfo_am_inc;
613 	if (OPL->lfo_am_cnt >= (uint32_t)(LFO_AM_TAB_ELEMENTS<<LFO_SH) )	/* lfo_am_table is 210 elements long */
614 		OPL->lfo_am_cnt -= (LFO_AM_TAB_ELEMENTS<<LFO_SH);
615 
616 	tmp = lfo_am_table[ OPL->lfo_am_cnt >> LFO_SH ];
617 
618 	if (OPL->lfo_am_depth)
619 		LFO_AM = tmp;
620 	else
621 		LFO_AM = tmp>>2;
622 
623 	OPL->lfo_pm_cnt += OPL->lfo_pm_inc;
624 	LFO_PM = ((OPL->lfo_pm_cnt>>LFO_SH) & 7) | OPL->lfo_pm_depth_range;
625 }
626 
627 /* advance to next sample */
advance(FM_OPL * OPL,int loch,int hich)628 static inline void advance(FM_OPL *OPL, int loch, int hich)
629 {
630 	OPL_CH *CH;
631 	OPL_SLOT *op;
632 	int i;
633 
634 	OPL->eg_timer += OPL->eg_timer_add;
635 	loch *= 2;
636 	hich *= 2;
637 
638 	while (OPL->eg_timer >= OPL->eg_timer_overflow)
639 	{
640 		OPL->eg_timer -= OPL->eg_timer_overflow;
641 
642 		OPL->eg_cnt++;
643 
644 		for (i = loch; i <= hich + 1; i++)
645 		{
646 			CH  = &OPL->P_CH[i/2];
647 			op  = &CH->SLOT[i&1];
648 
649 			/* Envelope Generator */
650 			switch(op->state)
651 			{
652 			case EG_ATT:		/* attack phase */
653 				if ( !(OPL->eg_cnt & ((1<<op->eg_sh_ar)-1) ) )
654 				{
655 					op->volume += (~op->volume *
656 	                        		           (eg_inc[op->eg_sel_ar + ((OPL->eg_cnt>>op->eg_sh_ar)&7)])
657         			                          ) >>3;
658 
659 					if (op->volume <= MIN_ATT_INDEX)
660 					{
661 						op->volume = MIN_ATT_INDEX;
662 						op->state = EG_DEC;
663 					}
664 
665 				}
666 			break;
667 
668 			case EG_DEC:    /* decay phase */
669 				if ( !(OPL->eg_cnt & ((1<<op->eg_sh_dr)-1) ) )
670 				{
671 					op->volume += eg_inc[op->eg_sel_dr + ((OPL->eg_cnt>>op->eg_sh_dr)&7)];
672 
673 					if ( op->volume >= (int32_t)op->sl )
674 						op->state = EG_SUS;
675 
676 				}
677 			break;
678 
679 			case EG_SUS:    /* sustain phase */
680 
681 				/* this is important behaviour:
682 				one can change percusive/non-percussive modes on the fly and
683 				the chip will remain in sustain phase - verified on real YM3812 */
684 
685 				if(op->eg_type)     /* non-percussive mode */
686 				{
687 									/* do nothing */
688 				}
689 				else                /* percussive mode */
690 				{
691 					/* during sustain phase chip adds Release Rate (in percussive mode) */
692 					if ( !(OPL->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
693 					{
694 						op->volume += eg_inc[op->eg_sel_rr + ((OPL->eg_cnt>>op->eg_sh_rr)&7)];
695 
696 						if ( op->volume >= MAX_ATT_INDEX )
697 							op->volume = MAX_ATT_INDEX;
698 					}
699 					/* else do nothing in sustain phase */
700 				}
701 			break;
702 
703 			case EG_REL:    /* release phase */
704 				if ( !(OPL->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
705 				{
706 					op->volume += eg_inc[op->eg_sel_rr + ((OPL->eg_cnt>>op->eg_sh_rr)&7)];
707 
708 					if ( op->volume >= MAX_ATT_INDEX )
709 					{
710 						op->volume = MAX_ATT_INDEX;
711 						op->state = EG_OFF;
712 					}
713 
714 				}
715 			break;
716 
717 			default:
718 			break;
719 			}
720 
721 			/* Phase Generator */
722 			if(op->vib)
723 			{
724 				uint8_t block;
725 				unsigned int block_fnum = CH->block_fnum;
726 
727 				unsigned int fnum_lfo   = (block_fnum&0x0380) >> 7;
728 
729 				signed int lfo_fn_table_index_offset = lfo_pm_table[LFO_PM + 16*fnum_lfo ];
730 
731 				if (lfo_fn_table_index_offset)	/* LFO phase modulation active */
732 				{
733 					block_fnum += lfo_fn_table_index_offset;
734 					block = (block_fnum&0x1c00) >> 10;
735 					op->Cnt += (OPL->fn_tab[block_fnum&0x03ff] >> (7-block)) * op->mul;
736 				}
737 				else	/* LFO phase modulation  = zero */
738 				{
739 					op->Cnt += op->Incr;
740 				}
741 			}
742 			else	/* LFO phase modulation disabled for this operator */
743 			{
744 				op->Cnt += op->Incr;
745 			}
746 		}
747 	}
748 }
749 
advance_noise(FM_OPL * OPL)750 static inline void advance_noise(FM_OPL *OPL)
751 {
752 	int i;
753 
754 	/*  The Noise Generator of the YM3812 is 23-bit shift register.
755 	*   Period is equal to 2^23-2 samples.
756 	*   Register works at sampling frequency of the chip, so output
757 	*   can change on every sample.
758 	*
759 	*   Output of the register and input to the bit 22 is:
760 	*   bit0 XOR bit14 XOR bit15 XOR bit22
761 	*
762 	*   Simply use bit 22 as the noise output.
763 	*/
764 
765 	OPL->noise_p += OPL->noise_f;
766 	i = OPL->noise_p >> FREQ_SH;        /* number of events (shifts of the shift register) */
767 	OPL->noise_p &= FREQ_MASK;
768 	while (i)
769 	{
770 		/*
771 		uint32_t j;
772 		j = ( (OPL->noise_rng) ^ (OPL->noise_rng>>14) ^ (OPL->noise_rng>>15) ^ (OPL->noise_rng>>22) ) & 1;
773 		OPL->noise_rng = (j<<22) | (OPL->noise_rng>>1);
774 		*/
775 
776 		/*
777 		    Instead of doing all the logic operations above, we
778 		    use a trick here (and use bit 0 as the noise output).
779 		    The difference is only that the noise bit changes one
780 		    step ahead. This doesn't matter since we don't know
781 			what is real state of the noise_rng after the reset.
782 		*/
783 
784 		if (OPL->noise_rng & 1) OPL->noise_rng ^= 0x800302;
785 		OPL->noise_rng >>= 1;
786 
787 		i--;
788 	}
789 }
790 
791 
op_calc(uint32_t phase,unsigned int env,signed int pm,unsigned int wave_tab)792 static inline signed int op_calc(uint32_t phase, unsigned int env, signed int pm, unsigned int wave_tab)
793 {
794 	uint32_t p;
795 
796 	p = (env<<4) + sin_tab[wave_tab + ((((signed int)((phase & ~FREQ_MASK) + (pm<<16))) >> FREQ_SH ) & SIN_MASK) ];
797 
798 	if (p >= TL_TAB_LEN)
799 		return 0;
800 	return tl_tab[p];
801 }
802 
op_calc1(uint32_t phase,unsigned int env,signed int pm,unsigned int wave_tab)803 static inline signed int op_calc1(uint32_t phase, unsigned int env, signed int pm, unsigned int wave_tab)
804 {
805 	uint32_t p;
806 
807 	p = (env<<4) + sin_tab[wave_tab + ((((signed int)((phase & ~FREQ_MASK) + pm      )) >> FREQ_SH ) & SIN_MASK) ];
808 
809 	if (p >= TL_TAB_LEN)
810 		return 0;
811 	return tl_tab[p];
812 }
813 
814 
815 #define volume_calc(OP) ((OP)->TLL + ((uint32_t)(OP)->volume) + (LFO_AM & (OP)->AMmask))
816 
817 /* calculate output */
OPL_CALC_CH(OPL_CH * CH)818 static inline float OPL_CALC_CH( OPL_CH *CH )
819 {
820 	OPL_SLOT *SLOT;
821 	unsigned int env;
822 	signed int out;
823 
824 	phase_modulation = 0;
825 
826 	/* SLOT 1 */
827 	SLOT = &CH->SLOT[SLOT1];
828 	env  = volume_calc(SLOT);
829 	out  = SLOT->op1_out[0] + SLOT->op1_out[1];
830 	SLOT->op1_out[0] = SLOT->op1_out[1];
831 	*SLOT->connect1 += SLOT->op1_out[0];
832 	SLOT->op1_out[1] = 0;
833 	if( env < ENV_QUIET )
834 	{
835 		if (!SLOT->FB)
836 			out = 0;
837 		SLOT->op1_out[1] = op_calc1(SLOT->Cnt, env, (out<<SLOT->FB), SLOT->wavetable );
838 	}
839 
840 	/* SLOT 2 */
841 	SLOT++;
842 	env = volume_calc(SLOT);
843 	if( env < ENV_QUIET )
844 	{
845 		output += op_calc(SLOT->Cnt, env, phase_modulation, SLOT->wavetable);
846 		/* [RH] Convert to floating point. */
847 		return float(output) / 10240;
848 	}
849 	return 0;
850 }
851 
852 /*
853     operators used in the rhythm sounds generation process:
854 
855     Envelope Generator:
856 
857 channel  operator  register number   Bass  High  Snare Tom  Top
858 / slot   number    TL ARDR SLRR Wave Drum  Hat   Drum  Tom  Cymbal
859  6 / 0   12        50  70   90   f0  +
860  6 / 1   15        53  73   93   f3  +
861  7 / 0   13        51  71   91   f1        +
862  7 / 1   16        54  74   94   f4              +
863  8 / 0   14        52  72   92   f2                    +
864  8 / 1   17        55  75   95   f5                          +
865 
866 	Phase Generator:
867 
868 channel  operator  register number   Bass  High  Snare Tom  Top
869 / slot   number    MULTIPLE          Drum  Hat   Drum  Tom  Cymbal
870  6 / 0   12        30                +
871  6 / 1   15        33                +
872  7 / 0   13        31                      +     +           +
873  7 / 1   16        34                -----  n o t  u s e d -----
874  8 / 0   14        32                                  +
875  8 / 1   17        35                      +                 +
876 
877 channel  operator  register number   Bass  High  Snare Tom  Top
878 number   number    BLK/FNUM2 FNUM    Drum  Hat   Drum  Tom  Cymbal
879    6     12,15     B6        A6      +
880 
881    7     13,16     B7        A7            +     +           +
882 
883    8     14,17     B8        A8            +           +     +
884 
885 */
886 
887 /* calculate rhythm */
888 
OPL_CALC_RH(OPL_CH * CH,unsigned int noise)889 static inline void OPL_CALC_RH( OPL_CH *CH, unsigned int noise )
890 {
891 	OPL_SLOT *SLOT;
892 	signed int out;
893 	unsigned int env;
894 
895 
896 	/* Bass Drum (verified on real YM3812):
897 	  - depends on the channel 6 'connect' register:
898 	      when connect = 0 it works the same as in normal (non-rhythm) mode (op1->op2->out)
899 	      when connect = 1 _only_ operator 2 is present on output (op2->out), operator 1 is ignored
900 	  - output sample always is multiplied by 2
901 	*/
902 
903 	phase_modulation = 0;
904 	/* SLOT 1 */
905 	SLOT = &CH[6].SLOT[SLOT1];
906 	env = volume_calc(SLOT);
907 
908 	out = SLOT->op1_out[0] + SLOT->op1_out[1];
909 	SLOT->op1_out[0] = SLOT->op1_out[1];
910 
911 	if (!SLOT->CON)
912 		phase_modulation = SLOT->op1_out[0];
913 	/* else ignore output of operator 1 */
914 
915 	SLOT->op1_out[1] = 0;
916 	if( env < ENV_QUIET )
917 	{
918 		if (!SLOT->FB)
919 			out = 0;
920 		SLOT->op1_out[1] = op_calc1(SLOT->Cnt, env, (out<<SLOT->FB), SLOT->wavetable );
921 	}
922 
923 	/* SLOT 2 */
924 	SLOT++;
925 	env = volume_calc(SLOT);
926 	if( env < ENV_QUIET )
927 		output += op_calc(SLOT->Cnt, env, phase_modulation, SLOT->wavetable) * 2;
928 
929 
930 	/* Phase generation is based on: */
931 	/* HH  (13) channel 7->slot 1 combined with channel 8->slot 2 (same combination as TOP CYMBAL but different output phases) */
932 	/* SD  (16) channel 7->slot 1 */
933 	/* TOM (14) channel 8->slot 1 */
934 	/* TOP (17) channel 7->slot 1 combined with channel 8->slot 2 (same combination as HIGH HAT but different output phases) */
935 
936 	/* Envelope generation based on: */
937 	/* HH  channel 7->slot1 */
938 	/* SD  channel 7->slot2 */
939 	/* TOM channel 8->slot1 */
940 	/* TOP channel 8->slot2 */
941 
942 
943 	/* The following formulas can be well optimized.
944 	   I leave them in direct form for now (in case I've missed something).
945 	*/
946 
947 	/* High Hat (verified on real YM3812) */
948 	env = volume_calc(&CH[7].SLOT[SLOT1]);
949 	if( env < ENV_QUIET )
950 	{
951 
952 		/* high hat phase generation:
953 			phase = d0 or 234 (based on frequency only)
954 			phase = 34 or 2d0 (based on noise)
955 		*/
956 
957 		/* base frequency derived from operator 1 in channel 7 */
958 		unsigned char bit7 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>7)&1;
959 		unsigned char bit3 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>3)&1;
960 		unsigned char bit2 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>2)&1;
961 
962 		unsigned char res1 = (bit2 ^ bit7) | bit3;
963 
964 		/* when res1 = 0 phase = 0x000 | 0xd0; */
965 		/* when res1 = 1 phase = 0x200 | (0xd0>>2); */
966 		uint32_t phase = res1 ? (0x200|(0xd0>>2)) : 0xd0;
967 
968 		/* enable gate based on frequency of operator 2 in channel 8 */
969 		unsigned char bit5e= ((CH[8].SLOT[SLOT2].Cnt>>FREQ_SH)>>5)&1;
970 		unsigned char bit3e= ((CH[8].SLOT[SLOT2].Cnt>>FREQ_SH)>>3)&1;
971 
972 		unsigned char res2 = (bit3e ^ bit5e);
973 
974 		/* when res2 = 0 pass the phase from calculation above (res1); */
975 		/* when res2 = 1 phase = 0x200 | (0xd0>>2); */
976 		if (res2)
977 			phase = (0x200|(0xd0>>2));
978 
979 
980 		/* when phase & 0x200 is set and noise=1 then phase = 0x200|0xd0 */
981 		/* when phase & 0x200 is set and noise=0 then phase = 0x200|(0xd0>>2), ie no change */
982 		if (phase&0x200)
983 		{
984 			if (noise)
985 				phase = 0x200|0xd0;
986 		}
987 		else
988 		/* when phase & 0x200 is clear and noise=1 then phase = 0xd0>>2 */
989 		/* when phase & 0x200 is clear and noise=0 then phase = 0xd0, ie no change */
990 		{
991 			if (noise)
992 				phase = 0xd0>>2;
993 		}
994 
995 		output += op_calc(phase<<FREQ_SH, env, 0, CH[7].SLOT[SLOT1].wavetable) * 2;
996 	}
997 
998 	/* Snare Drum (verified on real YM3812) */
999 	env = volume_calc(&CH[7].SLOT[SLOT2]);
1000 	if( env < ENV_QUIET )
1001 	{
1002 		/* base frequency derived from operator 1 in channel 7 */
1003 		unsigned char bit8 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>8)&1;
1004 
1005 		/* when bit8 = 0 phase = 0x100; */
1006 		/* when bit8 = 1 phase = 0x200; */
1007 		uint32_t phase = bit8 ? 0x200 : 0x100;
1008 
1009 		/* Noise bit XOR'es phase by 0x100 */
1010 		/* when noisebit = 0 pass the phase from calculation above */
1011 		/* when noisebit = 1 phase ^= 0x100; */
1012 		/* in other words: phase ^= (noisebit<<8); */
1013 		if (noise)
1014 			phase ^= 0x100;
1015 
1016 		output += op_calc(phase<<FREQ_SH, env, 0, CH[7].SLOT[SLOT2].wavetable) * 2;
1017 	}
1018 
1019 	/* Tom Tom (verified on real YM3812) */
1020 	env = volume_calc(&CH[8].SLOT[SLOT1]);
1021 	if( env < ENV_QUIET )
1022 		output += op_calc(CH[8].SLOT[SLOT1].Cnt, env, 0, CH[8].SLOT[SLOT2].wavetable) * 2;
1023 
1024 	/* Top Cymbal (verified on real YM3812) */
1025 	env = volume_calc(&CH[8].SLOT[SLOT2]);
1026 	if( env < ENV_QUIET )
1027 	{
1028 		/* base frequency derived from operator 1 in channel 7 */
1029 		unsigned char bit7 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>7)&1;
1030 		unsigned char bit3 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>3)&1;
1031 		unsigned char bit2 = ((CH[7].SLOT[SLOT1].Cnt>>FREQ_SH)>>2)&1;
1032 
1033 		unsigned char res1 = (bit2 ^ bit7) | bit3;
1034 
1035 		/* when res1 = 0 phase = 0x000 | 0x100; */
1036 		/* when res1 = 1 phase = 0x200 | 0x100; */
1037 		uint32_t phase = res1 ? 0x300 : 0x100;
1038 
1039 		/* enable gate based on frequency of operator 2 in channel 8 */
1040 		unsigned char bit5e= ((CH[8].SLOT[SLOT2].Cnt>>FREQ_SH)>>5)&1;
1041 		unsigned char bit3e= ((CH[8].SLOT[SLOT2].Cnt>>FREQ_SH)>>3)&1;
1042 
1043 		unsigned char res2 = (bit3e ^ bit5e);
1044 		/* when res2 = 0 pass the phase from calculation above (res1); */
1045 		/* when res2 = 1 phase = 0x200 | 0x100; */
1046 		if (res2)
1047 			phase = 0x300;
1048 
1049 		output += op_calc(phase<<FREQ_SH, env, 0, CH[8].SLOT[SLOT2].wavetable) * 2;
1050 	}
1051 }
1052 
1053 
1054 /* generic table initialize */
init_tables(void)1055 static void init_tables(void)
1056 {
1057 	signed int i,x;
1058 	signed int n;
1059 	double o,m;
1060 
1061 	/* We only need to do this once. */
1062 	static bool did_init = false;
1063 
1064 	if (did_init)
1065 	{
1066 		return;
1067 	}
1068 
1069 	for (x=0; x<TL_RES_LEN; x++)
1070 	{
1071 		m = (1<<16) / pow(2.0, (x+1) * (ENV_STEP/4.0) / 8.0);
1072 		m = floor(m);
1073 
1074 		/* we never reach (1<<16) here due to the (x+1) */
1075 		/* result fits within 16 bits at maximum */
1076 
1077 		n = (int)m;     /* 16 bits here */
1078 		n >>= 4;        /* 12 bits here */
1079 		n = (n+1)>>1;	/* round to nearest */
1080 						/* 11 bits here (rounded) */
1081 		n <<= 1;        /* 12 bits here (as in real chip) */
1082 		tl_tab[ x*2 + 0 ] = n;
1083 		tl_tab[ x*2 + 1 ] = -tl_tab[ x*2 + 0 ];
1084 
1085 		for (i=1; i<12; i++)
1086 		{
1087 			tl_tab[ x*2+0 + i*2*TL_RES_LEN ] =  tl_tab[ x*2+0 ]>>i;
1088 			tl_tab[ x*2+1 + i*2*TL_RES_LEN ] = -tl_tab[ x*2+0 ]>>i;
1089 		}
1090 	}
1091 
1092 	for (i=0; i<SIN_LEN; i++)
1093 	{
1094 		/* non-standard sinus */
1095 		m = sin( ((i*2)+1) * PI / SIN_LEN ); /* checked against the real chip */
1096 
1097 		/* we never reach zero here due to ((i*2)+1) */
1098 
1099 		if (m>0.0)
1100 			o = 8*log(1.0/m)/log(2.0);  /* convert to 'decibels' */
1101 		else
1102 			o = 8*log(-1.0/m)/log(2.0); /* convert to 'decibels' */
1103 
1104 		o = o / (ENV_STEP/4);
1105 
1106 		n = (int)(2.0*o);
1107 		if (n&1)                        /* round to nearest */
1108 			n = (n>>1)+1;
1109 		else
1110 			n = n>>1;
1111 
1112 		sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
1113 	}
1114 
1115 	for (i=0; i<SIN_LEN; i++)
1116 	{
1117 		/* waveform 1:  __      __     */
1118 		/*             /  \____/  \____*/
1119 		/* output only first half of the sinus waveform (positive one) */
1120 
1121 		if (i & (1<<(SIN_BITS-1)) )
1122 			sin_tab[1*SIN_LEN+i] = TL_TAB_LEN;
1123 		else
1124 			sin_tab[1*SIN_LEN+i] = sin_tab[i];
1125 
1126 		/* waveform 2:  __  __  __  __ */
1127 		/*             /  \/  \/  \/  \*/
1128 		/* abs(sin) */
1129 
1130 		sin_tab[2*SIN_LEN+i] = sin_tab[i & (SIN_MASK>>1) ];
1131 
1132 		/* waveform 3:  _   _   _   _  */
1133 		/*             / |_/ |_/ |_/ |_*/
1134 		/* abs(output only first quarter of the sinus waveform) */
1135 
1136 		if (i & (1<<(SIN_BITS-2)) )
1137 			sin_tab[3*SIN_LEN+i] = TL_TAB_LEN;
1138 		else
1139 			sin_tab[3*SIN_LEN+i] = sin_tab[i & (SIN_MASK>>2)];
1140 	}
1141 
1142 	did_init = true;
1143 }
1144 
OPL_initalize(FM_OPL * OPL)1145 static void OPL_initalize(FM_OPL *OPL)
1146 {
1147 	int i;
1148 
1149 	/* make fnumber -> increment counter table */
1150 	for( i=0 ; i < 1024 ; i++ )
1151 	{
1152 		/* opn phase increment counter = 20bit */
1153 		OPL->fn_tab[i] = (uint32_t)( (double)i * 64 * OPL_FREQBASE * (1<<(FREQ_SH-10)) ); /* -10 because chip works with 10.10 fixed point, while we use 16.16 */
1154 	}
1155 
1156 	/* Amplitude modulation: 27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples */
1157 	/* One entry from LFO_AM_TABLE lasts for 64 samples */
1158 	OPL->lfo_am_inc = uint32_t((1.0 / 64.0 ) * (1<<LFO_SH) * OPL_FREQBASE);
1159 
1160 	/* Vibrato: 8 output levels (triangle waveform); 1 level takes 1024 samples */
1161 	OPL->lfo_pm_inc = uint32_t((1.0 / 1024.0) * (1<<LFO_SH) * OPL_FREQBASE);
1162 
1163 	OPL->eg_timer_add  = uint32_t((1<<EG_SH)  * OPL_FREQBASE);
1164 	OPL->eg_timer_overflow = uint32_t(( 1 ) * (1<<EG_SH));
1165 
1166 	// [RH] Support full MIDI panning. (But default to mono and center panning.)
1167 	OPL->IsStereo = false;
1168 	for (int i = 0; i < 9; ++i)
1169 	{
1170 		OPL->P_CH[i].LeftVol = (float)CENTER_PANNING_POWER;
1171 		OPL->P_CH[i].RightVol = (float)CENTER_PANNING_POWER;
1172 	}
1173 }
1174 
FM_KEYON(OPL_SLOT * SLOT,uint32_t key_set)1175 static inline void FM_KEYON(OPL_SLOT *SLOT, uint32_t key_set)
1176 {
1177 	if( !SLOT->key )
1178 	{
1179 		/* restart Phase Generator */
1180 		SLOT->Cnt = 0;
1181 		/* phase -> Attack */
1182 		SLOT->state = EG_ATT;
1183 	}
1184 	SLOT->key |= key_set;
1185 }
1186 
FM_KEYOFF(OPL_SLOT * SLOT,uint32_t key_clr)1187 static inline void FM_KEYOFF(OPL_SLOT *SLOT, uint32_t key_clr)
1188 {
1189 	if( SLOT->key )
1190 	{
1191 		SLOT->key &= key_clr;
1192 
1193 		if( !SLOT->key )
1194 		{
1195 			/* phase -> Release */
1196 			if (SLOT->state>EG_REL)
1197 				SLOT->state = EG_REL;
1198 		}
1199 	}
1200 }
1201 
1202 /* update phase increment counter of operator (also update the EG rates if necessary) */
CALC_FCSLOT(OPL_CH * CH,OPL_SLOT * SLOT)1203 static inline void CALC_FCSLOT(OPL_CH *CH,OPL_SLOT *SLOT)
1204 {
1205 	int ksr;
1206 
1207 	/* (frequency) phase increment counter */
1208 	SLOT->Incr = CH->fc * SLOT->mul;
1209 	ksr = CH->kcode >> SLOT->KSR;
1210 
1211 	if( SLOT->ksr != ksr )
1212 	{
1213 		SLOT->ksr = ksr;
1214 
1215 		/* calculate envelope generator rates */
1216 		if ((SLOT->ar + SLOT->ksr) < 16+62)
1217 		{
1218 			SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
1219 			SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
1220 		}
1221 		else
1222 		{
1223 			SLOT->eg_sh_ar  = 0;
1224 			SLOT->eg_sel_ar = 13*RATE_STEPS;
1225 		}
1226 		SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
1227 		SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
1228 		SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
1229 		SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
1230 	}
1231 }
1232 
1233 /* set multi,am,vib,EG-TYP,KSR,mul */
set_mul(FM_OPL * OPL,int slot,int v)1234 static inline void set_mul(FM_OPL *OPL,int slot,int v)
1235 {
1236 	OPL_CH   *CH   = &OPL->P_CH[slot/2];
1237 	OPL_SLOT *SLOT = &CH->SLOT[slot&1];
1238 
1239 	SLOT->mul     = mul_tab[v&0x0f];
1240 	SLOT->KSR     = (v&0x10) ? 0 : 2;
1241 	SLOT->eg_type = (v&0x20);
1242 	SLOT->vib     = (v&0x40);
1243 	SLOT->AMmask  = (v&0x80) ? ~0 : 0;
1244 	CALC_FCSLOT(CH,SLOT);
1245 }
1246 
1247 /* set ksl & tl */
set_ksl_tl(FM_OPL * OPL,int slot,int v)1248 static inline void set_ksl_tl(FM_OPL *OPL,int slot,int v)
1249 {
1250 	OPL_CH   *CH   = &OPL->P_CH[slot/2];
1251 	OPL_SLOT *SLOT = &CH->SLOT[slot&1];
1252 
1253 	SLOT->ksl = ksl_shift[v >> 6];
1254 	SLOT->TL  = (v&0x3f)<<(ENV_BITS-1-7); /* 7 bits TL (bit 6 = always 0) */
1255 
1256 	SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
1257 }
1258 
1259 /* set attack rate & decay rate  */
set_ar_dr(FM_OPL * OPL,int slot,int v)1260 static inline void set_ar_dr(FM_OPL *OPL,int slot,int v)
1261 {
1262 	OPL_CH   *CH   = &OPL->P_CH[slot/2];
1263 	OPL_SLOT *SLOT = &CH->SLOT[slot&1];
1264 
1265 	SLOT->ar = (v>>4)  ? 16 + ((v>>4)  <<2) : 0;
1266 
1267 	if ((SLOT->ar + SLOT->ksr) < 16+62)
1268 	{
1269 		SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
1270 		SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
1271 	}
1272 	else
1273 	{
1274 		SLOT->eg_sh_ar  = 0;
1275 		SLOT->eg_sel_ar = 13*RATE_STEPS;
1276 	}
1277 
1278 	SLOT->dr    = (v&0x0f)? 16 + ((v&0x0f)<<2) : 0;
1279 	SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
1280 	SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
1281 }
1282 
1283 /* set sustain level & release rate */
set_sl_rr(FM_OPL * OPL,int slot,int v)1284 static inline void set_sl_rr(FM_OPL *OPL,int slot,int v)
1285 {
1286 	OPL_CH   *CH   = &OPL->P_CH[slot/2];
1287 	OPL_SLOT *SLOT = &CH->SLOT[slot&1];
1288 
1289 	SLOT->sl  = sl_tab[ v>>4 ];
1290 
1291 	SLOT->rr  = (v&0x0f)? 16 + ((v&0x0f)<<2) : 0;
1292 	SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
1293 	SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
1294 }
1295 
1296 
1297 /* write a value v to register r on OPL chip */
WriteRegister(FM_OPL * OPL,int r,int v)1298 static void WriteRegister(FM_OPL *OPL, int r, int v)
1299 {
1300 	OPL_CH *CH;
1301 	int slot;
1302 	int block_fnum;
1303 
1304 	/* adjust bus to 8 bits */
1305 	r &= 0xff;
1306 	v &= 0xff;
1307 
1308 	switch(r&0xe0)
1309 	{
1310 	case 0x00:  /* 00-1f:control */
1311 		switch(r&0x1f)
1312 		{
1313 		case 0x01:	/* waveform select enable */
1314 			OPL->wavesel = v&0x20;
1315 			break;
1316 		case 0x02:  /* Timer 1 */
1317 			OPL->T[0] = (256-v)*4;
1318 			break;
1319 		case 0x03:  /* Timer 2 */
1320 			OPL->T[1] = (256-v)*16;
1321 			break;
1322 		case 0x04:  /* IRQ clear / mask and Timer enable */
1323 			if(v&0x80)
1324 			{   /* IRQ flag clear */
1325 				OPL_STATUS_RESET(OPL,0x7f-0x08); /* don't reset BFRDY flag or we will have to call deltat module to set the flag */
1326 			}
1327 			else
1328 			{   /* set IRQ mask ,timer enable*/
1329 				uint8_t st1 = v&1;
1330 				uint8_t st2 = (v>>1)&1;
1331 
1332 				/* IRQRST,T1MSK,t2MSK,EOSMSK,BRMSK,x,ST2,ST1 */
1333 				OPL_STATUS_RESET(OPL, v & (0x78-0x08) );
1334 				OPL_STATUSMASK_SET(OPL, (~v) & 0x78 );
1335 
1336 				/* timer 2 */
1337 				if(OPL->st[1] != st2)
1338 				{
1339 					OPL->st[1] = st2;
1340 				}
1341 				/* timer 1 */
1342 				if(OPL->st[0] != st1)
1343 				{
1344 					OPL->st[0] = st1;
1345 				}
1346 			}
1347 			break;
1348 		case 0x08:	/* MODE,DELTA-T control 2 : CSM,NOTESEL,x,x,smpl,da/ad,64k,rom */
1349 			OPL->mode = v;
1350 			break;
1351 		}
1352 		break;
1353 	case 0x20:  /* am ON, vib ON, ksr, eg_type, mul */
1354 		slot = slot_array[r&0x1f];
1355 		if(slot < 0) return;
1356 		set_mul(OPL,slot,v);
1357 		break;
1358 	case 0x40:
1359 		slot = slot_array[r&0x1f];
1360 		if(slot < 0) return;
1361 		set_ksl_tl(OPL,slot,v);
1362 		break;
1363 	case 0x60:
1364 		slot = slot_array[r&0x1f];
1365 		if(slot < 0) return;
1366 		set_ar_dr(OPL,slot,v);
1367 		break;
1368 	case 0x80:
1369 		slot = slot_array[r&0x1f];
1370 		if(slot < 0) return;
1371 		set_sl_rr(OPL,slot,v);
1372 		break;
1373 	case 0xa0:
1374 		if (r == 0xbd)          /* am depth, vibrato depth, r,bd,sd,tom,tc,hh */
1375 		{
1376 			OPL->lfo_am_depth = v & 0x80;
1377 			OPL->lfo_pm_depth_range = (v&0x40) ? 8 : 0;
1378 
1379 			OPL->rhythm  = v&0x3f;
1380 
1381 			if(OPL->rhythm&0x20)
1382 			{
1383 				/* BD key on/off */
1384 				if(v&0x10)
1385 				{
1386 					FM_KEYON (&OPL->P_CH[6].SLOT[SLOT1], 2);
1387 					FM_KEYON (&OPL->P_CH[6].SLOT[SLOT2], 2);
1388 				}
1389 				else
1390 				{
1391 					FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT1],~2);
1392 					FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT2],~2);
1393 				}
1394 				/* HH key on/off */
1395 				if(v&0x01) FM_KEYON (&OPL->P_CH[7].SLOT[SLOT1], 2);
1396 				else       FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT1],~2);
1397 				/* SD key on/off */
1398 				if(v&0x08) FM_KEYON (&OPL->P_CH[7].SLOT[SLOT2], 2);
1399 				else       FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT2],~2);
1400 				/* TOM key on/off */
1401 				if(v&0x04) FM_KEYON (&OPL->P_CH[8].SLOT[SLOT1], 2);
1402 				else       FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT1],~2);
1403 				/* TOP-CY key on/off */
1404 				if(v&0x02) FM_KEYON (&OPL->P_CH[8].SLOT[SLOT2], 2);
1405 				else       FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT2],~2);
1406 			}
1407 			else
1408 			{
1409 				/* BD key off */
1410 				FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT1],~2);
1411 				FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT2],~2);
1412 				/* HH key off */
1413 				FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT1],~2);
1414 				/* SD key off */
1415 				FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT2],~2);
1416 				/* TOM key off */
1417 				FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT1],~2);
1418 				/* TOP-CY off */
1419 				FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT2],~2);
1420 			}
1421 			return;
1422 		}
1423 		/* keyon,block,fnum */
1424 		if( (r&0x0f) > 8) return;
1425 		CH = &OPL->P_CH[r&0x0f];
1426 		if(!(r&0x10))
1427 		{   /* a0-a8 */
1428 			block_fnum  = (CH->block_fnum&0x1f00) | v;
1429 		}
1430 		else
1431 		{   /* b0-b8 */
1432 			block_fnum = ((v&0x1f)<<8) | (CH->block_fnum&0xff);
1433 
1434 			if(v&0x20)
1435 			{
1436 				FM_KEYON (&CH->SLOT[SLOT1], 1);
1437 				FM_KEYON (&CH->SLOT[SLOT2], 1);
1438 			}
1439 			else
1440 			{
1441 				FM_KEYOFF(&CH->SLOT[SLOT1],~1);
1442 				FM_KEYOFF(&CH->SLOT[SLOT2],~1);
1443 			}
1444 		}
1445 		/* update */
1446 		if(CH->block_fnum != (uint32_t)block_fnum)
1447 		{
1448 			uint8_t block  = block_fnum >> 10;
1449 
1450 			CH->block_fnum = block_fnum;
1451 
1452 			CH->ksl_base = ksl_tab[block_fnum>>6];
1453 			CH->fc       = OPL->fn_tab[block_fnum&0x03ff] >> (7-block);
1454 
1455 			/* BLK 2,1,0 bits -> bits 3,2,1 of kcode */
1456 			CH->kcode    = (CH->block_fnum&0x1c00)>>9;
1457 
1458 				/* the info below is actually opposite to what is stated in the Manuals (verifed on real YM3812) */
1459 			/* if notesel == 0 -> lsb of kcode is bit 10 (MSB) of fnum  */
1460 			/* if notesel == 1 -> lsb of kcode is bit 9 (MSB-1) of fnum */
1461 			if (OPL->mode&0x40)
1462 				CH->kcode |= (CH->block_fnum&0x100)>>8; /* notesel == 1 */
1463 			else
1464 				CH->kcode |= (CH->block_fnum&0x200)>>9; /* notesel == 0 */
1465 
1466 			/* refresh Total Level in both SLOTs of this channel */
1467 			CH->SLOT[SLOT1].TLL = CH->SLOT[SLOT1].TL + (CH->ksl_base>>CH->SLOT[SLOT1].ksl);
1468 			CH->SLOT[SLOT2].TLL = CH->SLOT[SLOT2].TL + (CH->ksl_base>>CH->SLOT[SLOT2].ksl);
1469 
1470 			/* refresh frequency counter in both SLOTs of this channel */
1471 			CALC_FCSLOT(CH,&CH->SLOT[SLOT1]);
1472 			CALC_FCSLOT(CH,&CH->SLOT[SLOT2]);
1473 		}
1474 		break;
1475 	case 0xc0:
1476 		/* FB,C */
1477 		if( (r&0x0f) > 8) return;
1478 		CH = &OPL->P_CH[r&0x0f];
1479 		CH->SLOT[SLOT1].FB  = (v>>1)&7 ? ((v>>1)&7) + 7 : 0;
1480 		CH->SLOT[SLOT1].CON = v&1;
1481 		CH->SLOT[SLOT1].connect1 = CH->SLOT[SLOT1].CON ? &output : &phase_modulation;
1482 		break;
1483 	case 0xe0: /* waveform select */
1484 		/* simply ignore write to the waveform select register if selecting not enabled in test register */
1485 		if(OPL->wavesel)
1486 		{
1487 			slot = slot_array[r&0x1f];
1488 			if(slot < 0) return;
1489 			CH = &OPL->P_CH[slot/2];
1490 
1491 			CH->SLOT[slot&1].wavetable = (v&0x03)*SIN_LEN;
1492 		}
1493 		break;
1494 	}
1495 }
1496 
OPLResetChip(FM_OPL * OPL)1497 static void OPLResetChip(FM_OPL *OPL)
1498 {
1499 	int c,s;
1500 	int i;
1501 
1502 	OPL->eg_timer = 0;
1503 	OPL->eg_cnt   = 0;
1504 
1505 	OPL->noise_rng = 1; /* noise shift register */
1506 	OPL->mode   = 0;    /* normal mode */
1507 	OPL_STATUS_RESET(OPL,0x7f);
1508 
1509 	/* reset with register write */
1510 	WriteRegister(OPL,0x01,0); /* wavesel disable */
1511 	WriteRegister(OPL,0x02,0); /* Timer1 */
1512 	WriteRegister(OPL,0x03,0); /* Timer2 */
1513 	WriteRegister(OPL,0x04,0); /* IRQ mask clear */
1514 	for(i = 0xff ; i >= 0x20 ; i-- ) WriteRegister(OPL,i,0);
1515 
1516 	/* reset operator parameters */
1517 	for( c = 0 ; c < 9 ; c++ )
1518 	{
1519 		OPL_CH *CH = &OPL->P_CH[c];
1520 		for(s = 0 ; s < 2 ; s++ )
1521 		{
1522 			/* wave table */
1523 			CH->SLOT[s].wavetable = 0;
1524 			CH->SLOT[s].state     = EG_OFF;
1525 			CH->SLOT[s].volume    = MAX_ATT_INDEX;
1526 		}
1527 	}
1528 }
1529 
1530 
1531 class YM3812 : public OPLEmul
1532 {
1533 private:
1534 	FM_OPL Chip;
1535 
1536 public:
1537 	/* Create one of virtual YM3812 */
YM3812(bool stereo)1538 	YM3812(bool stereo)
1539 	{
1540 		init_tables();
1541 
1542 		/* clear */
1543 		memset(&Chip, 0, sizeof(Chip));
1544 
1545 		/* init global tables */
1546 		OPL_initalize(&Chip);
1547 
1548 		Chip.IsStereo = stereo;
1549 
1550 		Reset();
1551 	}
1552 
1553 	/* YM3812 I/O interface */
WriteReg(int reg,int v)1554 	void WriteReg(int reg, int v)
1555 	{
1556 		WriteRegister(&Chip, reg & 0xff, v);
1557 	}
1558 
Reset()1559 	void Reset()
1560 	{
1561 		OPLResetChip(&Chip);
1562 	}
1563 
1564 	/* [RH] Full support for MIDI panning */
SetPanning(int c,float left,float right)1565 	void SetPanning(int c, float left, float right)
1566 	{
1567 		Chip.P_CH[c].LeftVol = left;
1568 		Chip.P_CH[c].RightVol = right;
1569 	}
1570 
1571 
1572 	/*
1573 	** Generate samples for one of the YM3812's
1574 	**
1575 	** '*buffer' is the output buffer pointer
1576 	** 'length' is the number of samples that should be generated
1577 	*/
Update(float * buffer,int length)1578 	void Update(float *buffer, int length)
1579 	{
1580 		int i;
1581 
1582 		uint8_t		rhythm = Chip.rhythm&0x20;
1583 
1584 		uint32_t lfo_am_cnt_bak = Chip.lfo_am_cnt;
1585 		uint32_t eg_timer_bak = Chip.eg_timer;
1586 		uint32_t eg_cnt_bak = Chip.eg_cnt;
1587 
1588 		uint32_t lfo_am_cnt_out = lfo_am_cnt_bak;
1589 		uint32_t eg_timer_out = eg_timer_bak;
1590 		uint32_t eg_cnt_out = eg_cnt_bak;
1591 
1592 		for (i = 0; i <= (rhythm ? 5 : 8); ++i)
1593 		{
1594 			Chip.lfo_am_cnt = lfo_am_cnt_bak;
1595 			Chip.eg_timer = eg_timer_bak;
1596 			Chip.eg_cnt = eg_cnt_bak;
1597 			if (CalcVoice (&Chip, i, buffer, length))
1598 			{
1599 				lfo_am_cnt_out = Chip.lfo_am_cnt;
1600 				eg_timer_out = Chip.eg_timer;
1601 				eg_cnt_out = Chip.eg_cnt;
1602 			}
1603 		}
1604 
1605 		Chip.lfo_am_cnt = lfo_am_cnt_out;
1606 		Chip.eg_timer = eg_timer_out;
1607 		Chip.eg_cnt = eg_cnt_out;
1608 
1609 		if (rhythm)		/* Rhythm part */
1610 		{
1611 			Chip.lfo_am_cnt = lfo_am_cnt_bak;
1612 			Chip.eg_timer = eg_timer_bak;
1613 			Chip.eg_cnt = eg_cnt_bak;
1614 			CalcRhythm (&Chip, buffer, length);
1615 		}
1616 	}
1617 
GetVoiceString(void * chip)1618 	std::string GetVoiceString(void *chip)
1619 	{
1620 		FM_OPL *OPL = (FM_OPL *)chip;
1621 		char out[9*3];
1622 
1623 		for (int i = 0; i <= 8; ++i)
1624 		{
1625 			int color;
1626 
1627 			if (OPL != NULL && (OPL->P_CH[i].SLOT[0].state != EG_OFF || OPL->P_CH[i].SLOT[1].state != EG_OFF))
1628 			{
1629 				color = 'D';	// Green means in use
1630 			}
1631 			else
1632 			{
1633 				color = 'A';	// Brick means free
1634 			}
1635 			out[i*3+0] = '\x1c';
1636 			out[i*3+1] = color;
1637 			out[i*3+2] = '*';
1638 		}
1639 		return std::string (out, 9*3);
1640 	}
1641 };
1642 
YM3812Create(bool stereo)1643 OPLEmul *YM3812Create(bool stereo)
1644 {
1645 	/* emulator create */
1646 	return new YM3812(stereo);
1647 }
1648 
1649 // [RH] Render a whole voice at once. If nothing else, it lets us avoid
1650 // wasting a lot of time on voices that aren't playing anything.
1651 
CalcVoice(FM_OPL * OPL,int voice,float * buffer,int length)1652 static bool CalcVoice (FM_OPL *OPL, int voice, float *buffer, int length)
1653 {
1654 	OPL_CH *const CH = &OPL->P_CH[voice];
1655 	int i;
1656 
1657 	if (CH->SLOT[0].state == EG_OFF && CH->SLOT[1].state == EG_OFF)
1658 	{ // Voice is not playing, so don't do anything for it
1659 		return false;
1660 	}
1661 
1662 	for (i = 0; i < length; ++i)
1663 	{
1664 		advance_lfo(OPL);
1665 
1666 		output = 0;
1667 		float sample = OPL_CALC_CH(CH);
1668 		if (!OPL->IsStereo)
1669 		{
1670 			buffer[i] += sample;
1671 		}
1672 		else
1673 		{
1674 			buffer[i*2] += sample * CH->LeftVol;
1675 			buffer[i*2+1] += sample * CH->RightVol;
1676 		}
1677 
1678 		advance(OPL, voice, voice);
1679 	}
1680 	return true;
1681 }
1682 
CalcRhythm(FM_OPL * OPL,float * buffer,int length)1683 static bool CalcRhythm (FM_OPL *OPL, float *buffer, int length)
1684 {
1685 	int i;
1686 
1687 	for (i = 0; i < length; ++i)
1688 	{
1689 		advance_lfo(OPL);
1690 
1691 		output = 0;
1692 		OPL_CALC_RH(&OPL->P_CH[0], OPL->noise_rng & 1);
1693 		/* [RH] Convert to floating point. */
1694 		float sample = float(output) / 10240;
1695 		if (!OPL->IsStereo)
1696 		{
1697 			buffer[i] += sample;
1698 		}
1699 		else
1700 		{
1701 			// [RH] Always use center panning for rhythm.
1702 			// The MIDI player doesn't use the rhythm section anyway.
1703 			buffer[i*2] += sample * CENTER_PANNING_POWER;
1704 			buffer[i*2+1] += sample * CENTER_PANNING_POWER;
1705 		}
1706 
1707 		advance(OPL, 6, 8);
1708 		advance_noise(OPL);
1709 	}
1710 	return true;
1711 }
1712