/
sound_adlib.cpp
2414 lines (1956 loc) · 69 KB
/
sound_adlib.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* LGPL License
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "kyra/sound_intern.h"
#include "kyra/resource.h"
#include "common/system.h"
#include "common/mutex.h"
#include "common/config-manager.h"
#include "audio/mixer.h"
#include "audio/fmopl.h"
#include "audio/audiostream.h"
// Basic AdLib Programming:
// http://www.gamedev.net/reference/articles/article446.asp
#define CALLBACKS_PER_SECOND 72
namespace Kyra {
class AdLibDriver : public Audio::AudioStream {
public:
AdLibDriver(Audio::Mixer *mixer, int version);
~AdLibDriver();
void initDriver();
void setSoundData(uint8 *data);
void queueTrack(int track, int volume);
bool isChannelPlaying(int channel) const;
void stopAllChannels();
int getSoundTrigger() const { return _soundTrigger; }
void resetSoundTrigger() { _soundTrigger = 0; }
void callback();
// AudioStream API
int readBuffer(int16 *buffer, const int numSamples) {
int32 samplesLeft = numSamples;
memset(buffer, 0, sizeof(int16) * numSamples);
while (samplesLeft) {
if (!_samplesTillCallback) {
callback();
_samplesTillCallback = _samplesPerCallback;
_samplesTillCallbackRemainder += _samplesPerCallbackRemainder;
if (_samplesTillCallbackRemainder >= CALLBACKS_PER_SECOND) {
_samplesTillCallback++;
_samplesTillCallbackRemainder -= CALLBACKS_PER_SECOND;
}
}
int32 render = MIN(samplesLeft, _samplesTillCallback);
samplesLeft -= render;
_samplesTillCallback -= render;
YM3812UpdateOne(_adlib, buffer, render);
buffer += render;
}
return numSamples;
}
bool isStereo() const { return false; }
bool endOfData() const { return false; }
int getRate() const { return _mixer->getOutputRate(); }
void setSyncJumpMask(uint16 mask) { _syncJumpMask = mask; }
void setMusicVolume(uint8 volume);
void setSfxVolume(uint8 volume);
private:
// These variables have not yet been named, but some of them are partly
// known nevertheless:
//
// unk16 - Sound-related. Possibly some sort of pitch bend.
// unk18 - Sound-effect. Used for secondaryEffect1()
// unk19 - Sound-effect. Used for secondaryEffect1()
// unk20 - Sound-effect. Used for secondaryEffect1()
// unk21 - Sound-effect. Used for secondaryEffect1()
// unk22 - Sound-effect. Used for secondaryEffect1()
// unk29 - Sound-effect. Used for primaryEffect1()
// unk30 - Sound-effect. Used for primaryEffect1()
// unk31 - Sound-effect. Used for primaryEffect1()
// unk32 - Sound-effect. Used for primaryEffect2()
// unk33 - Sound-effect. Used for primaryEffect2()
// unk34 - Sound-effect. Used for primaryEffect2()
// unk35 - Sound-effect. Used for primaryEffect2()
// unk36 - Sound-effect. Used for primaryEffect2()
// unk37 - Sound-effect. Used for primaryEffect2()
// unk38 - Sound-effect. Used for primaryEffect2()
// unk39 - Currently unused, except for updateCallback56()
// unk40 - Currently unused, except for updateCallback56()
// unk41 - Sound-effect. Used for primaryEffect2()
struct Channel {
bool lock; // New to ScummVM
uint8 opExtraLevel2;
uint8 *dataptr;
uint8 duration;
uint8 repeatCounter;
int8 baseOctave;
uint8 priority;
uint8 dataptrStackPos;
uint8 *dataptrStack[4];
int8 baseNote;
uint8 unk29;
uint8 unk31;
uint16 unk30;
uint16 unk37;
uint8 unk33;
uint8 unk34;
uint8 unk35;
uint8 unk36;
uint8 unk32;
uint8 unk41;
uint8 unk38;
uint8 opExtraLevel1;
uint8 spacing2;
uint8 baseFreq;
uint8 tempo;
uint8 position;
uint8 regAx;
uint8 regBx;
typedef void (AdLibDriver::*Callback)(Channel&);
Callback primaryEffect;
Callback secondaryEffect;
uint8 fractionalSpacing;
uint8 opLevel1;
uint8 opLevel2;
uint8 opExtraLevel3;
uint8 twoChan;
uint8 unk39;
uint8 unk40;
uint8 spacing1;
uint8 durationRandomness;
uint8 unk19;
uint8 unk18;
int8 unk20;
int8 unk21;
uint8 unk22;
uint16 offset;
uint8 tempoReset;
uint8 rawNote;
int8 unk16;
uint8 volumeModifier;
};
void primaryEffect1(Channel &channel);
void primaryEffect2(Channel &channel);
void secondaryEffect1(Channel &channel);
void resetAdLibState();
void writeOPL(byte reg, byte val);
void initChannel(Channel &channel);
void noteOff(Channel &channel);
void unkOutput2(uint8 num);
uint16 getRandomNr();
void setupDuration(uint8 duration, Channel &channel);
void setupNote(uint8 rawNote, Channel &channel, bool flag = false);
void setupInstrument(uint8 regOffset, uint8 *dataptr, Channel &channel);
void noteOn(Channel &channel);
void adjustVolume(Channel &channel);
uint8 calculateOpLevel1(Channel &channel);
uint8 calculateOpLevel2(Channel &channel);
uint16 checkValue(int16 val) {
if (val < 0)
val = 0;
else if (val > 0x3F)
val = 0x3F;
return val;
}
// The sound data has at least two lookup tables:
//
// * One for programs, starting at offset 0.
// * One for instruments, starting at offset 500.
uint8 *getProgram(int progId) {
uint16 offset = READ_LE_UINT16(_soundData + 2 * progId);
//TODO: Check in LoL CD AdLib driver
if (offset == 0xFFFF)
return 0;
return _soundData + READ_LE_UINT16(_soundData + 2 * progId);
}
uint8 *getInstrument(int instrumentId) {
return _soundData + READ_LE_UINT16(_soundData + ((_version == 2) ? 1000 : 500) + 2 * instrumentId);
}
void setupPrograms();
void executePrograms();
struct ParserOpcode {
typedef int (AdLibDriver::*POpcode)(uint8 *&dataptr, Channel &channel, uint8 value);
POpcode function;
const char *name;
};
void setupParserOpcodeTable();
const ParserOpcode *_parserOpcodeTable;
int _parserOpcodeTableSize;
int update_setRepeat(uint8 *&dataptr, Channel &channel, uint8 value);
int update_checkRepeat(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupProgram(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setNoteSpacing(uint8 *&dataptr, Channel &channel, uint8 value);
int update_jump(uint8 *&dataptr, Channel &channel, uint8 value);
int update_jumpToSubroutine(uint8 *&dataptr, Channel &channel, uint8 value);
int update_returnFromSubroutine(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setBaseOctave(uint8 *&dataptr, Channel &channel, uint8 value);
int update_stopChannel(uint8 *&dataptr, Channel &channel, uint8 value);
int update_playRest(uint8 *&dataptr, Channel &channel, uint8 value);
int update_writeAdLib(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupNoteAndDuration(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setBaseNote(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupSecondaryEffect1(uint8 *&dataptr, Channel &channel, uint8 value);
int update_stopOtherChannel(uint8 *&dataptr, Channel &channel, uint8 value);
int update_waitForEndOfProgram(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupInstrument(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupPrimaryEffect1(uint8 *&dataptr, Channel &channel, uint8 value);
int update_removePrimaryEffect1(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setBaseFreq(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupPrimaryEffect2(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setPriority(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback23(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback24(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setExtraLevel1(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupDuration(uint8 *&dataptr, Channel &channel, uint8 value);
int update_playNote(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setFractionalNoteSpacing(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setTempo(uint8 *&dataptr, Channel &channel, uint8 value);
int update_removeSecondaryEffect1(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setChannelTempo(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setExtraLevel3(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setExtraLevel2(uint8 *&dataptr, Channel &channel, uint8 value);
int update_changeExtraLevel2(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setAMDepth(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setVibratoDepth(uint8 *&dataptr, Channel &channel, uint8 value);
int update_changeExtraLevel1(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback38(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback39(uint8 *&dataptr, Channel &channel, uint8 value);
int update_removePrimaryEffect2(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback41(uint8 *&dataptr, Channel &channel, uint8 value);
int update_resetToGlobalTempo(uint8 *&dataptr, Channel &channel, uint8 value);
int update_nop(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setDurationRandomness(uint8 *&dataptr, Channel &channel, uint8 value);
int update_changeChannelTempo(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback46(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setupRhythmSection(uint8 *&dataptr, Channel &channel, uint8 value);
int update_playRhythmSection(uint8 *&dataptr, Channel &channel, uint8 value);
int update_removeRhythmSection(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback51(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback52(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback53(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setSoundTrigger(uint8 *&dataptr, Channel &channel, uint8 value);
int update_setTempoReset(uint8 *&dataptr, Channel &channel, uint8 value);
int updateCallback56(uint8 *&dataptr, Channel &channel, uint8 value);
private:
// These variables have not yet been named, but some of them are partly
// known nevertheless:
//
// _unkValue1 - Unknown. Used for updating _unkValue2
// _unkValue2 - Unknown. Used for updating _unkValue4
// _unkValue4 - Unknown. Used for updating _unkValue5
// _unkValue5 - Unknown. Used for controlling updateCallback24().
// _unkValue6 - Unknown. Rhythm section volume?
// _unkValue7 - Unknown. Rhythm section volume?
// _unkValue8 - Unknown. Rhythm section volume?
// _unkValue9 - Unknown. Rhythm section volume?
// _unkValue10 - Unknown. Rhythm section volume?
// _unkValue11 - Unknown. Rhythm section volume?
// _unkValue12 - Unknown. Rhythm section volume?
// _unkValue13 - Unknown. Rhythm section volume?
// _unkValue14 - Unknown. Rhythm section volume?
// _unkValue15 - Unknown. Rhythm section volume?
// _unkValue16 - Unknown. Rhythm section volume?
// _unkValue17 - Unknown. Rhythm section volume?
// _unkValue18 - Unknown. Rhythm section volume?
// _unkValue19 - Unknown. Rhythm section volume?
// _unkValue20 - Unknown. Rhythm section volume?
// _unkTable[] - Probably frequences for the 12-tone scale.
// _unkTable2[] - Unknown. Currently only used by updateCallback46()
// _unkTable2_1[] - One of the tables in _unkTable2[]
// _unkTable2_2[] - One of the tables in _unkTable2[]
// _unkTable2_3[] - One of the tables in _unkTable2[]
int32 _samplesPerCallback;
int32 _samplesPerCallbackRemainder;
int32 _samplesTillCallback;
int32 _samplesTillCallbackRemainder;
int _curChannel;
uint8 _soundTrigger;
uint16 _rnd;
uint8 _unkValue1;
uint8 _unkValue2;
uint8 _callbackTimer;
uint8 _unkValue4;
uint8 _unkValue5;
uint8 _unkValue6;
uint8 _unkValue7;
uint8 _unkValue8;
uint8 _unkValue9;
uint8 _unkValue10;
uint8 _unkValue11;
uint8 _unkValue12;
uint8 _unkValue13;
uint8 _unkValue14;
uint8 _unkValue15;
uint8 _unkValue16;
uint8 _unkValue17;
uint8 _unkValue18;
uint8 _unkValue19;
uint8 _unkValue20;
FM_OPL *_adlib;
uint8 *_soundData;
struct QueueEntry {
uint8 *data;
uint8 volume;
};
QueueEntry _programQueue[16];
int _programStartTimeout;
int _programQueueStart, _programQueueEnd;
void adjustSfxData(uint8 *data, int volume);
uint8 *_sfxPointer;
int _sfxPriority;
int _sfxVelocity;
Channel _channels[10];
uint8 _vibratoAndAMDepthBits;
uint8 _rhythmSectionBits;
uint8 _curRegOffset;
uint8 _tempo;
const uint8 *_tablePtr1;
const uint8 *_tablePtr2;
static const uint8 _regOffset[];
static const uint16 _unkTable[];
static const uint8 *const _unkTable2[];
static const uint8 _unkTable2_1[];
static const uint8 _unkTable2_2[];
static const uint8 _unkTable2_3[];
static const uint8 _unkTables[][32];
uint16 _syncJumpMask;
Common::Mutex _mutex;
Audio::Mixer *_mixer;
Audio::SoundHandle _soundHandle;
uint8 _musicVolume, _sfxVolume;
int _version;
};
AdLibDriver::AdLibDriver(Audio::Mixer *mixer, int version) {
setupParserOpcodeTable();
_version = version;
_mixer = mixer;
_adlib = makeAdLibOPL(getRate());
assert(_adlib);
memset(_channels, 0, sizeof(_channels));
_soundData = 0;
_vibratoAndAMDepthBits = _curRegOffset = 0;
_curChannel = _rhythmSectionBits = 0;
_rnd = 0x1234;
_tempo = 0;
_soundTrigger = 0;
_programStartTimeout = 0;
_callbackTimer = 0xFF;
_unkValue1 = _unkValue2 = _unkValue4 = _unkValue5 = 0;
_unkValue6 = _unkValue7 = _unkValue8 = _unkValue9 = _unkValue10 = 0;
_unkValue11 = _unkValue12 = _unkValue13 = _unkValue14 = _unkValue15 =
_unkValue16 = _unkValue17 = _unkValue18 = _unkValue19 = _unkValue20 = 0;
_tablePtr1 = _tablePtr2 = 0;
_mixer->playStream(Audio::Mixer::kPlainSoundType, &_soundHandle, this, -1, Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::NO, true);
_samplesPerCallback = getRate() / CALLBACKS_PER_SECOND;
_samplesPerCallbackRemainder = getRate() % CALLBACKS_PER_SECOND;
_samplesTillCallback = 0;
_samplesTillCallbackRemainder = 0;
_syncJumpMask = 0;
_musicVolume = 0;
_sfxVolume = 0;
_sfxPointer = 0;
_programQueueStart = _programQueueEnd = 0;
}
AdLibDriver::~AdLibDriver() {
_mixer->stopHandle(_soundHandle);
OPLDestroy(_adlib);
_adlib = 0;
}
void AdLibDriver::setMusicVolume(uint8 volume) {
Common::StackLock lock(_mutex);
_musicVolume = volume;
for (uint i = 0; i < 6; ++i) {
Channel &chan = _channels[i];
chan.volumeModifier = volume;
const uint8 regOffset = _regOffset[i];
// Level Key Scaling / Total Level
writeOPL(0x40 + regOffset, calculateOpLevel1(chan));
writeOPL(0x43 + regOffset, calculateOpLevel2(chan));
}
// For now we use the music volume for both sfx and music in Kyra1.
if (_version < 2) {
_sfxVolume = volume;
for (uint i = 6; i < 9; ++i) {
Channel &chan = _channels[i];
chan.volumeModifier = volume;
const uint8 regOffset = _regOffset[i];
// Level Key Scaling / Total Level
writeOPL(0x40 + regOffset, calculateOpLevel1(chan));
writeOPL(0x43 + regOffset, calculateOpLevel2(chan));
}
}
}
void AdLibDriver::setSfxVolume(uint8 volume) {
// We only support sfx volume in version 2 games.
if (_version < 2)
return;
Common::StackLock lock(_mutex);
_sfxVolume = volume;
for (uint i = 6; i < 9; ++i) {
Channel &chan = _channels[i];
chan.volumeModifier = volume;
const uint8 regOffset = _regOffset[i];
// Level Key Scaling / Total Level
writeOPL(0x40 + regOffset, calculateOpLevel1(chan));
writeOPL(0x43 + regOffset, calculateOpLevel2(chan));
}
}
void AdLibDriver::initDriver() {
Common::StackLock lock(_mutex);
resetAdLibState();
}
void AdLibDriver::setSoundData(uint8 *data) {
Common::StackLock lock(_mutex);
// Drop all tracks that are still queued. These would point to the old
// sound data.
_programQueueStart = _programQueueEnd = 0;
memset(_programQueue, 0, sizeof(_programQueue));
if (_soundData) {
delete[] _soundData;
_soundData = _sfxPointer = 0;
}
_soundData = data;
}
void AdLibDriver::queueTrack(int track, int volume) {
Common::StackLock lock(_mutex);
uint8 *trackData = getProgram(track);
if (!trackData)
return;
if (_programQueueEnd == _programQueueStart && _programQueue[_programQueueEnd].data != 0) {
warning("AdLibDriver: Program queue full, dropping track %d", track);
return;
}
_programQueue[_programQueueEnd].data = trackData;
_programQueue[_programQueueEnd].volume = volume;
_programQueueEnd = (_programQueueEnd + 1) & 15;
}
bool AdLibDriver::isChannelPlaying(int channel) const {
Common::StackLock lock(_mutex);
assert(channel >= 0 && channel <= 9);
return (_channels[channel].dataptr != 0);
}
void AdLibDriver::stopAllChannels() {
Common::StackLock lock(_mutex);
for (int channel = 0; channel <= 9; ++channel) {
_curChannel = channel;
Channel &chan = _channels[_curChannel];
chan.priority = 0;
chan.dataptr = 0;
if (channel != 9)
noteOff(chan);
}
}
// timer callback
void AdLibDriver::callback() {
Common::StackLock lock(_mutex);
if (_programStartTimeout)
--_programStartTimeout;
else
setupPrograms();
executePrograms();
uint8 temp = _callbackTimer;
_callbackTimer += _tempo;
if (_callbackTimer < temp) {
if (!(--_unkValue2)) {
_unkValue2 = _unkValue1;
++_unkValue4;
}
}
}
void AdLibDriver::setupPrograms() {
// If there is no program queued, we skip this.
if (_programQueueStart == _programQueueEnd)
return;
uint8 *ptr = _programQueue[_programQueueStart].data;
// Clear the queue entry
_programQueue[_programQueueStart].data = 0;
_programQueueStart = (_programQueueStart + 1) & 15;
// Adjust data in case we hit a sound effect.
adjustSfxData(ptr, _programQueue[_programQueueStart].volume);
const int chan = *ptr++;
const int priority = *ptr++;
// Only start this sound if its priority is higher than the one
// already playing.
Channel &channel = _channels[chan];
if (priority >= channel.priority) {
initChannel(channel);
channel.priority = priority;
channel.dataptr = ptr;
channel.tempo = 0xFF;
channel.position = 0xFF;
channel.duration = 1;
if (chan <= 5)
channel.volumeModifier = _musicVolume;
else
channel.volumeModifier = _sfxVolume;
unkOutput2(chan);
// We need to wait two callback calls till we can start another track.
// This is (probably) required to assure that the sfx are started with
// the correct priority and velocity.
_programStartTimeout = 2;
}
}
void AdLibDriver::adjustSfxData(uint8 *ptr, int volume) {
// Check whether we need to reset the data of an old sfx which has been
// started.
if (_sfxPointer) {
_sfxPointer[1] = _sfxPriority;
_sfxPointer[3] = _sfxVelocity;
_sfxPointer = 0;
}
// Only music tracks are started on channel 9, thus we need to make sure
// we do not have a music track here.
if (*ptr == 9)
return;
// Store the pointer so we can reset the data when a new program is started.
_sfxPointer = ptr;
// Store the old values.
_sfxPriority = ptr[1];
_sfxVelocity = ptr[3];
// Adjust the values.
if (_version >= 1) {
int newVal = ((((ptr[3]) + 63) * volume) >> 8) & 0xFF;
ptr[3] = -newVal + 63;
ptr[1] = ((ptr[1] * volume) >> 8) & 0xFF;
} else {
int newVal = ((_sfxVelocity << 2) ^ 0xff) * volume;
ptr[3] = (newVal >> 10) ^ 0x3f;
ptr[1] = newVal >> 11;
}
}
// A few words on opcode parsing and timing:
//
// First of all, We simulate a timer callback 72 times per second. Each timeout
// we update each channel that has something to play.
//
// Each channel has its own individual tempo, which is added to its position.
// This will frequently cause the position to "wrap around" but that is
// intentional. In fact, it's the signal to go ahead and do more stuff with
// that channel.
//
// Each channel also has a duration, indicating how much time is left on the
// its current task. This duration is decreased by one. As long as it still has
// not reached zero, the only thing that can happen is that the note is turned
// off depending on manual or automatic note spacing. Once the duration reaches
// zero, a new set of musical opcodes are executed.
//
// An opcode is one byte, followed by a variable number of parameters. Since
// most opcodes have at least one one-byte parameter, we read that as well. Any
// opcode that doesn't have that one parameter is responsible for moving the
// data pointer back again.
//
// If the most significant bit of the opcode is 1, it's a function; call it.
// The opcode functions return either 0 (continue), 1 (stop) or 2 (stop, and do
// not run the effects callbacks).
//
// If the most significant bit of the opcode is 0, it's a note, and the first
// parameter is its duration. (There are cases where the duration is modified
// but that's an exception.) The note opcode is assumed to return 1, and is the
// last opcode unless its duration is zero.
//
// Finally, most of the times that the callback is called, it will invoke the
// effects callbacks. The final opcode in a set can prevent this, if it's a
// function and it returns anything other than 1.
void AdLibDriver::executePrograms() {
// Each channel runs its own program. There are ten channels: One for
// each AdLib channel (0-8), plus one "control channel" (9) which is
// the one that tells the other channels what to do.
// This is where we ensure that channels that are made to jump "in
// sync" do so.
if (_syncJumpMask) {
bool forceUnlock = true;
for (_curChannel = 9; _curChannel >= 0; --_curChannel) {
if ((_syncJumpMask & (1 << _curChannel)) == 0)
continue;
if (_channels[_curChannel].dataptr && !_channels[_curChannel].lock)
forceUnlock = false;
}
if (forceUnlock) {
for (_curChannel = 9; _curChannel >= 0; --_curChannel)
if (_syncJumpMask & (1 << _curChannel))
_channels[_curChannel].lock = false;
}
}
for (_curChannel = 9; _curChannel >= 0; --_curChannel) {
int result = 1;
if (!_channels[_curChannel].dataptr)
continue;
if (_channels[_curChannel].lock && (_syncJumpMask & (1 << _curChannel)))
continue;
Channel &channel = _channels[_curChannel];
if (_curChannel == 9)
_curRegOffset = 0;
else
_curRegOffset = _regOffset[_curChannel];
if (channel.tempoReset)
channel.tempo = _tempo;
uint8 backup = channel.position;
channel.position += channel.tempo;
if (channel.position < backup) {
if (--channel.duration) {
if (channel.duration == channel.spacing2)
noteOff(channel);
if (channel.duration == channel.spacing1 && _curChannel != 9)
noteOff(channel);
} else {
// An opcode is not allowed to modify its own
// data pointer except through the 'dataptr'
// parameter. To enforce that, we have to work
// on a copy of the data pointer.
//
// This fixes a subtle music bug where the
// wrong music would play when getting the
// quill in Kyra 1.
uint8 *dataptr = channel.dataptr;
while (dataptr) {
uint8 opcode = *dataptr++;
uint8 param = *dataptr++;
if (opcode & 0x80) {
opcode &= 0x7F;
if (opcode >= _parserOpcodeTableSize)
opcode = _parserOpcodeTableSize - 1;
debugC(9, kDebugLevelSound, "Calling opcode '%s' (%d) (channel: %d)", _parserOpcodeTable[opcode].name, opcode, _curChannel);
result = (this->*(_parserOpcodeTable[opcode].function))(dataptr, channel, param);
channel.dataptr = dataptr;
if (result)
break;
} else {
debugC(9, kDebugLevelSound, "Note on opcode 0x%02X (duration: %d) (channel: %d)", opcode, param, _curChannel);
setupNote(opcode, channel);
noteOn(channel);
setupDuration(param, channel);
if (param) {
// We need to make sure we are always running the
// effects after this. Otherwise some sounds are
// wrong. Like the sfx when bumping into a wall in
// LoL.
result = 1;
channel.dataptr = dataptr;
break;
}
}
}
}
}
if (result == 1) {
if (channel.primaryEffect)
(this->*(channel.primaryEffect))(channel);
if (channel.secondaryEffect)
(this->*(channel.secondaryEffect))(channel);
}
}
}
//
void AdLibDriver::resetAdLibState() {
debugC(9, kDebugLevelSound, "resetAdLibState()");
_rnd = 0x1234;
// Authorize the control of the waveforms
writeOPL(0x01, 0x20);
// Select FM music mode
writeOPL(0x08, 0x00);
// I would guess the main purpose of this is to turn off the rhythm,
// thus allowing us to use 9 melodic voices instead of 6.
writeOPL(0xBD, 0x00);
int loop = 10;
while (loop--) {
if (loop != 9) {
// Silence the channel
writeOPL(0x40 + _regOffset[loop], 0x3F);
writeOPL(0x43 + _regOffset[loop], 0x3F);
}
initChannel(_channels[loop]);
}
}
// Old calling style: output0x388(0xABCD)
// New calling style: writeOPL(0xAB, 0xCD)
void AdLibDriver::writeOPL(byte reg, byte val) {
OPLWriteReg(_adlib, reg, val);
}
void AdLibDriver::initChannel(Channel &channel) {
debugC(9, kDebugLevelSound, "initChannel(%lu)", (long)(&channel - _channels));
memset(&channel.dataptr, 0, sizeof(Channel) - ((char *)&channel.dataptr - (char *)&channel));
channel.tempo = 0xFF;
channel.priority = 0;
// normally here are nullfuncs but we set 0 for now
channel.primaryEffect = 0;
channel.secondaryEffect = 0;
channel.spacing1 = 1;
channel.lock = false;
}
void AdLibDriver::noteOff(Channel &channel) {
debugC(9, kDebugLevelSound, "noteOff(%lu)", (long)(&channel - _channels));
// The control channel has no corresponding AdLib channel
if (_curChannel >= 9)
return;
// When the rhythm section is enabled, channels 6, 7 and 8 are special.
if (_rhythmSectionBits && _curChannel >= 6)
return;
// This means the "Key On" bit will always be 0
channel.regBx &= 0xDF;
// Octave / F-Number / Key-On
writeOPL(0xB0 + _curChannel, channel.regBx);
}
void AdLibDriver::unkOutput2(uint8 chan) {
debugC(9, kDebugLevelSound, "unkOutput2(%d)", chan);
// The control channel has no corresponding AdLib channel
if (chan >= 9)
return;
// I believe this has to do with channels 6, 7, and 8 being special
// when AdLib's rhythm section is enabled.
if (_rhythmSectionBits && chan >= 6)
return;
uint8 offset = _regOffset[chan];
// The channel is cleared: First the attack/delay rate, then the
// sustain level/release rate, and finally the note is turned off.
writeOPL(0x60 + offset, 0xFF);
writeOPL(0x63 + offset, 0xFF);
writeOPL(0x80 + offset, 0xFF);
writeOPL(0x83 + offset, 0xFF);
writeOPL(0xB0 + chan, 0x00);
// ...and then the note is turned on again, with whatever value is
// still lurking in the A0 + chan register, but everything else -
// including the two most significant frequency bit, and the octave -
// set to zero.
//
// This is very strange behavior, and causes problems with the ancient
// FMOPL code we borrowed from AdPlug. I've added a workaround. See
// fmopl.cpp for more details.
//
// More recent versions of the MAME FMOPL don't seem to have this
// problem, but cannot currently be used because of licensing and
// performance issues.
//
// Ken Silverman's AdLib emulator (which can be found on his Web page -
// http://www.advsys.net/ken - and as part of AdPlug) also seems to be
// immune, but is apparently not as feature complete as MAME's.
writeOPL(0xB0 + chan, 0x20);
}
// I believe this is a random number generator. It actually does seem to
// generate an even distribution of almost all numbers from 0 through 65535,
// though in my tests some numbers were never generated.
uint16 AdLibDriver::getRandomNr() {
_rnd += 0x9248;
uint16 lowBits = _rnd & 7;
_rnd >>= 3;
_rnd |= (lowBits << 13);
return _rnd;
}
void AdLibDriver::setupDuration(uint8 duration, Channel &channel) {
debugC(9, kDebugLevelSound, "setupDuration(%d, %lu)", duration, (long)(&channel - _channels));
if (channel.durationRandomness) {
channel.duration = duration + (getRandomNr() & channel.durationRandomness);
return;
}
if (channel.fractionalSpacing)
channel.spacing2 = (duration >> 3) * channel.fractionalSpacing;
channel.duration = duration;
}
// This function may or may not play the note. It's usually followed by a call
// to noteOn(), which will always play the current note.
void AdLibDriver::setupNote(uint8 rawNote, Channel &channel, bool flag) {
debugC(9, kDebugLevelSound, "setupNote(%d, %lu)", rawNote, (long)(&channel - _channels));
if (_curChannel >= 9)
return;
channel.rawNote = rawNote;
int8 note = (rawNote & 0x0F) + channel.baseNote;
int8 octave = ((rawNote + channel.baseOctave) >> 4) & 0x0F;
// There are only twelve notes. If we go outside that, we have to
// adjust the note and octave.
if (note >= 12) {
note -= 12;
octave++;
} else if (note < 0) {
note += 12;
octave--;
}
// The calculation of frequency looks quite different from the original
// disassembly at a first glance, but when you consider that the
// largest possible value would be 0x0246 + 0xFF + 0x47 (and that's if
// baseFreq is unsigned), freq is still a 10-bit value, just as it
// should be to fit in the Ax and Bx registers.
//
// If it were larger than that, it could have overflowed into the
// octave bits, and that could possibly have been used in some sound.
// But as it is now, I can't see any way it would happen.
uint16 freq = _unkTable[note] + channel.baseFreq;
// When called from callback 41, the behavior is slightly different:
// We adjust the frequency, even when channel.unk16 is 0.
if (channel.unk16 || flag) {
const uint8 *table;
if (channel.unk16 >= 0) {
table = _unkTables[(channel.rawNote & 0x0F) + 2];
freq += table[channel.unk16];
} else {
table = _unkTables[channel.rawNote & 0x0F];
freq -= table[-channel.unk16];
}
}
channel.regAx = freq & 0xFF;
channel.regBx = (channel.regBx & 0x20) | (octave << 2) | ((freq >> 8) & 0x03);
// Keep the note on or off
writeOPL(0xA0 + _curChannel, channel.regAx);
writeOPL(0xB0 + _curChannel, channel.regBx);