-
Notifications
You must be signed in to change notification settings - Fork 0
/
sound_adlib.cpp
2576 lines (2110 loc) · 79.3 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
*
* $URL$
* $Id$
*
*/
#include <FileClasses/adl/sound_adlib.h>
#include <misc/exceptions.h>
#include <algorithm>
#include <cinttypes>
#include <cstdarg>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <memory>
#ifdef USE_SDL_MIXER_X
# include <SDL2/SDL_mixer_ext.h>
#else
# include <SDL2/SDL_mixer.h>
#endif
#include <SDL2/SDL_endian.h>
#include <FileClasses/adl/wemuopl.h>
#include <FileClasses/adl/surroundopl.h>
// Basic Adlib Programming:
// http://www.gamedev.net/reference/articles/article446.asp
#define CALLBACKS_PER_SECOND 72
#define ADLIB_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 auto *b = static_cast<const byte *>(ptr);
return (b[1] << 8) + b[0];
}
static inline uint16 READ_BE_uint16(const void *ptr) {
const auto *b = static_cast<const byte *>(ptr);
return (b[0] << 8) + b[1];
}
static inline void warning(const char *str, ...)
{
va_list args;
va_start(args, str);
vfprintf(stderr,str,args);
fprintf(stderr,"\n");
va_end(args);
}
static inline void debugC(int level, const char *str, ...)
{
/*
va_list args;
va_start(args, str);
vfprintf(stderr,str,args);
fprintf(stderr,"\n");
va_end(args);
*/
}
class AdlibDriver final {
public:
explicit AdlibDriver(int rate);
~AdlibDriver();
AdlibLogger *logger;
AdlibDriver(const AdlibDriver &) = delete;
AdlibDriver(AdlibDriver &&) = delete;
AdlibDriver& operator=(const AdlibDriver &) = delete;
AdlibDriver& operator=(AdlibDriver &&) = delete;
int callback(int opcode, ...);
void callback();
uint32_t _audioFrameCounter = 0;
// 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;
}
}
const int32 render = std::min(samplesLeft, _samplesTillCallback);
samplesLeft -= render;
_samplesTillCallback -= render;
//YM3812UpdateOne(_adlib, buffer, render);
opl->update(buffer, render);
buffer += render*2;
_audioFrameCounter += render;
}
return numSamples;
}
bool isStereo() const { return false; }
bool endOfData() const { return false; }
int getRate() const { return _rate; }
void setSyncJumpMask(uint16 mask) { _syncJumpMask = mask; }
private:
struct OpcodeEntry {
typedef int (AdlibDriver::*DriverOpcode)(va_list &list);
DriverOpcode function;
const char *name;
};
void setupOpcodeList();
const OpcodeEntry *_opcodeList;
int _opcodesEntries;
int snd_ret0x100(va_list &list);
int snd_ret0x1983(va_list &list);
int snd_initDriver(va_list &list);
int snd_deinitDriver(va_list &list);
int snd_setSoundData(va_list &list);
int snd_unkOpcode1(va_list &list);
int snd_startSong(va_list &list);
int snd_isChannelPlaying(va_list &list);
int snd_unkOpcode3(va_list &list);
int snd_readByte(va_list &list);
int snd_writeByte(va_list &list);
int snd_getSoundTrigger(va_list &list);
int snd_unkOpcode4(va_list &list);
int snd_dummy(va_list &list);
int snd_getNullvar4(va_list &list);
int snd_setNullvar3(va_list &list);
int snd_setFlag(va_list &list);
int snd_clearFlag(va_list &list);
// 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;
};
void primaryEffect1(Channel &channel);
void primaryEffect2(Channel &channel);
void secondaryEffect1(Channel &channel);
void resetAdlibState();
void writeOPL(uint8 reg, uint8 val) const;
void initChannel(Channel &channel);
void noteOff(Channel &channel);
void unkOutput2(uint8 chan);
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);
static 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) const {
const uint16 offset = READ_LE_uint16(_soundData + 2 * progId);
//TODO: Check in LoL CD Adlib driver
if (offset == 0xFFFF)
return nullptr;
return _soundData + READ_LE_uint16(_soundData + 2 * progId);
}
uint8 *getInstrument(int instrumentId) const {
const unsigned short tmp = READ_LE_uint16(_soundData + (_v2 ? 1000 : 500) + 2 * instrumentId);
if(tmp == 0xFFFF) {
return nullptr;
} else {
return _soundData + tmp;
}
}
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_nop1(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_nop2(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
// _unkValue3 - Unknown. Used for updating _unkValue2
// _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 _lastProcessed;
int8 _flagTrigger;
int _curChannel;
uint8 _soundTrigger;
int _soundsPlaying;
uint16 _rnd;
uint8 _unkValue1;
uint8 _unkValue2;
uint8 _unkValue3;
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;
int _flags;
std::unique_ptr<Copl> opl;
int _rate;
uint8 *_soundData;
uint8 _soundIdTable[0x10] = { 0 };
public:
Channel _channels[10];
private:
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 *_unkTable2[];
static const uint8 _unkTable2_1[];
static const uint8 _unkTable2_2[];
static const uint8 _unkTable2_3[];
static const uint8 _unkTables[][32];
uint16 _syncJumpMask;
bool _v2;
void lock() { }
void unlock() { }
};
class NullAdlibLogger final : public AdlibLogger {
public:
void logOPL(uint32_t framePos, uint8_t reg, uint8_t val) override {}
};
static NullAdlibLogger nullAdlibLogger;
AdlibDriver::AdlibDriver(int rate) : logger(&nullAdlibLogger) {
setupOpcodeList();
setupParserOpcodeTable();
_v2 = false;
_rate = rate;
_flags = 0;
// Copl *a = new CWemuopl(rate, false);
// Copl *b = new CWemuopl(rate, false);
opl = std::make_unique<CWemuopl>(rate, false);
// CSurroundopl now owns a and b and will free upon destruction
memset(_channels, 0, sizeof(_channels));
_soundData = nullptr;
_vibratoAndAMDepthBits = _curRegOffset = 0;
_lastProcessed = _flagTrigger = _curChannel = _rhythmSectionBits = 0;
_soundsPlaying = 0;
_rnd = 0x1234;
_tempo = 0;
_soundTrigger = 0;
_unkValue3 = 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 = nullptr;
// HACK: We use MusicSoundType here for now so we can adjust the volume in the launcher dialog.
// This affects SFX too, but if we want to support different volumes for SFX and music we would
// have to change our player implementation, currently we setup the volume for an AdLib channel
// in AdlibDriver::adjustVolume, so if that would be called, we would have to know if the channel
// is used by SFX or music, and then adjust the volume accordingly. Since Kyrandia 2 supports
// different volumes for SFX and music, looking at the disasm and checking how the original does it
// would be a good idea.
//_mixer->playInputStream(Audio::Mixer::kMusicSoundType, &_soundHandle, this, -1, Audio::Mixer::kMaxChannelVolume, 0, false, true);
_samplesPerCallback = getRate() / CALLBACKS_PER_SECOND;
_samplesPerCallbackRemainder = getRate() % CALLBACKS_PER_SECOND;
_samplesTillCallback = 0;
_samplesTillCallbackRemainder = 0;
_syncJumpMask = 0;
}
AdlibDriver::~AdlibDriver() = default;
int AdlibDriver::callback(int opcode, ...) {
lock();
if (opcode >= _opcodesEntries || opcode < 0) {
warning("AdlibDriver: calling unknown opcode '%d'", opcode);
return 0;
}
debugC(9, "Calling opcode '%s' (%d)", _opcodeList[opcode].name, opcode);
va_list args;
va_start(args, opcode);
const int returnValue = (this->*(_opcodeList[opcode].function))(args);
va_end(args);
unlock();
return returnValue;
}
// Opcodes
int AdlibDriver::snd_ret0x100(va_list &list) {
return 0x100;
}
int AdlibDriver::snd_ret0x1983(va_list &list) {
return 0x1983;
}
int AdlibDriver::snd_initDriver(va_list &list) {
_lastProcessed = _soundsPlaying = 0;
resetAdlibState();
return 0;
}
int AdlibDriver::snd_deinitDriver(va_list &list) {
resetAdlibState();
return 0;
}
int AdlibDriver::snd_setSoundData(va_list &list) {
if (_soundData) {
delete[] _soundData;
_soundData = nullptr;
}
_soundData = va_arg(list, uint8*);
return 0;
}
int AdlibDriver::snd_unkOpcode1(va_list &list) {
warning("unimplemented snd_unkOpcode1");
return 0;
}
int AdlibDriver::snd_startSong(va_list &list) {
const int songId = va_arg(list, int);
_flags |= 8;
_flagTrigger = 1;
const uint8 *ptr = getProgram(songId);
if(ptr == nullptr)
return 0;
uint8 chan = *ptr;
if ((songId << 1) != 0) {
if (chan == 9) {
if (_flags & 2)
return 0;
} else {
if (_flags & 1)
return 0;
}
}
_soundIdTable[_soundsPlaying++] = songId;
_soundsPlaying &= 0x0F;
return 0;
}
int AdlibDriver::snd_isChannelPlaying(va_list &list) {
int channel = va_arg(list, int);
if (_channels[channel].dataptr)
return 1;
return 0;
}
int AdlibDriver::snd_unkOpcode3(va_list &list) {
int value = va_arg(list, int);
int loop = value;
if (value < 0) {
value = 0;
loop = 9;
}
loop -= value;
++loop;
while (loop--) {
_curChannel = value;
Channel &channel = _channels[_curChannel];
channel.priority = 0;
channel.dataptr = 0;
if (value != 9)
noteOff(channel);
++value;
}
return 0;
}
int AdlibDriver::snd_readByte(va_list &list) {
int a = va_arg(list, int);
int b = va_arg(list, int);
const uint8 *ptr = getProgram(a);
if(ptr == NULL) {
warning("AdlibDriver::snd_readByte(): ptr == NULL!");
return -1;
}
const uint8 *ptr2 = ptr + b;
return *ptr2;
}
int AdlibDriver::snd_writeByte(va_list &list) {
int a = va_arg(list, int);
int b = va_arg(list, int);
int c = va_arg(list, int);
uint8 *ptr = getProgram(a) + b;
uint8 oldValue = *ptr;
*ptr = (uint8)c;
return oldValue;
}
int AdlibDriver::snd_getSoundTrigger(va_list &list) {
return _soundTrigger;
}
int AdlibDriver::snd_unkOpcode4(va_list &list) {
warning("unimplemented snd_unkOpcode4");
return 0;
}
int AdlibDriver::snd_dummy(va_list &list) {
return 0;
}
int AdlibDriver::snd_getNullvar4(va_list &list) {
warning("unimplemented snd_getNullvar4");
return 0;
}
int AdlibDriver::snd_setNullvar3(va_list &list) {
warning("unimplemented snd_setNullvar3");
return 0;
}
int AdlibDriver::snd_setFlag(va_list &list) {
int oldFlags = _flags;
_flags |= va_arg(list, int);
return oldFlags;
}
int AdlibDriver::snd_clearFlag(va_list &list) {
int oldFlags = _flags;
_flags &= ~(va_arg(list, int));
return oldFlags;
}
// timer callback
void AdlibDriver::callback() {
lock();
--_flagTrigger;
if (_flagTrigger < 0)
_flags &= ~8;
setupPrograms();
executePrograms();
uint8 temp = _unkValue3;
_unkValue3 += _tempo;
if (_unkValue3 < temp) {
if (!(--_unkValue2)) {
_unkValue2 = _unkValue1;
++_unkValue4;
}
}
unlock();
}
void AdlibDriver::setupPrograms() {
while (_lastProcessed != _soundsPlaying) {
uint8 *ptr = getProgram(_soundIdTable[_lastProcessed]);
uint8 chan = *ptr++;
uint8 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;
unkOutput2(chan);
}
// What we have set up now is, probably, the controlling
// channel for the sound. It is assumed that this program will
// set up all the other channels it needs, clearing their locks
// along the way.
++_lastProcessed;
_lastProcessed &= 0x0F;
}
}
// 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 = _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, "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, "Note on opcode 0x%02X (duration: %d) (channel: %d)", opcode, param, _curChannel);
setupNote(opcode, channel);
noteOn(channel);
setupDuration(param, channel);
if (param) {
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, "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(uint8 reg, uint8 val) const {
opl->write(reg, val);
logger->logOPL(_audioFrameCounter, reg, val);
}
void AdlibDriver::initChannel(Channel &channel) {
debugC(9, "initChannel(%d)", static_cast<int>(&channel - _channels));
memset(&channel.dataptr, 0, sizeof(Channel) - (reinterpret_cast<char *>(&channel.dataptr) - reinterpret_cast<char *>(&channel)));
channel.tempo = 0xFF;
channel.priority = 0;
// normally here are nullfuncs but we set 0 for now
channel.primaryEffect = nullptr;
channel.secondaryEffect = nullptr;
channel.spacing1 = 1;
channel.lock = false;
}
void AdlibDriver::noteOff(Channel &channel) {
debugC(9, "noteOff(%d)", static_cast<int>(&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, "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 behaviour, and causes problems with the ancient
// FMOPL code we borrowed from AdPlug. I've added a workaround. See