dbopl.cpp 39 KB

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