1 /*
2  *  Copyright (C) 2002-2011  The DOSBox Team
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18 
19 /*
20 	DOSBox implementation of a combined Yamaha YMF262 and Yamaha YM3812 emulator.
21 	Enabling the opl3 bit will switch the emulator to stereo opl3 output instead of regular mono opl2
22 	Except for the table generation it's all integer math
23 	Can choose different types of generators, using muls and bigger tables, try different ones for slower platforms
24 	The generation was based on the MAME implementation but tried to have it use less memory and be faster in general
25 	MAME uses much bigger envelope tables and this will be the biggest cause of it sounding different at times
26 
27 	//TODO Don't delay first operator 1 sample in opl3 mode
28 	//TODO Maybe not use class method pointers but a regular function pointers with operator as first parameter
29 	//TODO Fix panning for the Percussion channels, would any opl3 player use it and actually really change it though?
30 	//TODO Check if having the same accuracy in all frequency multipliers sounds better or not
31 
32 	//DUNNO Keyon in 4op, switch to 2op without keyoff.
33 */
34 
35 // Last synch with DOSBox SVN trunk r3752
36 
37 #include "dbopl.h"
38 
39 #ifndef DISABLE_DOSBOX_OPL
40 
41 namespace OPL {
42 namespace DOSBox {
43 
44 namespace DBOPL {
45 
46 #define OPLRATE		((double)(14318180.0 / 288.0))
47 #define TREMOLO_TABLE 52
48 
49 //Try to use most precision for frequencies
50 //Else try to keep different waves in synch
51 //#define WAVE_PRECISION	1
52 #ifndef WAVE_PRECISION
53 //Wave bits available in the top of the 32bit range
54 //Original adlib uses 10.10, we use 10.22
55 #define WAVE_BITS	10
56 #else
57 //Need some extra bits at the top to have room for octaves and frequency multiplier
58 //We support to 8 times lower rate
59 //128 * 15 * 8 = 15350, 2^13.9, so need 14 bits
60 #define WAVE_BITS	14
61 #endif
62 #define WAVE_SH		( 32 - WAVE_BITS )
63 #define WAVE_MASK	( ( 1 << WAVE_SH ) - 1 )
64 
65 //Use the same accuracy as the waves
66 #define LFO_SH ( WAVE_SH - 10 )
67 //LFO is controlled by our tremolo 256 sample limit
68 #define LFO_MAX ( 256 << ( LFO_SH ) )
69 
70 
71 //Maximum amount of attenuation bits
72 //Envelope goes to 511, 9 bits
73 #if (DBOPL_WAVE == WAVE_TABLEMUL )
74 //Uses the value directly
75 #define ENV_BITS	( 9 )
76 #else
77 //Add 3 bits here for more accuracy and would have to be shifted up either way
78 #define ENV_BITS	( 9 )
79 #endif
80 //Limits of the envelope with those bits and when the envelope goes silent
81 #define ENV_MIN		0
82 #define ENV_EXTRA	( ENV_BITS - 9 )
83 #define ENV_MAX		( 511 << ENV_EXTRA )
84 #define ENV_LIMIT	( ( 12 * 256) >> ( 3 - ENV_EXTRA ) )
85 #define ENV_SILENT( _X_ ) ( (_X_) >= ENV_LIMIT )
86 
87 //Attack/decay/release rate counter shift
88 #define RATE_SH		24
89 #define RATE_MASK	( ( 1 << RATE_SH ) - 1 )
90 //Has to fit within 16bit lookuptable
91 #define MUL_SH		16
92 
93 //Check some ranges
94 #if ENV_EXTRA > 3
95 #error Too many envelope bits
96 #endif
97 
98 
99 //How much to substract from the base value for the final attenuation
100 static const Bit8u KslCreateTable[16] = {
101 	//0 will always be be lower than 7 * 8
102 	64, 32, 24, 19,
103 	16, 12, 11, 10,
104 	 8,  6,  5,  4,
105 	 3,  2,  1,  0,
106 };
107 
108 #define M(_X_) ((Bit8u)( (_X_) * 2))
109 static const Bit8u FreqCreateTable[16] = {
110 	M(0.5), M(1 ), M(2 ), M(3 ), M(4 ), M(5 ), M(6 ), M(7 ),
111 	M(8  ), M(9 ), M(10), M(10), M(12), M(12), M(15), M(15)
112 };
113 #undef M
114 
115 //We're not including the highest attack rate, that gets a special value
116 static const Bit8u AttackSamplesTable[13] = {
117 	69, 55, 46, 40,
118 	35, 29, 23, 20,
119 	19, 15, 11, 10,
120 	9
121 };
122 //On a real opl these values take 8 samples to reach and are based upon larger tables
123 static const Bit8u EnvelopeIncreaseTable[13] = {
124 	4,  5,  6,  7,
125 	8, 10, 12, 14,
126 	16, 20, 24, 28,
127 	32,
128 };
129 
130 #if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG )
131 static Bit16u ExpTable[ 256 ];
132 #endif
133 
134 #if ( DBOPL_WAVE == WAVE_HANDLER )
135 //PI table used by WAVEHANDLER
136 static Bit16u SinTable[ 512 ];
137 #endif
138 
139 #if ( DBOPL_WAVE > WAVE_HANDLER )
140 //Layout of the waveform table in 512 entry intervals
141 //With overlapping waves we reduce the table to half it's size
142 
143 //	|    |//\\|____|WAV7|//__|/\  |____|/\/\|
144 //	|\\//|    |    |WAV7|    |  \/|    |    |
145 //	|06  |0126|17  |7   |3   |4   |4 5 |5   |
146 
147 //6 is just 0 shifted and masked
148 
149 static Bit16s WaveTable[ 8 * 512 ];
150 //Distance into WaveTable the wave starts
151 static const Bit16u WaveBaseTable[8] = {
152 	0x000, 0x200, 0x200, 0x800,
153 	0xa00, 0xc00, 0x100, 0x400,
154 
155 };
156 //Mask the counter with this
157 static const Bit16u WaveMaskTable[8] = {
158 	1023, 1023, 511, 511,
159 	1023, 1023, 512, 1023,
160 };
161 
162 //Where to start the counter on at keyon
163 static const Bit16u WaveStartTable[8] = {
164 	512, 0, 0, 0,
165 	0, 512, 512, 256,
166 };
167 #endif
168 
169 #if ( DBOPL_WAVE == WAVE_TABLEMUL )
170 static Bit16u MulTable[ 384 ];
171 #endif
172 
173 static Bit8u KslTable[ 8 * 16 ];
174 static Bit8u TremoloTable[ TREMOLO_TABLE ];
175 //Start of a channel behind the chip struct start
176 static Bit16u ChanOffsetTable[32];
177 //Start of an operator behind the chip struct start
178 static Bit16u OpOffsetTable[64];
179 
180 //The lower bits are the shift of the operator vibrato value
181 //The highest bit is right shifted to generate -1 or 0 for negation
182 //So taking the highest input value of 7 this gives 3, 7, 3, 0, -3, -7, -3, 0
183 static const Bit8s VibratoTable[ 8 ] = {
184 	1 - 0x00, 0 - 0x00, 1 - 0x00, 30 - 0x00,
185 	1 - 0x80, 0 - 0x80, 1 - 0x80, 30 - 0x80
186 };
187 
188 //Shift strength for the ksl value determined by ksl strength
189 static const Bit8u KslShiftTable[4] = {
190 	31,1,2,0
191 };
192 
193 //Generate a table index and table shift value using input value from a selected rate
EnvelopeSelect(Bit8u val,Bit8u & index,Bit8u & shift)194 static void EnvelopeSelect( Bit8u val, Bit8u& index, Bit8u& shift ) {
195 	if ( val < 13 * 4 ) {				//Rate 0 - 12
196 		shift = 12 - ( val >> 2 );
197 		index = val & 3;
198 	} else if ( val < 15 * 4 ) {		//rate 13 - 14
199 		shift = 0;
200 		index = val - 12 * 4;
201 	} else {							//rate 15 and up
202 		shift = 0;
203 		index = 12;
204 	}
205 }
206 
207 #if ( DBOPL_WAVE == WAVE_HANDLER )
208 /*
209 	Generate the different waveforms out of the sine/exponetial table using handlers
210 */
MakeVolume(Bitu wave,Bitu volume)211 static inline Bits MakeVolume( Bitu wave, Bitu volume ) {
212 	Bitu total = wave + volume;
213 	Bitu index = total & 0xff;
214 	Bitu sig = ExpTable[ index ];
215 	Bitu exp = total >> 8;
216 #if 0
217 	//Check if we overflow the 31 shift limit
218 	if ( exp >= 32 ) {
219 		LOG_MSG( "WTF %d %d", total, exp );
220 	}
221 #endif
222 	return (sig >> exp);
223 }
224 
WaveForm0(Bitu i,Bitu volume)225 static Bits DB_FASTCALL WaveForm0( Bitu i, Bitu volume ) {
226 	Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0
227 	Bitu wave = SinTable[i & 511];
228 	return (MakeVolume( wave, volume ) ^ neg) - neg;
229 }
WaveForm1(Bitu i,Bitu volume)230 static Bits DB_FASTCALL WaveForm1( Bitu i, Bitu volume ) {
231 	Bit32u wave = SinTable[i & 511];
232 	wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 );
233 	return MakeVolume( wave, volume );
234 }
WaveForm2(Bitu i,Bitu volume)235 static Bits DB_FASTCALL WaveForm2( Bitu i, Bitu volume ) {
236 	Bitu wave = SinTable[i & 511];
237 	return MakeVolume( wave, volume );
238 }
WaveForm3(Bitu i,Bitu volume)239 static Bits DB_FASTCALL WaveForm3( Bitu i, Bitu volume ) {
240 	Bitu wave = SinTable[i & 255];
241 	wave |= ( ( (i ^ 256 ) & 256) - 1) >> ( 32 - 12 );
242 	return MakeVolume( wave, volume );
243 }
WaveForm4(Bitu i,Bitu volume)244 static Bits DB_FASTCALL WaveForm4( Bitu i, Bitu volume ) {
245 	//Twice as fast
246 	i <<= 1;
247 	Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0
248 	Bitu wave = SinTable[i & 511];
249 	wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 );
250 	return (MakeVolume( wave, volume ) ^ neg) - neg;
251 }
WaveForm5(Bitu i,Bitu volume)252 static Bits DB_FASTCALL WaveForm5( Bitu i, Bitu volume ) {
253 	//Twice as fast
254 	i <<= 1;
255 	Bitu wave = SinTable[i & 511];
256 	wave |= ( ( (i ^ 512 ) & 512) - 1) >> ( 32 - 12 );
257 	return MakeVolume( wave, volume );
258 }
WaveForm6(Bitu i,Bitu volume)259 static Bits DB_FASTCALL WaveForm6( Bitu i, Bitu volume ) {
260 	Bits neg = 0 - (( i >> 9) & 1);//Create ~0 or 0
261 	return (MakeVolume( 0, volume ) ^ neg) - neg;
262 }
WaveForm7(Bitu i,Bitu volume)263 static Bits DB_FASTCALL WaveForm7( Bitu i, Bitu volume ) {
264 	//Negative is reversed here
265 	Bits neg = (( i >> 9) & 1) - 1;
266 	Bitu wave = (i << 3);
267 	//When negative the volume also runs backwards
268 	wave = ((wave ^ neg) - neg) & 4095;
269 	return (MakeVolume( wave, volume ) ^ neg) - neg;
270 }
271 
272 static const WaveHandler WaveHandlerTable[8] = {
273 	WaveForm0, WaveForm1, WaveForm2, WaveForm3,
274 	WaveForm4, WaveForm5, WaveForm6, WaveForm7
275 };
276 
277 #endif
278 
279 /*
280 	Operator
281 */
282 
283 //We zero out when rate == 0
UpdateAttack(const Chip * chip)284 inline void Operator::UpdateAttack( const Chip* chip ) {
285 	Bit8u rate = reg60 >> 4;
286 	if ( rate ) {
287 		Bit8u val = (rate << 2) + ksr;
288 		attackAdd = chip->attackRates[ val ];
289 		rateZero &= ~(1 << ATTACK);
290 	} else {
291 		attackAdd = 0;
292 		rateZero |= (1 << ATTACK);
293 	}
294 }
UpdateDecay(const Chip * chip)295 inline void Operator::UpdateDecay( const Chip* chip ) {
296 	Bit8u rate = reg60 & 0xf;
297 	if ( rate ) {
298 		Bit8u val = (rate << 2) + ksr;
299 		decayAdd = chip->linearRates[ val ];
300 		rateZero &= ~(1 << DECAY);
301 	} else {
302 		decayAdd = 0;
303 		rateZero |= (1 << DECAY);
304 	}
305 }
UpdateRelease(const Chip * chip)306 inline void Operator::UpdateRelease( const Chip* chip ) {
307 	Bit8u rate = reg80 & 0xf;
308 	if ( rate ) {
309 		Bit8u val = (rate << 2) + ksr;
310 		releaseAdd = chip->linearRates[ val ];
311 		rateZero &= ~(1 << RELEASE);
312 		if ( !(reg20 & MASK_SUSTAIN ) ) {
313 			rateZero &= ~( 1 << SUSTAIN );
314 		}
315 	} else {
316 		rateZero |= (1 << RELEASE);
317 		releaseAdd = 0;
318 		if ( !(reg20 & MASK_SUSTAIN ) ) {
319 			rateZero |= ( 1 << SUSTAIN );
320 		}
321 	}
322 }
323 
UpdateAttenuation()324 inline void Operator::UpdateAttenuation( ) {
325 	Bit8u kslBase = (Bit8u)((chanData >> SHIFT_KSLBASE) & 0xff);
326 	Bit32u tl = reg40 & 0x3f;
327 	Bit8u kslShift = KslShiftTable[ reg40 >> 6 ];
328 	//Make sure the attenuation goes to the right bits
329 	totalLevel = tl << ( ENV_BITS - 7 );	//Total level goes 2 bits below max
330 	totalLevel += ( kslBase << ENV_EXTRA ) >> kslShift;
331 }
332 
UpdateFrequency()333 void Operator::UpdateFrequency(  ) {
334 	Bit32u freq = chanData & (( 1 << 10 ) - 1);
335 	Bit32u block = (chanData >> 10) & 0xff;
336 #ifdef WAVE_PRECISION
337 	block = 7 - block;
338 	waveAdd = ( freq * freqMul ) >> block;
339 #else
340 	waveAdd = ( freq << block ) * freqMul;
341 #endif
342 	if ( reg20 & MASK_VIBRATO ) {
343 		vibStrength = (Bit8u)(freq >> 7);
344 
345 #ifdef WAVE_PRECISION
346 		vibrato = ( vibStrength * freqMul ) >> block;
347 #else
348 		vibrato = ( vibStrength << block ) * freqMul;
349 #endif
350 	} else {
351 		vibStrength = 0;
352 		vibrato = 0;
353 	}
354 }
355 
UpdateRates(const Chip * chip)356 void Operator::UpdateRates( const Chip* chip ) {
357 	//Mame seems to reverse this where enabling ksr actually lowers
358 	//the rate, but pdf manuals says otherwise?
359 	Bit8u newKsr = (Bit8u)((chanData >> SHIFT_KEYCODE) & 0xff);
360 	if ( !( reg20 & MASK_KSR ) ) {
361 		newKsr >>= 2;
362 	}
363 	if ( ksr == newKsr )
364 		return;
365 	ksr = newKsr;
366 	UpdateAttack( chip );
367 	UpdateDecay( chip );
368 	UpdateRelease( chip );
369 }
370 
RateForward(Bit32u add)371 INLINE Bit32s Operator::RateForward( Bit32u add ) {
372 	rateIndex += add;
373 	Bit32s ret = rateIndex >> RATE_SH;
374 	rateIndex = rateIndex & RATE_MASK;
375 	return ret;
376 }
377 
378 template< Operator::State yes>
TemplateVolume()379 Bits Operator::TemplateVolume(  ) {
380 	Bit32s vol = volume;
381 	Bit32s change;
382 	switch ( yes ) {
383 	case OFF:
384 		return ENV_MAX;
385 	case ATTACK:
386 		change = RateForward( attackAdd );
387 		if ( !change )
388 			return vol;
389 		vol += ( (~vol) * change ) >> 3;
390 		if ( vol < ENV_MIN ) {
391 			volume = ENV_MIN;
392 			rateIndex = 0;
393 			SetState( DECAY );
394 			return ENV_MIN;
395 		}
396 		break;
397 	case DECAY:
398 		vol += RateForward( decayAdd );
399 		if ( GCC_UNLIKELY(vol >= sustainLevel) ) {
400 			//Check if we didn't overshoot max attenuation, then just go off
401 			if ( GCC_UNLIKELY(vol >= ENV_MAX) ) {
402 				volume = ENV_MAX;
403 				SetState( OFF );
404 				return ENV_MAX;
405 			}
406 			//Continue as sustain
407 			rateIndex = 0;
408 			SetState( SUSTAIN );
409 		}
410 		break;
411 	case SUSTAIN:
412 		if ( reg20 & MASK_SUSTAIN ) {
413 			return vol;
414 		}
415 		//In sustain phase, but not sustaining, do regular release
416 		//fall through
417 	case RELEASE:
418 		vol += RateForward( releaseAdd );
419 		if ( GCC_UNLIKELY(vol >= ENV_MAX) ) {
420 			volume = ENV_MAX;
421 			SetState( OFF );
422 			return ENV_MAX;
423 		}
424 		break;
425 	}
426 	volume = vol;
427 	return vol;
428 }
429 
430 static const VolumeHandler VolumeHandlerTable[5] = {
431 	&Operator::TemplateVolume< Operator::OFF >,
432 	&Operator::TemplateVolume< Operator::RELEASE >,
433 	&Operator::TemplateVolume< Operator::SUSTAIN >,
434 	&Operator::TemplateVolume< Operator::DECAY >,
435 	&Operator::TemplateVolume< Operator::ATTACK >
436 };
437 
ForwardVolume()438 INLINE Bitu Operator::ForwardVolume() {
439 	return currentLevel + (this->*volHandler)();
440 }
441 
442 
ForwardWave()443 INLINE Bitu Operator::ForwardWave() {
444 	waveIndex += waveCurrent;
445 	return waveIndex >> WAVE_SH;
446 }
447 
Write20(const Chip * chip,Bit8u val)448 void Operator::Write20( const Chip* chip, Bit8u val ) {
449 	Bit8u change = (reg20 ^ val );
450 	if ( !change )
451 		return;
452 	reg20 = val;
453 	//Shift the tremolo bit over the entire register, saved a branch, YES!
454 	tremoloMask = (Bit8s)(val) >> 7;
455 	tremoloMask &= ~(( 1 << ENV_EXTRA ) -1);
456 	//Update specific features based on changes
457 	if ( change & MASK_KSR ) {
458 		UpdateRates( chip );
459 	}
460 	//With sustain enable the volume doesn't change
461 	if ( reg20 & MASK_SUSTAIN || ( !releaseAdd ) ) {
462 		rateZero |= ( 1 << SUSTAIN );
463 	} else {
464 		rateZero &= ~( 1 << SUSTAIN );
465 	}
466 	//Frequency multiplier or vibrato changed
467 	if ( change & (0xf | MASK_VIBRATO) ) {
468 		freqMul = chip->freqMul[ val & 0xf ];
469 		UpdateFrequency();
470 	}
471 }
472 
Write40(const Chip *,Bit8u val)473 void Operator::Write40( const Chip* /*chip*/, Bit8u val ) {
474 	if (!(reg40 ^ val ))
475 		return;
476 	reg40 = val;
477 	UpdateAttenuation( );
478 }
479 
Write60(const Chip * chip,Bit8u val)480 void Operator::Write60( const Chip* chip, Bit8u val ) {
481 	Bit8u change = reg60 ^ val;
482 	reg60 = val;
483 	if ( change & 0x0f ) {
484 		UpdateDecay( chip );
485 	}
486 	if ( change & 0xf0 ) {
487 		UpdateAttack( chip );
488 	}
489 }
490 
Write80(const Chip * chip,Bit8u val)491 void Operator::Write80( const Chip* chip, Bit8u val ) {
492 	Bit8u change = (reg80 ^ val );
493 	if ( !change )
494 		return;
495 	reg80 = val;
496 	Bit8u sustain = val >> 4;
497 	//Turn 0xf into 0x1f
498 	sustain |= ( sustain + 1) & 0x10;
499 	sustainLevel = sustain << ( ENV_BITS - 5 );
500 	if ( change & 0x0f ) {
501 		UpdateRelease( chip );
502 	}
503 }
504 
WriteE0(const Chip * chip,Bit8u val)505 void Operator::WriteE0( const Chip* chip, Bit8u val ) {
506 	if ( !(regE0 ^ val) )
507 		return;
508 	//in opl3 mode you can always selet 7 waveforms regardless of waveformselect
509 	Bit8u waveForm = val & ( ( 0x3 & chip->waveFormMask ) | (0x7 & chip->opl3Active ) );
510 	regE0 = val;
511 #if ( DBOPL_WAVE == WAVE_HANDLER )
512 	waveHandler = WaveHandlerTable[ waveForm ];
513 #else
514 	waveBase = WaveTable + WaveBaseTable[ waveForm ];
515 	waveStart = WaveStartTable[ waveForm ] << WAVE_SH;
516 	waveMask = WaveMaskTable[ waveForm ];
517 #endif
518 }
519 
SetState(Bit8u s)520 INLINE void Operator::SetState( Bit8u s ) {
521 	state = s;
522 	volHandler = VolumeHandlerTable[ s ];
523 }
524 
Silent() const525 INLINE bool Operator::Silent() const {
526 	if ( !ENV_SILENT( totalLevel + volume ) )
527 		return false;
528 	if ( !(rateZero & ( 1 << state ) ) )
529 		return false;
530 	return true;
531 }
532 
Prepare(const Chip * chip)533 INLINE void Operator::Prepare( const Chip* chip )  {
534 	currentLevel = totalLevel + (chip->tremoloValue & tremoloMask);
535 	waveCurrent = waveAdd;
536 	if ( vibStrength >> chip->vibratoShift ) {
537 		Bit32s add = vibrato >> chip->vibratoShift;
538 		//Sign extend over the shift value
539 		Bit32s neg = chip->vibratoSign;
540 		//Negate the add with -1 or 0
541 		add = ( add ^ neg ) - neg;
542 		waveCurrent += add;
543 	}
544 }
545 
KeyOn(Bit8u mask)546 void Operator::KeyOn( Bit8u mask ) {
547 	if ( !keyOn ) {
548 		//Restart the frequency generator
549 #if ( DBOPL_WAVE > WAVE_HANDLER )
550 		waveIndex = waveStart;
551 #else
552 		waveIndex = 0;
553 #endif
554 		rateIndex = 0;
555 		SetState( ATTACK );
556 	}
557 	keyOn |= mask;
558 }
559 
KeyOff(Bit8u mask)560 void Operator::KeyOff( Bit8u mask ) {
561 	keyOn &= ~mask;
562 	if ( !keyOn ) {
563 		if ( state != OFF ) {
564 			SetState( RELEASE );
565 		}
566 	}
567 }
568 
GetWave(Bitu index,Bitu vol)569 INLINE Bits Operator::GetWave( Bitu index, Bitu vol ) {
570 #if ( DBOPL_WAVE == WAVE_HANDLER )
571 	return waveHandler( index, vol << ( 3 - ENV_EXTRA ) );
572 #elif ( DBOPL_WAVE == WAVE_TABLEMUL )
573 	return (waveBase[ index & waveMask ] * MulTable[ vol >> ENV_EXTRA ]) >> MUL_SH;
574 #elif ( DBOPL_WAVE == WAVE_TABLELOG )
575 	Bit32s wave = waveBase[ index & waveMask ];
576 	Bit32u total = ( wave & 0x7fff ) + vol << ( 3 - ENV_EXTRA );
577 	Bit32s sig = ExpTable[ total & 0xff ];
578 	Bit32u exp = total >> 8;
579 	Bit32s neg = wave >> 16;
580 	return ((sig ^ neg) - neg) >> exp;
581 #else
582 #error "No valid wave routine"
583 #endif
584 }
585 
GetSample(Bits modulation)586 INLINE Bits Operator::GetSample( Bits modulation ) {
587 	Bitu vol = ForwardVolume();
588 	if ( ENV_SILENT( vol ) ) {
589 		//Simply forward the wave
590 		waveIndex += waveCurrent;
591 		return 0;
592 	} else {
593 		Bitu index = ForwardWave();
594 		index += modulation;
595 		return GetWave( index, vol );
596 	}
597 }
598 
Operator()599 Operator::Operator() {
600 	chanData = 0;
601 	freqMul = 0;
602 	waveIndex = 0;
603 	waveAdd = 0;
604 	waveCurrent = 0;
605 	keyOn = 0;
606 	ksr = 0;
607 	reg20 = 0;
608 	reg40 = 0;
609 	reg60 = 0;
610 	reg80 = 0;
611 	regE0 = 0;
612 	SetState( OFF );
613 	rateZero = (1 << OFF);
614 	sustainLevel = ENV_MAX;
615 	currentLevel = ENV_MAX;
616 	totalLevel = ENV_MAX;
617 	volume = ENV_MAX;
618 	releaseAdd = 0;
619 }
620 
621 /*
622 	Channel
623 */
624 
Channel()625 Channel::Channel() {
626 	old[0] = old[1] = 0;
627 	chanData = 0;
628 	regB0 = 0;
629 	regC0 = 0;
630 	maskLeft = -1;
631 	maskRight = -1;
632 	feedback = 31;
633 	fourMask = 0;
634 	synthHandler = &Channel::BlockTemplate< sm2FM >;
635 }
636 
SetChanData(const Chip * chip,Bit32u data)637 void Channel::SetChanData( const Chip* chip, Bit32u data ) {
638 	Bit32u change = chanData ^ data;
639 	chanData = data;
640 	Op( 0 )->chanData = data;
641 	Op( 1 )->chanData = data;
642 	//Since a frequency update triggered this, always update frequency
643 	Op( 0 )->UpdateFrequency();
644 	Op( 1 )->UpdateFrequency();
645 	if ( change & ( 0xff << SHIFT_KSLBASE ) ) {
646 		Op( 0 )->UpdateAttenuation();
647 		Op( 1 )->UpdateAttenuation();
648 	}
649 	if ( change & ( 0xff << SHIFT_KEYCODE ) ) {
650 		Op( 0 )->UpdateRates( chip );
651 		Op( 1 )->UpdateRates( chip );
652 	}
653 }
654 
UpdateFrequency(const Chip * chip,Bit8u fourOp)655 void Channel::UpdateFrequency( const Chip* chip, Bit8u fourOp ) {
656 	//Extrace the frequency bits
657 	Bit32u data = chanData & 0xffff;
658 	Bit32u kslBase = KslTable[ data >> 6 ];
659 	Bit32u keyCode = ( data & 0x1c00) >> 9;
660 	if ( chip->reg08 & 0x40 ) {
661 		keyCode |= ( data & 0x100)>>8;	/* notesel == 1 */
662 	} else {
663 		keyCode |= ( data & 0x200)>>9;	/* notesel == 0 */
664 	}
665 	//Add the keycode and ksl into the highest bits of chanData
666 	data |= (keyCode << SHIFT_KEYCODE) | ( kslBase << SHIFT_KSLBASE );
667 	( this + 0 )->SetChanData( chip, data );
668 	if ( fourOp & 0x3f ) {
669 		( this + 1 )->SetChanData( chip, data );
670 	}
671 }
672 
WriteA0(const Chip * chip,Bit8u val)673 void Channel::WriteA0( const Chip* chip, Bit8u val ) {
674 	Bit8u fourOp = chip->reg104 & chip->opl3Active & fourMask;
675 	//Don't handle writes to silent fourop channels
676 	if ( fourOp > 0x80 )
677 		return;
678 	Bit32u change = (chanData ^ val ) & 0xff;
679 	if ( change ) {
680 		chanData ^= change;
681 		UpdateFrequency( chip, fourOp );
682 	}
683 }
684 
WriteB0(const Chip * chip,Bit8u val)685 void Channel::WriteB0( const Chip* chip, Bit8u val ) {
686 	Bit8u fourOp = chip->reg104 & chip->opl3Active & fourMask;
687 	//Don't handle writes to silent fourop channels
688 	if ( fourOp > 0x80 )
689 		return;
690 	Bitu change = (chanData ^ ( val << 8 ) ) & 0x1f00;
691 	if ( change ) {
692 		chanData ^= change;
693 		UpdateFrequency( chip, fourOp );
694 	}
695 	//Check for a change in the keyon/off state
696 	if ( !(( val ^ regB0) & 0x20))
697 		return;
698 	regB0 = val;
699 	if ( val & 0x20 ) {
700 		Op(0)->KeyOn( 0x1 );
701 		Op(1)->KeyOn( 0x1 );
702 		if ( fourOp & 0x3f ) {
703 			( this + 1 )->Op(0)->KeyOn( 1 );
704 			( this + 1 )->Op(1)->KeyOn( 1 );
705 		}
706 	} else {
707 		Op(0)->KeyOff( 0x1 );
708 		Op(1)->KeyOff( 0x1 );
709 		if ( fourOp & 0x3f ) {
710 			( this + 1 )->Op(0)->KeyOff( 1 );
711 			( this + 1 )->Op(1)->KeyOff( 1 );
712 		}
713 	}
714 }
715 
WriteC0(const Chip * chip,Bit8u val)716 void Channel::WriteC0( const Chip* chip, Bit8u val ) {
717 	Bit8u change = val ^ regC0;
718 	if ( !change )
719 		return;
720 	regC0 = val;
721 	feedback = ( val >> 1 ) & 7;
722 	if ( feedback ) {
723 		//We shift the input to the right 10 bit wave index value
724 		feedback = 9 - feedback;
725 	} else {
726 		feedback = 31;
727 	}
728 	//Select the new synth mode
729 	if ( chip->opl3Active ) {
730 		//4-op mode enabled for this channel
731 		if ( (chip->reg104 & fourMask) & 0x3f ) {
732 			Channel* chan0, *chan1;
733 			//Check if it's the 2nd channel in a 4-op
734 			if ( !(fourMask & 0x80 ) ) {
735 				chan0 = this;
736 				chan1 = this + 1;
737 			} else {
738 				chan0 = this - 1;
739 				chan1 = this;
740 			}
741 
742 			Bit8u synth = ( (chan0->regC0 & 1) << 0 )| (( chan1->regC0 & 1) << 1 );
743 			switch ( synth ) {
744 			case 0:
745 				chan0->synthHandler = &Channel::BlockTemplate< sm3FMFM >;
746 				break;
747 			case 1:
748 				chan0->synthHandler = &Channel::BlockTemplate< sm3AMFM >;
749 				break;
750 			case 2:
751 				chan0->synthHandler = &Channel::BlockTemplate< sm3FMAM >;
752 				break;
753 			case 3:
754 				chan0->synthHandler = &Channel::BlockTemplate< sm3AMAM >;
755 				break;
756 			}
757 		//Disable updating percussion channels
758 		} else if ((fourMask & 0x40) && ( chip->regBD & 0x20) ) {
759 
760 		//Regular dual op, am or fm
761 		} else if ( val & 1 ) {
762 			synthHandler = &Channel::BlockTemplate< sm3AM >;
763 		} else {
764 			synthHandler = &Channel::BlockTemplate< sm3FM >;
765 		}
766 		maskLeft = ( val & 0x10 ) ? -1 : 0;
767 		maskRight = ( val & 0x20 ) ? -1 : 0;
768 	//opl2 active
769 	} else {
770 		//Disable updating percussion channels
771 		if ( (fourMask & 0x40) && ( chip->regBD & 0x20 ) ) {
772 
773 		//Regular dual op, am or fm
774 		} else if ( val & 1 ) {
775 			synthHandler = &Channel::BlockTemplate< sm2AM >;
776 		} else {
777 			synthHandler = &Channel::BlockTemplate< sm2FM >;
778 		}
779 	}
780 }
781 
ResetC0(const Chip * chip)782 void Channel::ResetC0( const Chip* chip ) {
783 	Bit8u val = regC0;
784 	regC0 ^= 0xff;
785 	WriteC0( chip, val );
786 }
787 
788 template< bool opl3Mode>
GeneratePercussion(Chip * chip,Bit32s * output)789 INLINE void Channel::GeneratePercussion( Chip* chip, Bit32s* output ) {
790 	Channel* chan = this;
791 
792 	//BassDrum
793 	Bit32s mod = (Bit32u)((old[0] + old[1])) >> feedback;
794 	old[0] = old[1];
795 	old[1] = Op(0)->GetSample( mod );
796 
797 	//When bassdrum is in AM mode first operator is ignoed
798 	if ( chan->regC0 & 1 ) {
799 		mod = 0;
800 	} else {
801 		mod = old[0];
802 	}
803 	Bit32s sample = Op(1)->GetSample( mod );
804 
805 
806 	//Precalculate stuff used by other outputs
807 	Bit32u noiseBit = chip->ForwardNoise() & 0x1;
808 	Bit32u c2 = Op(2)->ForwardWave();
809 	Bit32u c5 = Op(5)->ForwardWave();
810 	Bit32u phaseBit = (((c2 & 0x88) ^ ((c2<<5) & 0x80)) | ((c5 ^ (c5<<2)) & 0x20)) ? 0x02 : 0x00;
811 
812 	//Hi-Hat
813 	Bit32u hhVol = Op(2)->ForwardVolume();
814 	if ( !ENV_SILENT( hhVol ) ) {
815 		Bit32u hhIndex = (phaseBit<<8) | (0x34 << ( phaseBit ^ (noiseBit << 1 )));
816 		sample += Op(2)->GetWave( hhIndex, hhVol );
817 	}
818 	//Snare Drum
819 	Bit32u sdVol = Op(3)->ForwardVolume();
820 	if ( !ENV_SILENT( sdVol ) ) {
821 		Bit32u sdIndex = ( 0x100 + (c2 & 0x100) ) ^ ( noiseBit << 8 );
822 		sample += Op(3)->GetWave( sdIndex, sdVol );
823 	}
824 	//Tom-tom
825 	sample += Op(4)->GetSample( 0 );
826 
827 	//Top-Cymbal
828 	Bit32u tcVol = Op(5)->ForwardVolume();
829 	if ( !ENV_SILENT( tcVol ) ) {
830 		Bit32u tcIndex = (1 + phaseBit) << 8;
831 		sample += Op(5)->GetWave( tcIndex, tcVol );
832 	}
833 	sample <<= 1;
834 	if ( opl3Mode ) {
835 		output[0] += sample;
836 		output[1] += sample;
837 	} else {
838 		output[0] += sample;
839 	}
840 }
841 
842 template<SynthMode mode>
BlockTemplate(Chip * chip,Bit32u samples,Bit32s * output)843 Channel* Channel::BlockTemplate( Chip* chip, Bit32u samples, Bit32s* output ) {
844 	switch( mode ) {
845 	case sm2AM:
846 	case sm3AM:
847 		if ( Op(0)->Silent() && Op(1)->Silent() ) {
848 			old[0] = old[1] = 0;
849 			return (this + 1);
850 		}
851 		break;
852 	case sm2FM:
853 	case sm3FM:
854 		if ( Op(1)->Silent() ) {
855 			old[0] = old[1] = 0;
856 			return (this + 1);
857 		}
858 		break;
859 	case sm3FMFM:
860 		if ( Op(3)->Silent() ) {
861 			old[0] = old[1] = 0;
862 			return (this + 2);
863 		}
864 		break;
865 	case sm3AMFM:
866 		if ( Op(0)->Silent() && Op(3)->Silent() ) {
867 			old[0] = old[1] = 0;
868 			return (this + 2);
869 		}
870 		break;
871 	case sm3FMAM:
872 		if ( Op(1)->Silent() && Op(3)->Silent() ) {
873 			old[0] = old[1] = 0;
874 			return (this + 2);
875 		}
876 		break;
877 	case sm3AMAM:
878 		if ( Op(0)->Silent() && Op(2)->Silent() && Op(3)->Silent() ) {
879 			old[0] = old[1] = 0;
880 			return (this + 2);
881 		}
882 		break;
883 	case sm2Percussion:
884 		// This case was not handled in the DOSBox code either
885 		// thus we leave this blank.
886 		// TODO: Consider checking this.
887 		break;
888 	case sm3Percussion:
889 		// This case was not handled in the DOSBox code either
890 		// thus we leave this blank.
891 		// TODO: Consider checking this.
892 		break;
893 	case sm4Start:
894 		// This case was not handled in the DOSBox code either
895 		// thus we leave this blank.
896 		// TODO: Consider checking this.
897 		break;
898 	case sm6Start:
899 		// This case was not handled in the DOSBox code either
900 		// thus we leave this blank.
901 		// TODO: Consider checking this.
902 		break;
903 	}
904 	//Init the operators with the the current vibrato and tremolo values
905 	Op( 0 )->Prepare( chip );
906 	Op( 1 )->Prepare( chip );
907 	if ( mode > sm4Start ) {
908 		Op( 2 )->Prepare( chip );
909 		Op( 3 )->Prepare( chip );
910 	}
911 	if ( mode > sm6Start ) {
912 		Op( 4 )->Prepare( chip );
913 		Op( 5 )->Prepare( chip );
914 	}
915 	for ( Bitu i = 0; i < samples; i++ ) {
916 		//Early out for percussion handlers
917 		if ( mode == sm2Percussion ) {
918 			GeneratePercussion<false>( chip, output + i );
919 			continue;	//Prevent some unitialized value bitching
920 		} else if ( mode == sm3Percussion ) {
921 			GeneratePercussion<true>( chip, output + i * 2 );
922 			continue;	//Prevent some unitialized value bitching
923 		}
924 
925 		//Do unsigned shift so we can shift out all bits but still stay in 10 bit range otherwise
926 		Bit32s mod = (Bit32u)((old[0] + old[1])) >> feedback;
927 		old[0] = old[1];
928 		old[1] = Op(0)->GetSample( mod );
929 		Bit32s sample;
930 		Bit32s out0 = old[0];
931 		if ( mode == sm2AM || mode == sm3AM ) {
932 			sample = out0 + Op(1)->GetSample( 0 );
933 		} else if ( mode == sm2FM || mode == sm3FM ) {
934 			sample = Op(1)->GetSample( out0 );
935 		} else if ( mode == sm3FMFM ) {
936 			Bits next = Op(1)->GetSample( out0 );
937 			next = Op(2)->GetSample( next );
938 			sample = Op(3)->GetSample( next );
939 		} else if ( mode == sm3AMFM ) {
940 			sample = out0;
941 			Bits next = Op(1)->GetSample( 0 );
942 			next = Op(2)->GetSample( next );
943 			sample += Op(3)->GetSample( next );
944 		} else if ( mode == sm3FMAM ) {
945 			sample = Op(1)->GetSample( out0 );
946 			Bits next = Op(2)->GetSample( 0 );
947 			sample += Op(3)->GetSample( next );
948 		} else if ( mode == sm3AMAM ) {
949 			sample = out0;
950 			Bits next = Op(1)->GetSample( 0 );
951 			sample += Op(2)->GetSample( next );
952 			sample += Op(3)->GetSample( 0 );
953 		}
954 		switch( mode ) {
955 		case sm2AM:
956 		case sm2FM:
957 			output[ i ] += sample;
958 			break;
959 		case sm3AM:
960 		case sm3FM:
961 		case sm3FMFM:
962 		case sm3AMFM:
963 		case sm3FMAM:
964 		case sm3AMAM:
965 			output[ i * 2 + 0 ] += sample & maskLeft;
966 			output[ i * 2 + 1 ] += sample & maskRight;
967 			break;
968 		case sm2Percussion:
969 			// This case was not handled in the DOSBox code either
970 			// thus we leave this blank.
971 			// TODO: Consider checking this.
972 			break;
973 		case sm3Percussion:
974 			// This case was not handled in the DOSBox code either
975 			// thus we leave this blank.
976 			// TODO: Consider checking this.
977 			break;
978 		case sm4Start:
979 			// This case was not handled in the DOSBox code either
980 			// thus we leave this blank.
981 			// TODO: Consider checking this.
982 			break;
983 		case sm6Start:
984 			// This case was not handled in the DOSBox code either
985 			// thus we leave this blank.
986 			// TODO: Consider checking this.
987 			break;
988 		}
989 	}
990 	switch( mode ) {
991 	case sm2AM:
992 	case sm2FM:
993 	case sm3AM:
994 	case sm3FM:
995 		return ( this + 1 );
996 	case sm3FMFM:
997 	case sm3AMFM:
998 	case sm3FMAM:
999 	case sm3AMAM:
1000 		return( this + 2 );
1001 	case sm2Percussion:
1002 	case sm3Percussion:
1003 		return( this + 3 );
1004 	case sm4Start:
1005 		// This case was not handled in the DOSBox code either
1006 		// thus we leave this blank.
1007 		// TODO: Consider checking this.
1008 		break;
1009 	case sm6Start:
1010 		// This case was not handled in the DOSBox code either
1011 		// thus we leave this blank.
1012 		// TODO: Consider checking this.
1013 		break;
1014 	}
1015 	return 0;
1016 }
1017 
1018 /*
1019 	Chip
1020 */
1021 
Chip()1022 Chip::Chip() {
1023 	reg08 = 0;
1024 	reg04 = 0;
1025 	regBD = 0;
1026 	reg104 = 0;
1027 	opl3Active = 0;
1028 }
1029 
ForwardNoise()1030 INLINE Bit32u Chip::ForwardNoise() {
1031 	noiseCounter += noiseAdd;
1032 	Bitu count = noiseCounter >> LFO_SH;
1033 	noiseCounter &= WAVE_MASK;
1034 	for ( ; count > 0; --count ) {
1035 		//Noise calculation from mame
1036 		noiseValue ^= ( 0x800302 ) & ( 0 - (noiseValue & 1 ) );
1037 		noiseValue >>= 1;
1038 	}
1039 	return noiseValue;
1040 }
1041 
ForwardLFO(Bit32u samples)1042 INLINE Bit32u Chip::ForwardLFO( Bit32u samples ) {
1043 	//Current vibrato value, runs 4x slower than tremolo
1044 	vibratoSign = ( VibratoTable[ vibratoIndex >> 2] ) >> 7;
1045 	vibratoShift = ( VibratoTable[ vibratoIndex >> 2] & 7) + vibratoStrength;
1046 	tremoloValue = TremoloTable[ tremoloIndex ] >> tremoloStrength;
1047 
1048 	//Check hom many samples there can be done before the value changes
1049 	Bit32u todo = LFO_MAX - lfoCounter;
1050 	Bit32u count = (todo + lfoAdd - 1) / lfoAdd;
1051 	if ( count > samples ) {
1052 		count = samples;
1053 		lfoCounter += count * lfoAdd;
1054 	} else {
1055 		lfoCounter += count * lfoAdd;
1056 		lfoCounter &= (LFO_MAX - 1);
1057 		//Maximum of 7 vibrato value * 4
1058 		vibratoIndex = ( vibratoIndex + 1 ) & 31;
1059 		//Clip tremolo to the the table size
1060 		if ( tremoloIndex + 1 < TREMOLO_TABLE  )
1061 			++tremoloIndex;
1062 		else
1063 			tremoloIndex = 0;
1064 	}
1065 	return count;
1066 }
1067 
1068 
WriteBD(Bit8u val)1069 void Chip::WriteBD( Bit8u val ) {
1070 	Bit8u change = regBD ^ val;
1071 	if ( !change )
1072 		return;
1073 	regBD = val;
1074 	//TODO could do this with shift and xor?
1075 	vibratoStrength = (val & 0x40) ? 0x00 : 0x01;
1076 	tremoloStrength = (val & 0x80) ? 0x00 : 0x02;
1077 	if ( val & 0x20 ) {
1078 		//Drum was just enabled, make sure channel 6 has the right synth
1079 		if ( change & 0x20 ) {
1080 			if ( opl3Active ) {
1081 				chan[6].synthHandler = &Channel::BlockTemplate< sm3Percussion >;
1082 			} else {
1083 				chan[6].synthHandler = &Channel::BlockTemplate< sm2Percussion >;
1084 			}
1085 		}
1086 		//Bass Drum
1087 		if ( val & 0x10 ) {
1088 			chan[6].op[0].KeyOn( 0x2 );
1089 			chan[6].op[1].KeyOn( 0x2 );
1090 		} else {
1091 			chan[6].op[0].KeyOff( 0x2 );
1092 			chan[6].op[1].KeyOff( 0x2 );
1093 		}
1094 		//Hi-Hat
1095 		if ( val & 0x1 ) {
1096 			chan[7].op[0].KeyOn( 0x2 );
1097 		} else {
1098 			chan[7].op[0].KeyOff( 0x2 );
1099 		}
1100 		//Snare
1101 		if ( val & 0x8 ) {
1102 			chan[7].op[1].KeyOn( 0x2 );
1103 		} else {
1104 			chan[7].op[1].KeyOff( 0x2 );
1105 		}
1106 		//Tom-Tom
1107 		if ( val & 0x4 ) {
1108 			chan[8].op[0].KeyOn( 0x2 );
1109 		} else {
1110 			chan[8].op[0].KeyOff( 0x2 );
1111 		}
1112 		//Top Cymbal
1113 		if ( val & 0x2 ) {
1114 			chan[8].op[1].KeyOn( 0x2 );
1115 		} else {
1116 			chan[8].op[1].KeyOff( 0x2 );
1117 		}
1118 	//Toggle keyoffs when we turn off the percussion
1119 	} else if ( change & 0x20 ) {
1120 		//Trigger a reset to setup the original synth handler
1121 		chan[6].ResetC0( this );
1122 		chan[6].op[0].KeyOff( 0x2 );
1123 		chan[6].op[1].KeyOff( 0x2 );
1124 		chan[7].op[0].KeyOff( 0x2 );
1125 		chan[7].op[1].KeyOff( 0x2 );
1126 		chan[8].op[0].KeyOff( 0x2 );
1127 		chan[8].op[1].KeyOff( 0x2 );
1128 	}
1129 }
1130 
1131 
1132 #define REGOP( _FUNC_ )															\
1133 	index = ( ( reg >> 3) & 0x20 ) | ( reg & 0x1f );								\
1134 	if ( OpOffsetTable[ index ] ) {													\
1135 		Operator* regOp = (Operator *)( ((char *)this ) + OpOffsetTable[ index ] );	\
1136 		regOp->_FUNC_( this, val );													\
1137 	}
1138 
1139 #define REGCHAN( _FUNC_ )																\
1140 	index = ( ( reg >> 4) & 0x10 ) | ( reg & 0xf );										\
1141 	if ( ChanOffsetTable[ index ] ) {													\
1142 		Channel* regChan = (Channel *)( ((char *)this ) + ChanOffsetTable[ index ] );	\
1143 		regChan->_FUNC_( this, val );													\
1144 	}
1145 
WriteReg(Bit32u reg,Bit8u val)1146 void Chip::WriteReg( Bit32u reg, Bit8u val ) {
1147 	Bitu index;
1148 	switch ( (reg & 0xf0) >> 4 ) {
1149 	case 0x00 >> 4:
1150 		if ( reg == 0x01 ) {
1151 			waveFormMask = ( val & 0x20 ) ? 0x7 : 0x0;
1152 		} else if ( reg == 0x104 ) {
1153 			//Only detect changes in lowest 6 bits
1154 			if ( !((reg104 ^ val) & 0x3f) )
1155 				return;
1156 			//Always keep the highest bit enabled, for checking > 0x80
1157 			reg104 = 0x80 | ( val & 0x3f );
1158 		} else if ( reg == 0x105 ) {
1159 			//MAME says the real opl3 doesn't reset anything on opl3 disable/enable till the next write in another register
1160 			if ( !((opl3Active ^ val) & 1 ) )
1161 				return;
1162 			opl3Active = ( val & 1 ) ? 0xff : 0;
1163 			//Update the 0xc0 register for all channels to signal the switch to mono/stereo handlers
1164 			for ( int i = 0; i < 18;i++ ) {
1165 				chan[i].ResetC0( this );
1166 			}
1167 		} else if ( reg == 0x08 ) {
1168 			reg08 = val;
1169 		}
1170 	case 0x10 >> 4:
1171 		break;
1172 	case 0x20 >> 4:
1173 	case 0x30 >> 4:
1174 		REGOP( Write20 );
1175 		break;
1176 	case 0x40 >> 4:
1177 	case 0x50 >> 4:
1178 		REGOP( Write40 );
1179 		break;
1180 	case 0x60 >> 4:
1181 	case 0x70 >> 4:
1182 		REGOP( Write60 );
1183 		break;
1184 	case 0x80 >> 4:
1185 	case 0x90 >> 4:
1186 		REGOP( Write80 );
1187 		break;
1188 	case 0xa0 >> 4:
1189 		REGCHAN( WriteA0 );
1190 		break;
1191 	case 0xb0 >> 4:
1192 		if ( reg == 0xbd ) {
1193 			WriteBD( val );
1194 		} else {
1195 			REGCHAN( WriteB0 );
1196 		}
1197 		break;
1198 	case 0xc0 >> 4:
1199 		REGCHAN( WriteC0 );
1200 	case 0xd0 >> 4:
1201 		break;
1202 	case 0xe0 >> 4:
1203 	case 0xf0 >> 4:
1204 		REGOP( WriteE0 );
1205 		break;
1206 	}
1207 }
1208 
1209 
WriteAddr(Bit32u port,Bit8u val)1210 Bit32u Chip::WriteAddr( Bit32u port, Bit8u val ) {
1211 	switch ( port & 3 ) {
1212 	case 0:
1213 		return val;
1214 	case 2:
1215 		if ( opl3Active || (val == 0x05) )
1216 			return 0x100 | val;
1217 		else
1218 			return val;
1219 	}
1220 	return 0;
1221 }
1222 
GenerateBlock2(Bitu total,Bit32s * output)1223 void Chip::GenerateBlock2( Bitu total, Bit32s* output ) {
1224 	while ( total > 0 ) {
1225 		Bit32u samples = ForwardLFO( total );
1226 		memset(output, 0, sizeof(Bit32s) * samples);
1227 		int count = 0;
1228 		for( Channel* ch = chan; ch < chan + 9; ) {
1229 			count++;
1230 			ch = (ch->*(ch->synthHandler))( this, samples, output );
1231 		}
1232 		total -= samples;
1233 		output += samples;
1234 	}
1235 }
1236 
GenerateBlock3(Bitu total,Bit32s * output)1237 void Chip::GenerateBlock3( Bitu total, Bit32s* output  ) {
1238 	while ( total > 0 ) {
1239 		Bit32u samples = ForwardLFO( total );
1240 		memset(output, 0, sizeof(Bit32s) * samples * 2);
1241 		int count = 0;
1242 		for( Channel* ch = chan; ch < chan + 18; ) {
1243 			count++;
1244 			ch = (ch->*(ch->synthHandler))( this, samples, output );
1245 		}
1246 		total -= samples;
1247 		output += samples * 2;
1248 	}
1249 }
1250 
Setup(Bit32u rate)1251 void Chip::Setup( Bit32u rate ) {
1252 	double scale = OPLRATE / (double)rate;
1253 
1254 	//Noise counter is run at the same precision as general waves
1255 	noiseAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) );
1256 	noiseCounter = 0;
1257 	noiseValue = 1;	//Make sure it triggers the noise xor the first time
1258 	//The low frequency oscillation counter
1259 	//Every time his overflows vibrato and tremoloindex are increased
1260 	lfoAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) );
1261 	lfoCounter = 0;
1262 	vibratoIndex = 0;
1263 	tremoloIndex = 0;
1264 
1265 	//With higher octave this gets shifted up
1266 	//-1 since the freqCreateTable = *2
1267 #ifdef WAVE_PRECISION
1268 	double freqScale = ( 1 << 7 ) * scale * ( 1 << ( WAVE_SH - 1 - 10));
1269 	for ( int i = 0; i < 16; i++ ) {
1270 		freqMul[i] = (Bit32u)( 0.5 + freqScale * FreqCreateTable[ i ] );
1271 	}
1272 #else
1273 	Bit32u freqScale = (Bit32u)( 0.5 + scale * ( 1 << ( WAVE_SH - 1 - 10)));
1274 	for ( int i = 0; i < 16; i++ ) {
1275 		freqMul[i] = freqScale * FreqCreateTable[ i ];
1276 	}
1277 #endif
1278 
1279 	//-3 since the real envelope takes 8 steps to reach the single value we supply
1280 	for ( Bit8u i = 0; i < 76; i++ ) {
1281 		Bit8u index, shift;
1282 		EnvelopeSelect( i, index, shift );
1283 		linearRates[i] = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH + ENV_EXTRA - shift - 3 )));
1284 	}
1285 	//Generate the best matching attack rate
1286 	for ( Bit8u i = 0; i < 62; i++ ) {
1287 		Bit8u index, shift;
1288 		EnvelopeSelect( i, index, shift );
1289 		//Original amount of samples the attack would take
1290 		Bit32s original = (Bit32u)( (AttackSamplesTable[ index ] << shift) / scale);
1291 
1292 		Bit32s guessAdd = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH - shift - 3 )));
1293 		Bit32s bestAdd = guessAdd;
1294 		Bit32u bestDiff = 1 << 30;
1295 		for( Bit32u passes = 0; passes < 16; passes ++ ) {
1296 			Bit32s volume = ENV_MAX;
1297 			Bit32s samples = 0;
1298 			Bit32u count = 0;
1299 			while ( volume > 0 && samples < original * 2 ) {
1300 				count += guessAdd;
1301 				Bit32s change = count >> RATE_SH;
1302 				count &= RATE_MASK;
1303 				if ( GCC_UNLIKELY(change) ) { // less than 1 %
1304 					volume += ( ~volume * change ) >> 3;
1305 				}
1306 				samples++;
1307 
1308 			}
1309 			Bit32s diff = original - samples;
1310 			Bit32u lDiff = labs( diff );
1311 			//Init last on first pass
1312 			if ( lDiff < bestDiff ) {
1313 				bestDiff = lDiff;
1314 				bestAdd = guessAdd;
1315 				if ( !bestDiff )
1316 					break;
1317 			}
1318 			//Below our target
1319 			if ( diff < 0 ) {
1320 				//Better than the last time
1321 				Bit32s mul = ((original - diff) << 12) / original;
1322 				guessAdd = ((guessAdd * mul) >> 12);
1323 				guessAdd++;
1324 			} else if ( diff > 0 ) {
1325 				Bit32s mul = ((original - diff) << 12) / original;
1326 				guessAdd = (guessAdd * mul) >> 12;
1327 				guessAdd--;
1328 			}
1329 		}
1330 		attackRates[i] = bestAdd;
1331 	}
1332 	for ( Bit8u i = 62; i < 76; i++ ) {
1333 		//This should provide instant volume maximizing
1334 		attackRates[i] = 8 << RATE_SH;
1335 	}
1336 	//Setup the channels with the correct four op flags
1337 	//Channels are accessed through a table so they appear linear here
1338 	chan[ 0].fourMask = 0x00 | ( 1 << 0 );
1339 	chan[ 1].fourMask = 0x80 | ( 1 << 0 );
1340 	chan[ 2].fourMask = 0x00 | ( 1 << 1 );
1341 	chan[ 3].fourMask = 0x80 | ( 1 << 1 );
1342 	chan[ 4].fourMask = 0x00 | ( 1 << 2 );
1343 	chan[ 5].fourMask = 0x80 | ( 1 << 2 );
1344 
1345 	chan[ 9].fourMask = 0x00 | ( 1 << 3 );
1346 	chan[10].fourMask = 0x80 | ( 1 << 3 );
1347 	chan[11].fourMask = 0x00 | ( 1 << 4 );
1348 	chan[12].fourMask = 0x80 | ( 1 << 4 );
1349 	chan[13].fourMask = 0x00 | ( 1 << 5 );
1350 	chan[14].fourMask = 0x80 | ( 1 << 5 );
1351 
1352 	//mark the percussion channels
1353 	chan[ 6].fourMask = 0x40;
1354 	chan[ 7].fourMask = 0x40;
1355 	chan[ 8].fourMask = 0x40;
1356 
1357 	//Clear Everything in opl3 mode
1358 	WriteReg( 0x105, 0x1 );
1359 	for ( int i = 0; i < 512; i++ ) {
1360 		if ( i == 0x105 )
1361 			continue;
1362 		WriteReg( i, 0xff );
1363 		WriteReg( i, 0x0 );
1364 	}
1365 	WriteReg( 0x105, 0x0 );
1366 	//Clear everything in opl2 mode
1367 	for ( int i = 0; i < 255; i++ ) {
1368 		WriteReg( i, 0xff );
1369 		WriteReg( i, 0x0 );
1370 	}
1371 }
1372 
1373 static bool doneTables = false;
InitTables(void)1374 void InitTables( void ) {
1375 	if ( doneTables )
1376 		return;
1377 	doneTables = true;
1378 #if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG )
1379 	//Exponential volume table, same as the real adlib
1380 	for ( int i = 0; i < 256; i++ ) {
1381 		//Save them in reverse
1382 		ExpTable[i] = (int)( 0.5 + ( pow(2.0, ( 255 - i) * ( 1.0 /256 ) )-1) * 1024 );
1383 		ExpTable[i] += 1024; //or remove the -1 oh well :)
1384 		//Preshift to the left once so the final volume can shift to the right
1385 		ExpTable[i] *= 2;
1386 	}
1387 #endif
1388 #if ( DBOPL_WAVE == WAVE_HANDLER )
1389 	//Add 0.5 for the trunc rounding of the integer cast
1390 	//Do a PI sinetable instead of the original 0.5 PI
1391 	for ( int i = 0; i < 512; i++ ) {
1392 		SinTable[i] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (M_PI / 512.0) ) ) / log10(2.0)*256 );
1393 	}
1394 #endif
1395 #if ( DBOPL_WAVE == WAVE_TABLEMUL )
1396 	//Multiplication based tables
1397 	for ( int i = 0; i < 384; i++ ) {
1398 		int s = i * 8;
1399 		//TODO maybe keep some of the precision errors of the original table?
1400 		double val = ( 0.5 + ( pow(2.0, -1.0 + ( 255 - s) * ( 1.0 /256 ) )) * ( 1 << MUL_SH ));
1401 		MulTable[i] = (Bit16u)(val);
1402 	}
1403 
1404 	//Sine Wave Base
1405 	for ( int i = 0; i < 512; i++ ) {
1406 		WaveTable[ 0x0200 + i ] = (Bit16s)(sin( (i + 0.5) * (M_PI / 512.0) ) * 4084);
1407 		WaveTable[ 0x0000 + i ] = -WaveTable[ 0x200 + i ];
1408 	}
1409 	//Exponential wave
1410 	for ( int i = 0; i < 256; i++ ) {
1411 		WaveTable[ 0x700 + i ] = (Bit16s)( 0.5 + ( pow(2.0, -1.0 + ( 255 - i * 8) * ( 1.0 /256 ) ) ) * 4085 );
1412 		WaveTable[ 0x6ff - i ] = -WaveTable[ 0x700 + i ];
1413 	}
1414 #endif
1415 #if ( DBOPL_WAVE == WAVE_TABLELOG )
1416 	//Sine Wave Base
1417 	for ( int i = 0; i < 512; i++ ) {
1418 		WaveTable[ 0x0200 + i ] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (M_PI / 512.0) ) ) / log10(2.0)*256 );
1419 		WaveTable[ 0x0000 + i ] = ((Bit16s)0x8000) | WaveTable[ 0x200 + i];
1420 	}
1421 	//Exponential wave
1422 	for ( int i = 0; i < 256; i++ ) {
1423 		WaveTable[ 0x700 + i ] = i * 8;
1424 		WaveTable[ 0x6ff - i ] = ((Bit16s)0x8000) | i * 8;
1425 	}
1426 #endif
1427 
1428 	//	|    |//\\|____|WAV7|//__|/\  |____|/\/\|
1429 	//	|\\//|    |    |WAV7|    |  \/|    |    |
1430 	//	|06  |0126|27  |7   |3   |4   |4 5 |5   |
1431 
1432 #if (( DBOPL_WAVE == WAVE_TABLELOG ) || ( DBOPL_WAVE == WAVE_TABLEMUL ))
1433 	for ( int i = 0; i < 256; i++ ) {
1434 		//Fill silence gaps
1435 		WaveTable[ 0x400 + i ] = WaveTable[0];
1436 		WaveTable[ 0x500 + i ] = WaveTable[0];
1437 		WaveTable[ 0x900 + i ] = WaveTable[0];
1438 		WaveTable[ 0xc00 + i ] = WaveTable[0];
1439 		WaveTable[ 0xd00 + i ] = WaveTable[0];
1440 		//Replicate sines in other pieces
1441 		WaveTable[ 0x800 + i ] = WaveTable[ 0x200 + i ];
1442 		//double speed sines
1443 		WaveTable[ 0xa00 + i ] = WaveTable[ 0x200 + i * 2 ];
1444 		WaveTable[ 0xb00 + i ] = WaveTable[ 0x000 + i * 2 ];
1445 		WaveTable[ 0xe00 + i ] = WaveTable[ 0x200 + i * 2 ];
1446 		WaveTable[ 0xf00 + i ] = WaveTable[ 0x200 + i * 2 ];
1447 	}
1448 #endif
1449 
1450 	//Create the ksl table
1451 	for ( int oct = 0; oct < 8; oct++ ) {
1452 		int base = oct * 8;
1453 		for ( int i = 0; i < 16; i++ ) {
1454 			int val = base - KslCreateTable[i];
1455 			if ( val < 0 )
1456 				val = 0;
1457 			//*4 for the final range to match attenuation range
1458 			KslTable[ oct * 16 + i ] = val * 4;
1459 		}
1460 	}
1461 	//Create the Tremolo table, just increase and decrease a triangle wave
1462 	for ( Bit8u i = 0; i < TREMOLO_TABLE / 2; i++ ) {
1463 		Bit8u val = i << ENV_EXTRA;
1464 		TremoloTable[i] = val;
1465 		TremoloTable[TREMOLO_TABLE - 1 - i] = val;
1466 	}
1467 	//Create a table with offsets of the channels from the start of the chip
1468 	DBOPL::Chip* chip = 0;
1469 	for ( Bitu i = 0; i < 32; i++ ) {
1470 		Bitu index = i & 0xf;
1471 		if ( index >= 9 ) {
1472 			ChanOffsetTable[i] = 0;
1473 			continue;
1474 		}
1475 		//Make sure the four op channels follow eachother
1476 		if ( index < 6 ) {
1477 			index = (index % 3) * 2 + ( index / 3 );
1478 		}
1479 		//Add back the bits for highest ones
1480 		if ( i >= 16 )
1481 			index += 9;
1482 		Bitu blah = reinterpret_cast<size_t>( &(chip->chan[ index ]) );
1483 		ChanOffsetTable[i] = blah;
1484 	}
1485 	//Same for operators
1486 	for ( Bitu i = 0; i < 64; i++ ) {
1487 		if ( i % 8 >= 6 || ( (i / 8) % 4 == 3 ) ) {
1488 			OpOffsetTable[i] = 0;
1489 			continue;
1490 		}
1491 		Bitu chNum = (i / 8) * 3 + (i % 8) % 3;
1492 		//Make sure we use 16 and up for the 2nd range to match the chanoffset gap
1493 		if ( chNum >= 12 )
1494 			chNum += 16 - 12;
1495 		Bitu opNum = ( i % 8 ) / 3;
1496 		DBOPL::Channel* chan = 0;
1497 		Bitu blah = reinterpret_cast<size_t>( &(chan->op[opNum]) );
1498 		OpOffsetTable[i] = ChanOffsetTable[ chNum ] + blah;
1499 	}
1500 #if 0
1501 	//Stupid checks if table's are correct
1502 	for ( Bitu i = 0; i < 18; i++ ) {
1503 		Bit32u find = (Bit16u)( &(chip->chan[ i ]) );
1504 		for ( Bitu c = 0; c < 32; c++ ) {
1505 			if ( ChanOffsetTable[c] == find ) {
1506 				find = 0;
1507 				break;
1508 			}
1509 		}
1510 		if ( find ) {
1511 			find = find;
1512 		}
1513 	}
1514 	for ( Bitu i = 0; i < 36; i++ ) {
1515 		Bit32u find = (Bit16u)( &(chip->chan[ i / 2 ].op[i % 2]) );
1516 		for ( Bitu c = 0; c < 64; c++ ) {
1517 			if ( OpOffsetTable[c] == find ) {
1518 				find = 0;
1519 				break;
1520 			}
1521 		}
1522 		if ( find ) {
1523 			find = find;
1524 		}
1525 	}
1526 #endif
1527 }
1528 
1529 }		//Namespace DBOPL
1530 } // End of namespace DOSBox
1531 } // End of namespace OPL
1532 
1533 #endif // !DISABLE_DOSBOX_OPL
1534