dbopl.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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. default:
  808. break;
  809. }
  810. //Init the operators with the the current vibrato and tremolo values
  811. Op( 0 )->Prepare( chip );
  812. Op( 1 )->Prepare( chip );
  813. if ( mode > sm4Start ) {
  814. Op( 2 )->Prepare( chip );
  815. Op( 3 )->Prepare( chip );
  816. }
  817. if ( mode > sm6Start ) {
  818. Op( 4 )->Prepare( chip );
  819. Op( 5 )->Prepare( chip );
  820. }
  821. for ( Bitu i = 0; i < samples; i++ ) {
  822. //Early out for percussion handlers
  823. if ( mode == sm2Percussion ) {
  824. GeneratePercussion<false>( chip, output + i );
  825. continue; //Prevent some unitialized value bitching
  826. } else if ( mode == sm3Percussion ) {
  827. GeneratePercussion<true>( chip, output + i * 2 );
  828. continue; //Prevent some unitialized value bitching
  829. }
  830. //Do unsigned shift so we can shift out all bits but still stay in 10 bit range otherwise
  831. Bit32s mod = (Bit32u)((old[0] + old[1])) >> feedback;
  832. old[0] = old[1];
  833. old[1] = Op(0)->GetSample( mod );
  834. Bit32s sample;
  835. Bit32s out0 = old[0];
  836. if ( mode == sm2AM || mode == sm3AM ) {
  837. sample = out0 + Op(1)->GetSample( 0 );
  838. } else if ( mode == sm2FM || mode == sm3FM ) {
  839. sample = Op(1)->GetSample( out0 );
  840. } else if ( mode == sm3FMFM ) {
  841. Bits next = Op(1)->GetSample( out0 );
  842. next = Op(2)->GetSample( next );
  843. sample = Op(3)->GetSample( next );
  844. } else if ( mode == sm3AMFM ) {
  845. sample = out0;
  846. Bits next = Op(1)->GetSample( 0 );
  847. next = Op(2)->GetSample( next );
  848. sample += Op(3)->GetSample( next );
  849. } else if ( mode == sm3FMAM ) {
  850. sample = Op(1)->GetSample( out0 );
  851. Bits next = Op(2)->GetSample( 0 );
  852. sample += Op(3)->GetSample( next );
  853. } else if ( mode == sm3AMAM ) {
  854. sample = out0;
  855. Bits next = Op(1)->GetSample( 0 );
  856. sample += Op(2)->GetSample( next );
  857. sample += Op(3)->GetSample( 0 );
  858. }
  859. switch( mode ) {
  860. case sm2AM:
  861. case sm2FM:
  862. output[ i ] += sample;
  863. break;
  864. case sm3AM:
  865. case sm3FM:
  866. case sm3FMFM:
  867. case sm3AMFM:
  868. case sm3FMAM:
  869. case sm3AMAM:
  870. output[ i * 2 + 0 ] += sample & maskLeft;
  871. output[ i * 2 + 1 ] += sample & maskRight;
  872. break;
  873. default:
  874. break;
  875. }
  876. }
  877. switch( mode ) {
  878. case sm2AM:
  879. case sm2FM:
  880. case sm3AM:
  881. case sm3FM:
  882. return ( this + 1 );
  883. case sm3FMFM:
  884. case sm3AMFM:
  885. case sm3FMAM:
  886. case sm3AMAM:
  887. return( this + 2 );
  888. case sm2Percussion:
  889. case sm3Percussion:
  890. return( this + 3 );
  891. }
  892. return 0;
  893. }
  894. /*
  895. Chip
  896. */
  897. Chip::Chip() {
  898. reg08 = 0;
  899. reg04 = 0;
  900. regBD = 0;
  901. reg104 = 0;
  902. opl3Active = 0;
  903. }
  904. OPL_INLINE Bit32u Chip::ForwardNoise() {
  905. noiseCounter += noiseAdd;
  906. Bitu count = noiseCounter >> LFO_SH;
  907. noiseCounter &= WAVE_MASK;
  908. for ( ; count > 0; --count ) {
  909. //Noise calculation from mame
  910. noiseValue ^= ( 0x800302 ) & ( 0 - (noiseValue & 1 ) );
  911. noiseValue >>= 1;
  912. }
  913. return noiseValue;
  914. }
  915. OPL_INLINE Bit32u Chip::ForwardLFO( Bit32u samples ) {
  916. //Current vibrato value, runs 4x slower than tremolo
  917. vibratoSign = ( VibratoTable[ vibratoIndex >> 2] ) >> 7;
  918. vibratoShift = ( VibratoTable[ vibratoIndex >> 2] & 7) + vibratoStrength;
  919. tremoloValue = TremoloTable[ tremoloIndex ] >> tremoloStrength;
  920. //Check hom many samples there can be done before the value changes
  921. Bit32u todo = LFO_MAX - lfoCounter;
  922. Bit32u count = (todo + lfoAdd - 1) / lfoAdd;
  923. if ( count > samples ) {
  924. count = samples;
  925. lfoCounter += count * lfoAdd;
  926. } else {
  927. lfoCounter += count * lfoAdd;
  928. lfoCounter &= (LFO_MAX - 1);
  929. //Maximum of 7 vibrato value * 4
  930. vibratoIndex = ( vibratoIndex + 1 ) & 31;
  931. //Clip tremolo to the the table size
  932. if ( tremoloIndex + 1 < TREMOLO_TABLE )
  933. ++tremoloIndex;
  934. else
  935. tremoloIndex = 0;
  936. }
  937. return count;
  938. }
  939. void Chip::WriteBD( Bit8u val ) {
  940. Bit8u change = regBD ^ val;
  941. if ( !change )
  942. return;
  943. regBD = val;
  944. //TODO could do this with shift and xor?
  945. vibratoStrength = (val & 0x40) ? 0x00 : 0x01;
  946. tremoloStrength = (val & 0x80) ? 0x00 : 0x02;
  947. if ( val & 0x20 ) {
  948. //Drum was just enabled, make sure channel 6 has the right synth
  949. if ( change & 0x20 ) {
  950. if ( opl3Active ) {
  951. chan[6].synthHandler = &Channel::BlockTemplate< sm3Percussion >;
  952. } else {
  953. chan[6].synthHandler = &Channel::BlockTemplate< sm2Percussion >;
  954. }
  955. }
  956. //Bass Drum
  957. if ( val & 0x10 ) {
  958. chan[6].op[0].KeyOn( 0x2 );
  959. chan[6].op[1].KeyOn( 0x2 );
  960. } else {
  961. chan[6].op[0].KeyOff( 0x2 );
  962. chan[6].op[1].KeyOff( 0x2 );
  963. }
  964. //Hi-Hat
  965. if ( val & 0x1 ) {
  966. chan[7].op[0].KeyOn( 0x2 );
  967. } else {
  968. chan[7].op[0].KeyOff( 0x2 );
  969. }
  970. //Snare
  971. if ( val & 0x8 ) {
  972. chan[7].op[1].KeyOn( 0x2 );
  973. } else {
  974. chan[7].op[1].KeyOff( 0x2 );
  975. }
  976. //Tom-Tom
  977. if ( val & 0x4 ) {
  978. chan[8].op[0].KeyOn( 0x2 );
  979. } else {
  980. chan[8].op[0].KeyOff( 0x2 );
  981. }
  982. //Top Cymbal
  983. if ( val & 0x2 ) {
  984. chan[8].op[1].KeyOn( 0x2 );
  985. } else {
  986. chan[8].op[1].KeyOff( 0x2 );
  987. }
  988. //Toggle keyoffs when we turn off the percussion
  989. } else if ( change & 0x20 ) {
  990. //Trigger a reset to setup the original synth handler
  991. chan[6].ResetC0( this );
  992. chan[6].op[0].KeyOff( 0x2 );
  993. chan[6].op[1].KeyOff( 0x2 );
  994. chan[7].op[0].KeyOff( 0x2 );
  995. chan[7].op[1].KeyOff( 0x2 );
  996. chan[8].op[0].KeyOff( 0x2 );
  997. chan[8].op[1].KeyOff( 0x2 );
  998. }
  999. }
  1000. #define REGOP( _FUNC_ ) \
  1001. index = ( ( reg >> 3) & 0x20 ) | ( reg & 0x1f ); \
  1002. if ( OpOffsetTable[ index ] ) { \
  1003. Operator* regOp = (Operator*)( ((char *)this ) + OpOffsetTable[ index ] ); \
  1004. regOp->_FUNC_( this, val ); \
  1005. }
  1006. #define REGCHAN( _FUNC_ ) \
  1007. index = ( ( reg >> 4) & 0x10 ) | ( reg & 0xf ); \
  1008. if ( ChanOffsetTable[ index ] ) { \
  1009. Channel* regChan = (Channel*)( ((char *)this ) + ChanOffsetTable[ index ] ); \
  1010. regChan->_FUNC_( this, val ); \
  1011. }
  1012. void Chip::WriteReg( Bit32u reg, Bit8u val ) {
  1013. Bitu index;
  1014. switch ( (reg & 0xf0) >> 4 ) {
  1015. case 0x00 >> 4:
  1016. if ( reg == 0x01 ) {
  1017. waveFormMask = ( val & 0x20 ) ? 0x7 : 0x0;
  1018. } else if ( reg == 0x104 ) {
  1019. //Only detect changes in lowest 6 bits
  1020. if ( !((reg104 ^ val) & 0x3f) )
  1021. return;
  1022. //Always keep the highest bit enabled, for checking > 0x80
  1023. reg104 = 0x80 | ( val & 0x3f );
  1024. } else if ( reg == 0x105 ) {
  1025. //MAME says the real opl3 doesn't reset anything on opl3 disable/enable till the next write in another register
  1026. if ( !((opl3Active ^ val) & 1 ) )
  1027. return;
  1028. opl3Active = ( val & 1 ) ? 0xff : 0;
  1029. //Update the 0xc0 register for all channels to signal the switch to mono/stereo handlers
  1030. for ( int i = 0; i < 18;i++ ) {
  1031. chan[i].ResetC0( this );
  1032. }
  1033. } else if ( reg == 0x08 ) {
  1034. reg08 = val;
  1035. }
  1036. case 0x10 >> 4:
  1037. break;
  1038. case 0x20 >> 4:
  1039. case 0x30 >> 4:
  1040. REGOP( Write20 );
  1041. break;
  1042. case 0x40 >> 4:
  1043. case 0x50 >> 4:
  1044. REGOP( Write40 );
  1045. break;
  1046. case 0x60 >> 4:
  1047. case 0x70 >> 4:
  1048. REGOP( Write60 );
  1049. break;
  1050. case 0x80 >> 4:
  1051. case 0x90 >> 4:
  1052. REGOP( Write80 );
  1053. break;
  1054. case 0xa0 >> 4:
  1055. REGCHAN( WriteA0 );
  1056. break;
  1057. case 0xb0 >> 4:
  1058. if ( reg == 0xbd ) {
  1059. WriteBD( val );
  1060. } else {
  1061. REGCHAN( WriteB0 );
  1062. }
  1063. break;
  1064. case 0xc0 >> 4:
  1065. REGCHAN( WriteC0 );
  1066. case 0xd0 >> 4:
  1067. break;
  1068. case 0xe0 >> 4:
  1069. case 0xf0 >> 4:
  1070. REGOP( WriteE0 );
  1071. break;
  1072. }
  1073. }
  1074. Bit32u Chip::WriteAddr( Bit32u port, Bit8u val ) {
  1075. switch ( port & 3 ) {
  1076. case 0:
  1077. return val;
  1078. case 2:
  1079. if ( opl3Active || (val == 0x05) )
  1080. return 0x100 | val;
  1081. else
  1082. return val;
  1083. }
  1084. return 0;
  1085. }
  1086. void Chip::GenerateBlock2( Bitu total, Bit32s* output ) {
  1087. while ( total > 0 ) {
  1088. Bit32u samples = ForwardLFO( total );
  1089. memset(output, 0, sizeof(Bit32s) * samples);
  1090. int count = 0;
  1091. for( Channel* ch = chan; ch < chan + 9; ) {
  1092. count++;
  1093. ch = (ch->*(ch->synthHandler))( this, samples, output );
  1094. }
  1095. total -= samples;
  1096. output += samples;
  1097. }
  1098. }
  1099. void Chip::GenerateBlock3( Bitu total, Bit32s* output ) {
  1100. while ( total > 0 ) {
  1101. Bit32u samples = ForwardLFO( total );
  1102. memset(output, 0, sizeof(Bit32s) * samples *2);
  1103. int count = 0;
  1104. for( Channel* ch = chan; ch < chan + 18; ) {
  1105. count++;
  1106. ch = (ch->*(ch->synthHandler))( this, samples, output );
  1107. }
  1108. total -= samples;
  1109. output += samples * 2;
  1110. }
  1111. }
  1112. void Chip::Setup( Bit32u rate ) {
  1113. double original = OPLRATE;
  1114. // double original = rate;
  1115. double scale = original / (double)rate;
  1116. //Noise counter is run at the same precision as general waves
  1117. noiseAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) );
  1118. noiseCounter = 0;
  1119. noiseValue = 1; //Make sure it triggers the noise xor the first time
  1120. //The low frequency oscillation counter
  1121. //Every time his overflows vibrato and tremoloindex are increased
  1122. lfoAdd = (Bit32u)( 0.5 + scale * ( 1 << LFO_SH ) );
  1123. lfoCounter = 0;
  1124. vibratoIndex = 0;
  1125. tremoloIndex = 0;
  1126. //With higher octave this gets shifted up
  1127. //-1 since the freqCreateTable = *2
  1128. #ifdef WAVE_PRECISION
  1129. double freqScale = ( 1 << 7 ) * scale * ( 1 << ( WAVE_SH - 1 - 10));
  1130. for ( int i = 0; i < 16; i++ ) {
  1131. freqMul[i] = (Bit32u)( 0.5 + freqScale * FreqCreateTable[ i ] );
  1132. }
  1133. #else
  1134. Bit32u freqScale = (Bit32u)( 0.5 + scale * ( 1 << ( WAVE_SH - 1 - 10)));
  1135. for ( int i = 0; i < 16; i++ ) {
  1136. freqMul[i] = freqScale * FreqCreateTable[ i ];
  1137. }
  1138. #endif
  1139. //-3 since the real envelope takes 8 steps to reach the single value we supply
  1140. for ( Bit8u i = 0; i < 76; i++ ) {
  1141. Bit8u index, shift;
  1142. EnvelopeSelect( i, index, shift );
  1143. linearRates[i] = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH + ENV_EXTRA - shift - 3 )));
  1144. }
  1145. //Generate the best matching attack rate
  1146. for ( Bit8u i = 0; i < 62; i++ ) {
  1147. Bit8u index, shift;
  1148. EnvelopeSelect( i, index, shift );
  1149. //Original amount of samples the attack would take
  1150. Bit32s original = (Bit32u)( (AttackSamplesTable[ index ] << shift) / scale);
  1151. Bit32s guessAdd = (Bit32u)( scale * (EnvelopeIncreaseTable[ index ] << ( RATE_SH - shift - 3 )));
  1152. Bit32s bestAdd = guessAdd;
  1153. Bit32u bestDiff = 1 << 30;
  1154. for( Bit32u passes = 0; passes < 16; passes ++ ) {
  1155. Bit32s volume = ENV_MAX;
  1156. Bit32s samples = 0;
  1157. Bit32u count = 0;
  1158. while ( volume > 0 && samples < original * 2 ) {
  1159. count += guessAdd;
  1160. Bit32s change = count >> RATE_SH;
  1161. count &= RATE_MASK;
  1162. if ( GCC_UNLIKELY(change) ) { // less than 1 %
  1163. volume += ( ~volume * change ) >> 3;
  1164. }
  1165. samples++;
  1166. }
  1167. Bit32s diff = original - samples;
  1168. Bit32u lDiff = labs( diff );
  1169. //Init last on first pass
  1170. if ( lDiff < bestDiff ) {
  1171. bestDiff = lDiff;
  1172. bestAdd = guessAdd;
  1173. if ( !bestDiff )
  1174. break;
  1175. }
  1176. //Below our target
  1177. if ( diff < 0 ) {
  1178. //Better than the last time
  1179. Bit32s mul = ((original - diff) << 12) / original;
  1180. guessAdd = ((guessAdd * mul) >> 12);
  1181. guessAdd++;
  1182. } else if ( diff > 0 ) {
  1183. Bit32s mul = ((original - diff) << 12) / original;
  1184. guessAdd = (guessAdd * mul) >> 12;
  1185. guessAdd--;
  1186. }
  1187. }
  1188. attackRates[i] = bestAdd;
  1189. }
  1190. for ( Bit8u i = 62; i < 76; i++ ) {
  1191. //This should provide instant volume maximizing
  1192. attackRates[i] = 8 << RATE_SH;
  1193. }
  1194. //Setup the channels with the correct four op flags
  1195. //Channels are accessed through a table so they appear linear here
  1196. chan[ 0].fourMask = 0x00 | ( 1 << 0 );
  1197. chan[ 1].fourMask = 0x80 | ( 1 << 0 );
  1198. chan[ 2].fourMask = 0x00 | ( 1 << 1 );
  1199. chan[ 3].fourMask = 0x80 | ( 1 << 1 );
  1200. chan[ 4].fourMask = 0x00 | ( 1 << 2 );
  1201. chan[ 5].fourMask = 0x80 | ( 1 << 2 );
  1202. chan[ 9].fourMask = 0x00 | ( 1 << 3 );
  1203. chan[10].fourMask = 0x80 | ( 1 << 3 );
  1204. chan[11].fourMask = 0x00 | ( 1 << 4 );
  1205. chan[12].fourMask = 0x80 | ( 1 << 4 );
  1206. chan[13].fourMask = 0x00 | ( 1 << 5 );
  1207. chan[14].fourMask = 0x80 | ( 1 << 5 );
  1208. //mark the percussion channels
  1209. chan[ 6].fourMask = 0x40;
  1210. chan[ 7].fourMask = 0x40;
  1211. chan[ 8].fourMask = 0x40;
  1212. //Clear Everything in opl3 mode
  1213. WriteReg( 0x105, 0x1 );
  1214. for ( int i = 0; i < 512; i++ ) {
  1215. if ( i == 0x105 )
  1216. continue;
  1217. WriteReg( i, 0xff );
  1218. WriteReg( i, 0x0 );
  1219. }
  1220. WriteReg( 0x105, 0x0 );
  1221. //Clear everything in opl2 mode
  1222. for ( int i = 0; i < 255; i++ ) {
  1223. WriteReg( i, 0xff );
  1224. WriteReg( i, 0x0 );
  1225. }
  1226. }
  1227. static bool doneTables = false;
  1228. bool InitTables( void ) {
  1229. if ( doneTables )
  1230. return true;
  1231. doneTables = true;
  1232. #if ( DBOPL_WAVE == WAVE_HANDLER ) || ( DBOPL_WAVE == WAVE_TABLELOG )
  1233. //Exponential volume table, same as the real adlib
  1234. for ( int i = 0; i < 256; i++ ) {
  1235. //Save them in reverse
  1236. ExpTable[i] = (int)( 0.5 + ( pow(2.0, ( 255 - i) * ( 1.0 /256 ) )-1) * 1024 );
  1237. ExpTable[i] += 1024; //or remove the -1 oh well :)
  1238. //Preshift to the left once so the final volume can shift to the right
  1239. ExpTable[i] *= 2;
  1240. }
  1241. #endif
  1242. #if ( DBOPL_WAVE == WAVE_HANDLER )
  1243. //Add 0.5 for the trunc rounding of the integer cast
  1244. //Do a PI sinetable instead of the original 0.5 PI
  1245. for ( int i = 0; i < 512; i++ ) {
  1246. SinTable[i] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (PI / 512.0) ) ) / log10(2.0)*256 );
  1247. }
  1248. #endif
  1249. #if ( DBOPL_WAVE == WAVE_TABLEMUL )
  1250. //Multiplication based tables
  1251. for ( int i = 0; i < 384; i++ ) {
  1252. int s = i * 8;
  1253. //TODO maybe keep some of the precision errors of the original table?
  1254. double val = ( 0.5 + ( pow(2.0, -1.0 + ( 255 - s) * ( 1.0 /256 ) )) * ( 1 << MUL_SH ));
  1255. MulTable[i] = (Bit16u)(val);
  1256. }
  1257. //Sine Wave Base
  1258. for ( int i = 0; i < 512; i++ ) {
  1259. WaveTable[ 0x0200 + i ] = (Bit16s)(sin( (i + 0.5) * (PI / 512.0) ) * 4084);
  1260. WaveTable[ 0x0000 + i ] = -WaveTable[ 0x200 + i ];
  1261. }
  1262. //Exponential wave
  1263. for ( int i = 0; i < 256; i++ ) {
  1264. WaveTable[ 0x700 + i ] = (Bit16s)( 0.5 + ( pow(2.0, -1.0 + ( 255 - i * 8) * ( 1.0 /256 ) ) ) * 4085 );
  1265. WaveTable[ 0x6ff - i ] = -WaveTable[ 0x700 + i ];
  1266. }
  1267. #endif
  1268. #if ( DBOPL_WAVE == WAVE_TABLELOG )
  1269. //Sine Wave Base
  1270. for ( int i = 0; i < 512; i++ ) {
  1271. WaveTable[ 0x0200 + i ] = (Bit16s)( 0.5 - log10( sin( (i + 0.5) * (PI / 512.0) ) ) / log10(2.0)*256 );
  1272. WaveTable[ 0x0000 + i ] = ((Bit16s)0x8000) | WaveTable[ 0x200 + i];
  1273. }
  1274. //Exponential wave
  1275. for ( int i = 0; i < 256; i++ ) {
  1276. WaveTable[ 0x700 + i ] = i * 8;
  1277. WaveTable[ 0x6ff - i ] = ((Bit16s)0x8000) | i * 8;
  1278. }
  1279. #endif
  1280. // | |//\\|____|WAV7|//__|/\ |____|/\/\|
  1281. // |\\//| | |WAV7| | \/| | |
  1282. // |06 |0126|27 |7 |3 |4 |4 5 |5 |
  1283. #if (( DBOPL_WAVE == WAVE_TABLELOG ) || ( DBOPL_WAVE == WAVE_TABLEMUL ))
  1284. for ( int i = 0; i < 256; i++ ) {
  1285. //Fill silence gaps
  1286. WaveTable[ 0x400 + i ] = WaveTable[0];
  1287. WaveTable[ 0x500 + i ] = WaveTable[0];
  1288. WaveTable[ 0x900 + i ] = WaveTable[0];
  1289. WaveTable[ 0xc00 + i ] = WaveTable[0];
  1290. WaveTable[ 0xd00 + i ] = WaveTable[0];
  1291. //Replicate sines in other pieces
  1292. WaveTable[ 0x800 + i ] = WaveTable[ 0x200 + i ];
  1293. //double speed sines
  1294. WaveTable[ 0xa00 + i ] = WaveTable[ 0x200 + i * 2 ];
  1295. WaveTable[ 0xb00 + i ] = WaveTable[ 0x000 + i * 2 ];
  1296. WaveTable[ 0xe00 + i ] = WaveTable[ 0x200 + i * 2 ];
  1297. WaveTable[ 0xf00 + i ] = WaveTable[ 0x200 + i * 2 ];
  1298. }
  1299. #endif
  1300. //Create the ksl table
  1301. for ( int oct = 0; oct < 8; oct++ ) {
  1302. int base = oct * 8;
  1303. for ( int i = 0; i < 16; i++ ) {
  1304. int val = base - KslCreateTable[i];
  1305. if ( val < 0 )
  1306. val = 0;
  1307. //*4 for the final range to match attenuation range
  1308. KslTable[ oct * 16 + i ] = val * 4;
  1309. }
  1310. }
  1311. //Create the Tremolo table, just increase and decrease a triangle wave
  1312. for ( Bit8u i = 0; i < TREMOLO_TABLE / 2; i++ ) {
  1313. Bit8u val = i << ENV_EXTRA;
  1314. TremoloTable[i] = val;
  1315. TremoloTable[TREMOLO_TABLE - 1 - i] = val;
  1316. }
  1317. //Create a table with offsets of the channels from the start of the chip
  1318. DBOPL::Chip* chip = 0;
  1319. for ( Bitu i = 0; i < 32; i++ ) {
  1320. Bitu index = i & 0xf;
  1321. if ( index >= 9 ) {
  1322. ChanOffsetTable[i] = 0;
  1323. continue;
  1324. }
  1325. //Make sure the four op channels follow eachother
  1326. if ( index < 6 ) {
  1327. index = (index % 3) * 2 + ( index / 3 );
  1328. }
  1329. //Add back the bits for highest ones
  1330. if ( i >= 16 )
  1331. index += 9;
  1332. Bitu blah = reinterpret_cast<Bitu>( &(chip->chan[ index ]) );
  1333. ChanOffsetTable[i] = blah;
  1334. }
  1335. //Same for operators
  1336. for ( Bitu i = 0; i < 64; i++ ) {
  1337. if ( i % 8 >= 6 || ( (i / 8) % 4 == 3 ) ) {
  1338. OpOffsetTable[i] = 0;
  1339. continue;
  1340. }
  1341. Bitu chNum = (i / 8) * 3 + (i % 8) % 3;
  1342. //Make sure we use 16 and up for the 2nd range to match the chanoffset gap
  1343. if ( chNum >= 12 )
  1344. chNum += 16 - 12;
  1345. Bitu opNum = ( i % 8 ) / 3;
  1346. DBOPL::Channel* chan = 0;
  1347. Bitu blah = reinterpret_cast<Bitu>( &(chan->op[opNum]) );
  1348. OpOffsetTable[i] = ChanOffsetTable[ chNum ] + blah;
  1349. }
  1350. #if 0
  1351. //Stupid checks if table's are correct
  1352. for ( Bitu i = 0; i < 18; i++ ) {
  1353. Bit32u find = (Bit16u)( &(chip->chan[ i ]) );
  1354. for ( Bitu c = 0; c < 32; c++ ) {
  1355. if ( ChanOffsetTable[c] == find ) {
  1356. find = 0;
  1357. break;
  1358. }
  1359. }
  1360. if ( find ) {
  1361. find = find;
  1362. }
  1363. }
  1364. for ( Bitu i = 0; i < 36; i++ ) {
  1365. Bit32u find = (Bit16u)( &(chip->chan[ i / 2 ].op[i % 2]) );
  1366. for ( Bitu c = 0; c < 64; c++ ) {
  1367. if ( OpOffsetTable[c] == find ) {
  1368. find = 0;
  1369. break;
  1370. }
  1371. }
  1372. if ( find ) {
  1373. find = find;
  1374. }
  1375. }
  1376. #endif
  1377. return true;
  1378. }
  1379. }; //Namespace DBOPL