-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathadl.cpp
More file actions
2948 lines (2408 loc) · 87.6 KB
/
Copy pathadl.cpp
File metadata and controls
2948 lines (2408 loc) · 87.6 KB
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
/*
* adl.cpp - ADL player adaption by Simon Peter <dn.tlp@gmx.net>
*
* Original ADL player by Torbjorn Andersson and Johannes Schickel
* 'lordhoto' <lordhoto at scummvm dot org> of the ScummVM project.
*
* https://github.com/scummvm/scummvm/blob/master/engines/kyra/sound/drivers/adlib.cpp
*/
/* 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
*
*/
/* AdLib implementation of the sound output device.
*
* It uses a sound file format special to EoB I, II, Dune II,
* Kyrandia 1 and 2, and LoL. There are slightly different
* variants: EoB I uses the oldest format (version 1);
* EoB II (version 2), Dune II and Kyrandia 1 (version 3) have
* the same file format (but need different offset adjustments);
* Kyrandia 2 and LoL format (version 4) is different again.
*/
#include <cstring>
#include <inttypes.h>
#include <stdarg.h>
#include <assert.h>
#include <stdio.h>
#include "adl.h"
#include "debug.h"
// Compatibility layer:
#ifdef ADL_DEBUG
# define warning(...) do { \
AdPlug_LogWrite(__VA_ARGS__); \
AdPlug_LogWrite("\n"); \
} while (0)
# define debugC(i1, i2, ...) warning(__VA_ARGS__)
#else
# define kDebugLevelSound 1
static inline void warning(const char *str, ...) {}
static inline void debugC(int i1, int i2, const char *str, ...) {}
#endif
#define ARRAYSIZE(x) ((int)(sizeof(x) / sizeof(x[0])))
typedef uint8_t uint8;
typedef int8_t int8;
typedef uint16_t uint16;
typedef int16_t int16;
typedef uint32_t uint32;
typedef int32_t int32;
typedef uint8_t byte;
static inline uint16 READ_LE_UINT16(const void *ptr) {
const byte *b = (const byte *)ptr;
return (b[1] << 8) + b[0];
}
static inline uint16 READ_BE_UINT16(const void *ptr) {
const byte *b = (const byte *)ptr;
return (b[0] << 8) + b[1];
}
template <class T>
static inline T CLIP(const T &value, const T &min, const T &max) {
return value < min ? min : value > max ? max : value;
}
#if !defined(nullptr) && __cplusplus < 201103L && _MSC_VER < 1600
const class nullptr_t {
public:
template<class T> // convertible to any type of null non-member pointer...
operator T*() const {
return 0;
}
template<class C, class T> // or any type of null member pointer...
operator T C::*() const {
return 0;
}
private:
void operator&() const; // Can't take address of nullptr
} nullptr = {}; // and whose name is nullptr
#endif
#define override // AdLibDriver has no base class here, so no overrides
// ### Start of engines/kyra/sound/drivers/adlib.cpp ###
// Basic AdLib Programming:
// https://web.archive.org/web/20050322080425/http://www.gamedev.net/reference/articles/article446.asp
/*
#include "kyra/sound/drivers/pc_base.h"
#include "audio/fmopl.h"
#include "common/mutex.h"
*/
#define CALLBACKS_PER_SECOND 72
/*
namespace Kyra {
*/
class AdLibDriver /* : public PCSoundDriver */ {
public:
// AdLibDriver(Audio::Mixer *mixer, int version);
AdLibDriver(Copl *opl);
~AdLibDriver() override;
void initDriver() override;
void setSoundData(uint8 *data, uint32 size) override;
void startSound(int track, int volume) override;
bool isChannelPlaying(int channel) const override;
void stopAllChannels() override;
int getSoundTrigger() const override { return _soundTrigger; }
void resetSoundTrigger() override { _soundTrigger = 0; }
void callback();
/*
void setSyncJumpMask(uint16 mask) override { _syncJumpMask = mask; }
void setMusicVolume(uint8 volume) override;
void setSfxVolume(uint8 volume) override;
*/
void setVersion(uint8 v) { // added in AdPlug
_version = v;
_numPrograms = (_version == 1) ? 150 : ((_version == 4) ? 500 : 250);
}
bool isChannelRepeating(int i) { // added in AdPlug
return _channels[i].repeating;
}
private:
// These variables have not yet been named, but some of them are partly
// known nevertheless:
//
// unk39 - Currently unused, except for updateCallback56()
// unk40 - Currently unused, except for updateCallback56()
struct Channel {
bool lock; // New to ScummVM
bool repeating; // Added in Adplug
uint8 opExtraLevel2;
const uint8 *dataptr;
uint8 duration;
uint8 repeatCounter;
int8 baseOctave;
uint8 priority;
uint8 dataptrStackPos;
const uint8 *dataptrStack[4];
int8 baseNote;
uint8 slideTempo;
uint8 slideTimer;
int16 slideStep;
int16 vibratoStep;
uint8 vibratoStepRange;
uint8 vibratoStepsCountdown;
uint8 vibratoNumSteps;
uint8 vibratoDelay;
uint8 vibratoTempo;
uint8 vibratoTimer;
uint8 vibratoDelayCountdown;
uint8 opExtraLevel1;
uint8 spacing2;
uint8 baseFreq;
uint8 tempo;
uint8 timer;
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 secondaryEffectTempo;
uint8 secondaryEffectTimer;
int8 secondaryEffectSize;
int8 secondaryEffectPos;
uint8 secondaryEffectRegbase;
uint16 secondaryEffectData;
uint8 tempoReset;
uint8 rawNote;
int8 pitchBend;
uint8 volumeModifier;
};
void primaryEffectSlide(Channel &channel);
void primaryEffectVibrato(Channel &channel);
void secondaryEffect1(Channel &channel);
void resetAdLibState();
void writeOPL(byte reg, byte val);
void initChannel(Channel &channel);
void noteOff(Channel &channel);
void initAdlibChannel(uint8 num);
uint16 getRandomNr();
void setupDuration(uint8 duration, Channel &channel);
void setupNote(uint8 rawNote, Channel &channel, bool flag = false);
void setupInstrument(uint8 regOffset, const uint8 *dataptr, Channel &channel);
void noteOn(Channel &channel);
void adjustVolume(Channel &channel);
uint8 calculateOpLevel1(Channel &channel);
uint8 calculateOpLevel2(Channel &channel);
static uint16 checkValue(int16 val) { return CLIP<int16>(val, 0, 0x3F); }
// The driver uses timer/tempo pairs in several places. On every
// callback, the tempo is added to the timer. This will frequently
// cause the timer to "wrap around", which is the signal to go ahead
// and do more stuff.
static bool advance(uint8 &timer, uint8 tempo) {
uint8 old = timer;
timer += tempo;
return timer < old;
}
const uint8 *checkDataOffset(const uint8 *ptr, long n) {
if (ptr) {
long offset = ptr - _soundData;
if (n >= -offset && n <= (long)_soundDataSize - offset)
return ptr + n;
}
return nullptr;
}
// The sound data has two lookup tables:
// * One for programs, starting at offset 0.
// * One for instruments, starting at offset 300, 500, or 1000.
// Method moved to patent class in scummvm:
uint8 *getProgram(int progId) {
// Safety check: invalid progId would crash.
if (progId < 0 || progId >= (int32)_soundDataSize / 2)
return nullptr;
const uint16 offset = READ_LE_UINT16(_soundData + 2 * progId);
// In case an invalid offset is specified we return nullptr to
// indicate an error. 0xFFFF seems to indicate "this is not a valid
// program/instrument". However, 0 is also invalid because it points
// inside the offset table itself. We also ignore any offsets outside
// of the actual data size.
// The original does not contain any safety checks and will simply
// read outside of the valid sound data in case an invalid offset is
// encountered.
if (offset == 0 || offset >= _soundDataSize) {
return nullptr;
} else {
return _soundData + offset;
}
}
const uint8 *getInstrument(int instrumentId) {
return getProgram(_numPrograms + instrumentId);
}
void setupPrograms();
void executePrograms();
struct ParserOpcode {
typedef int (AdLibDriver::*POpcode)(Channel &channel, const uint8 *values);
POpcode function;
const char *name;
int values;
};
static const ParserOpcode _parserOpcodeTable[];
static const int _parserOpcodeTableSize;
int update_setRepeat(Channel &channel, const uint8 *values);
int update_checkRepeat(Channel &channel, const uint8 *values);
int update_setupProgram(Channel &channel, const uint8 *values);
int update_setNoteSpacing(Channel &channel, const uint8 *values);
int update_jump(Channel &channel, const uint8 *values);
int update_jumpToSubroutine(Channel &channel, const uint8 *values);
int update_returnFromSubroutine(Channel &channel, const uint8 *values);
int update_setBaseOctave(Channel &channel, const uint8 *values);
int update_stopChannel(Channel &channel, const uint8 *values);
int update_playRest(Channel &channel, const uint8 *values);
int update_writeAdLib(Channel &channel, const uint8 *values);
int update_setupNoteAndDuration(Channel &channel, const uint8 *values);
int update_setBaseNote(Channel &channel, const uint8 *values);
int update_setupSecondaryEffect1(Channel &channel, const uint8 *values);
int update_stopOtherChannel(Channel &channel, const uint8 *values);
int update_waitForEndOfProgram(Channel &channel, const uint8 *values);
int update_setupInstrument(Channel &channel, const uint8 *values);
int update_setupPrimaryEffectSlide(Channel &channel, const uint8 *values);
int update_removePrimaryEffectSlide(Channel &channel, const uint8 *values);
int update_setBaseFreq(Channel &channel, const uint8 *values);
int update_setupPrimaryEffectVibrato(Channel &channel, const uint8 *values);
int update_setPriority(Channel &channel, const uint8 *values);
int update_setBeat(Channel &channel, const uint8 *values);
int update_waitForNextBeat(Channel &channel, const uint8 *values);
int update_setExtraLevel1(Channel &channel, const uint8 *values);
int update_setupDuration(Channel &channel, const uint8 *values);
int update_playNote(Channel &channel, const uint8 *values);
int update_setFractionalNoteSpacing(Channel &channel, const uint8 *values);
int update_setTempo(Channel &channel, const uint8 *values);
int update_removeSecondaryEffect1(Channel &channel, const uint8 *values);
int update_setChannelTempo(Channel &channel, const uint8 *values);
int update_setExtraLevel3(Channel &channel, const uint8 *values);
int update_setExtraLevel2(Channel &channel, const uint8 *values);
int update_changeExtraLevel2(Channel &channel, const uint8 *values);
int update_setAMDepth(Channel &channel, const uint8 *values);
int update_setVibratoDepth(Channel &channel, const uint8 *values);
int update_changeExtraLevel1(Channel &channel, const uint8 *values);
int update_clearChannel(Channel &channel, const uint8 *values);
int update_changeNoteRandomly(Channel &channel, const uint8 *values);
int update_removePrimaryEffectVibrato(Channel &channel, const uint8 *values);
int update_pitchBend(Channel &channel, const uint8 *values);
int update_resetToGlobalTempo(Channel &channel, const uint8 *values);
int update_nop(Channel &channel, const uint8 *values);
int update_setDurationRandomness(Channel &channel, const uint8 *values);
int update_changeChannelTempo(Channel &channel, const uint8 *values);
int updateCallback46(Channel &channel, const uint8 *values);
int update_setupRhythmSection(Channel &channel, const uint8 *values);
int update_playRhythmSection(Channel &channel, const uint8 *values);
int update_removeRhythmSection(Channel &channel, const uint8 *values);
int update_setRhythmLevel2(Channel &channel, const uint8 *values);
int update_changeRhythmLevel1(Channel &channel, const uint8 *values);
int update_setRhythmLevel1(Channel &channel, const uint8 *values);
int update_setSoundTrigger(Channel &channel, const uint8 *values);
int update_setTempoReset(Channel &channel, const uint8 *values);
int updateCallback56(Channel &channel, const uint8 *values);
private:
// These variables have not yet been named, but some of them are partly
// known nevertheless:
//
// _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[]
int _curChannel;
uint8 _soundTrigger;
uint16 _rnd;
uint8 _beatDivider;
uint8 _beatDivCnt;
uint8 _callbackTimer;
uint8 _beatCounter;
uint8 _beatWaiting;
uint8 _opLevelBD;
uint8 _opLevelHH;
uint8 _opLevelSD;
uint8 _opLevelTT;
uint8 _opLevelCY;
uint8 _opExtraLevel1HH;
uint8 _opExtraLevel2HH;
uint8 _opExtraLevel1CY;
uint8 _opExtraLevel2CY;
uint8 _opExtraLevel2TT;
uint8 _opExtraLevel1TT;
uint8 _opExtraLevel1SD;
uint8 _opExtraLevel2SD;
uint8 _opExtraLevel1BD;
uint8 _opExtraLevel2BD;
// OPL::OPL *_adlib;
Copl *_opl; // added in AdPlug
uint8 *_soundData; // moved to parent class in scummvm
uint32 _soundDataSize; // moved to parent class in scummvm
struct QueueEntry {
QueueEntry() : data(0), id(0), volume(0) {}
QueueEntry(uint8 *ptr, uint8 track, uint8 vol) : data(ptr), id(track), volume(vol) {}
uint8 *data;
uint8 id;
uint8 volume;
};
QueueEntry _programQueue[16];
int _programStartTimeout;
int _programQueueStart, _programQueueEnd;
bool _retrySounds;
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 _freqTable[];
static const uint8 *const _unkTable2[];
static const int _unkTable2Size;
static const uint8 _unkTable2_1[];
static const uint8 _unkTable2_2[];
static const uint8 _unkTable2_3[];
static const uint8 _pitchBendTables[][32];
uint16 _syncJumpMask;
/*
Common::Mutex _mutex;
Audio::Mixer *_mixer;
*/
uint8 _musicVolume, _sfxVolume;
int _numPrograms;
int _version;
};
//AdLibDriver::AdLibDriver(Audio::Mixer *mixer, int version) : PCSoundDriver() {
AdLibDriver::AdLibDriver(Copl *newopl) :
_opl(newopl), _soundData(0), _soundDataSize(0), _sfxPriority(0), _sfxVelocity(0), _numPrograms(0), _version(0)
{
/*
_version = version;
_numPrograms = (_version == 1) ? 150 : ((_version == 4) ? 500 : 250);
_mixer = mixer;
_adlib = OPL::Config::create();
if (!_adlib || !_adlib->init())
error("Failed to create OPL");
*/
memset(_channels, 0, sizeof(_channels));
_vibratoAndAMDepthBits = _curRegOffset = 0;
_curChannel = _rhythmSectionBits = 0;
_rnd = 0x1234;
_tempo = 0;
_soundTrigger = 0;
_programStartTimeout = 0;
_callbackTimer = 0xFF;
_beatDivider = _beatDivCnt = _beatCounter = _beatWaiting = 0;
_opLevelBD = _opLevelHH = _opLevelSD = _opLevelTT = _opLevelCY = 0;
_opExtraLevel1HH = _opExtraLevel2HH =
_opExtraLevel1CY = _opExtraLevel2CY =
_opExtraLevel2TT = _opExtraLevel1TT =
_opExtraLevel1SD = _opExtraLevel2SD =
_opExtraLevel1BD = _opExtraLevel2BD = 0;
_tablePtr1 = _tablePtr2 = nullptr;
_syncJumpMask = 0;
// _musicVolume = 0;
// _sfxVolume = 0;
_musicVolume = _sfxVolume = 0xFF;
_sfxPointer = nullptr;
_programQueueStart = _programQueueEnd = 0;
_retrySounds = false;
// _adlib->start(new Common::Functor0Mem<void, AdLibDriver>(this, &AdLibDriver::callback), CALLBACKS_PER_SECOND);
}
AdLibDriver::~AdLibDriver() {
/*
delete _adlib;
_adlib = nullptr;
*/
}
/*
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 and EoB
if (_version < 4) {
_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 4 games.
if (_version < 4)
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, uint32 size) {
// Common::StackLock lock(_mutex);
// Drop all tracks that are still queued. These would point to the old
// sound data.
_programQueueStart = _programQueueEnd = 0;
_programQueue[0] = QueueEntry();
_sfxPointer = nullptr;
_soundData = data;
_soundDataSize = size;
}
void AdLibDriver::startSound(int track, int volume) {
// Common::StackLock lock(_mutex);
uint8 *trackData = getProgram(track);
if (!trackData)
return;
if (_programQueueEnd == _programQueueStart && _programQueue[_programQueueEnd].data != 0) {
// Don't warn when dropping tracks in EoB. The queue is always full there if a couple of monsters are around.
if (_version >= 3)
warning("AdLibDriver: Program queue full, dropping track %d", track);
return;
}
_programQueue[_programQueueEnd] = QueueEntry(trackData, track, volume);
++_programQueueEnd &= 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);
}
_retrySounds = false;
_programQueueStart = _programQueueEnd = 0;
_programQueue[0] = QueueEntry();
_programStartTimeout = 0;
}
// timer callback
//
// Starts and executes programs and maintains a global beat that channels
// can synchronize on.
void AdLibDriver::callback() {
// Common::StackLock lock(_mutex);
if (_programStartTimeout)
--_programStartTimeout;
else
setupPrograms();
executePrograms();
if (advance(_callbackTimer, _tempo)) {
if (!(--_beatDivCnt)) {
_beatDivCnt = _beatDivider;
++_beatCounter;
}
}
}
void AdLibDriver::setupPrograms() {
QueueEntry &entry = _programQueue[_programQueueStart];
uint8 *ptr = entry.data;
// If there is no program queued, we skip this.
if (_programQueueStart == _programQueueEnd && !ptr)
return;
// The AdLib driver (in its old versions used for EOB) is not suitable for modern (fast) CPUs.
// The stop sound track (track 0 which has a priority of 50) will often still be busy when the
// next sound (with a lower priority) starts which will cause that sound to be skipped. We simply
// restart incoming sounds during stop sound execution.
// UPDATE: This still applies after introduction of the _programQueue.
// UPDATE: This can also happen with the HOF main menu, so I commented out the version < 3 limitation.
QueueEntry retrySound;
if (/*_version < 3 &&*/ entry.id == 0)
_retrySounds = true;
else if (_retrySounds)
retrySound = entry;
// Clear the queue entry
entry.data = nullptr;
++_programQueueStart &= 15;
// Safety check: 2 bytes (channel, priority) are required for each
// program, plus 2 more bytes (opcode, _sfxVelocity) for sound effects.
// More data is needed, but executePrograms() checks for that.
// Also ignore request for invalid channel number.
if (!checkDataOffset(ptr, 2))
return;
const int chan = *ptr;
if (chan > 9 || (chan < 9 && !checkDataOffset(ptr, 4)))
return;
Channel &channel = _channels[chan];
// Adjust data in case we hit a sound effect.
adjustSfxData(ptr++, entry.volume);
const int priority = *ptr++;
// Only start this sound if its priority is higher than the one
// already playing.
if (priority >= channel.priority) {
initChannel(channel);
channel.priority = priority;
channel.dataptr = ptr;
channel.tempo = 0xFF;
channel.timer = 0xFF;
channel.duration = 1;
if (chan <= 5)
channel.volumeModifier = _musicVolume;
else
channel.volumeModifier = _sfxVolume;
initAdlibChannel(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;
retrySound = QueueEntry();
}
if (retrySound.data) {
debugC(9, kDebugLevelSound, "AdLibDriver::setupPrograms(): WORKAROUND - Restarting skipped sound %d)", retrySound.id);
startSound(retrySound.id, retrySound.volume);
}
}
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 = nullptr;
}
// 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 (volume != 0xFF) {
if (_version >= 3) {
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 and timer. The timer is updated,
// and when it wraps around, we go ahead and do more stuff with that channel.
// Otherwise we skip straiht to the effect callbacks.
//
// Each channel also has a duration, indicating how much time is left on 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.
// If the most significant bit of the opcode is 1, it's a function; call it.
// An opcode function can change control flow by updating the channel's data
// pointer (which is set to the next opcode before the call). The function's
// return value is 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.
if (_syncJumpMask) {
// This is where we ensure that channels that are made to jump
// "in sync" do so.
for (_curChannel = 9; _curChannel >= 0; --_curChannel) {
if ((_syncJumpMask & (1 << _curChannel)) && _channels[_curChannel].dataptr && !_channels[_curChannel].lock)
break; // don't unlock
}
if (_curChannel < 0) {
// force unlock
for (_curChannel = 9; _curChannel >= 0; --_curChannel)
if (_syncJumpMask & (1 << _curChannel))
_channels[_curChannel].lock = false;
}
}
for (_curChannel = 9; _curChannel >= 0; --_curChannel) {
Channel &channel = _channels[_curChannel];
const uint8 *&dataptr = channel.dataptr;
if (!dataptr)
continue;
if (channel.lock && (_syncJumpMask & (1 << _curChannel)))
continue;
if (_curChannel == 9)
_curRegOffset = 0;
else
_curRegOffset = _regOffset[_curChannel];
if (channel.tempoReset)
channel.tempo = _tempo;
int result = 1;
if (advance(channel.timer, channel.tempo)) {
if (--channel.duration) {
if (channel.duration == channel.spacing2)
noteOff(channel);
if (channel.duration == channel.spacing1 && _curChannel != 9)
noteOff(channel);
} else {
// Process some opcodes.
result = 0;
}
}
while (result == 0 && dataptr) {
uint8 opcode = 0xFF;
// Safety check to avoid illegal access.
// Stop channel if not enough data.
if (checkDataOffset(dataptr, 1))
opcode = *dataptr++;
if (opcode & 0x80) {
opcode = CLIP(opcode & 0x7F, 0, _parserOpcodeTableSize - 1);
const ParserOpcode &op = _parserOpcodeTable[opcode];
// Safety check for end of data.
if (!checkDataOffset(dataptr, op.values)) {
result = update_stopChannel(channel, dataptr);
break;
}
debugC(9, kDebugLevelSound, "Calling opcode '%s' (%d) (channel: %d)", op.name, opcode, _curChannel);
dataptr += op.values;
result = (this->*(op.function))(channel, dataptr - op.values);
} else {
// Safety check for end of data.
if (!checkDataOffset(dataptr, 1)) {
result = update_stopChannel(channel, dataptr);
break;
}
uint8 duration = *dataptr++;
debugC(9, kDebugLevelSound, "Note on opcode 0x%02X (duration: %d) (channel: %d)", opcode, duration, _curChannel);
setupNote(opcode, channel);
noteOn(channel);
setupDuration(duration, channel);
// 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 = duration != 0;
}
}
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);
initChannel(_channels[9]);
for (int loop = 8; loop >= 0; loop--) {
// 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) {
// _adlib->writeReg(reg, val);
_opl->write(reg, val);
}
void AdLibDriver::initChannel(Channel &channel) {
debugC(9, kDebugLevelSound, "initChannel(%lu)", (long)(&channel - _channels));
uint8 backupEL2 = channel.opExtraLevel2;
memset(&channel, 0, sizeof(Channel));
channel.opExtraLevel2 = backupEL2;
channel.tempo = 0xFF;
channel.priority = 0;
// normally here are nullfuncs but we set nullptr for now
channel.primaryEffect = nullptr;
channel.secondaryEffect = nullptr;
channel.spacing1 = 1;
channel.lock = false;
channel.repeating = 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::initAdlibChannel(uint8 chan) {
debugC(9, kDebugLevelSound, "initAdlibChannel(%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