/
snd_dma.cpp
5658 lines (4765 loc) · 151 KB
/
snd_dma.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
/*****************************************************************************
* name: snd_dma.c
*
* desc: main control for any streaming sound output device
*
*
*****************************************************************************/
// leave this as first line for PCH reasons...
//
#include "../server/exe_headers.h"
#include "snd_local.h"
#include "cl_mp3.h"
#include "snd_music.h"
static void S_Play_f(void);
static void S_SoundList_f(void);
static void S_Music_f(void);
static void S_SetDynamicMusic_f(void);
void S_Update_();
void S_StopAllSounds(void);
static void S_UpdateBackgroundTrack( void );
sfx_t *S_FindName( const char *name );
static int SND_FreeSFXMem(sfx_t *sfx);
extern qboolean Sys_LowPhysicalMemory();
//////////////////////////
//
// vars for bgrnd music track...
//
const int iMP3MusicStream_DiskBytesToRead = 10000;//4096;
const int iMP3MusicStream_DiskBufferSize = iMP3MusicStream_DiskBytesToRead*2; //*10;
typedef struct
{
qboolean bIsMP3;
//
// MP3 specific...
//
sfx_t sfxMP3_Bgrnd;
MP3STREAM streamMP3_Bgrnd; // this one is pointed at by the sfx_t's ptr, and is NOT the one the decoder uses every cycle
channel_t chMP3_Bgrnd; // ... but the one in this struct IS.
//
// MP3 disk streamer stuff... (if music is non-dynamic)
//
byte byMP3MusicStream_DiskBuffer[iMP3MusicStream_DiskBufferSize];
int iMP3MusicStream_DiskReadPos;
int iMP3MusicStream_DiskWindowPos;
//
// MP3 disk-load stuff (for use during dynamic music, which is mem-resident)
//
byte *pLoadedData; // Z_Malloc, Z_Free // these two MUST be kept as valid/invalid together
char sLoadedDataName[MAX_QPATH]; // " " " " "
int iLoadedDataLen;
//
// remaining dynamic fields...
//
int iXFadeVolumeSeekTime;
int iXFadeVolumeSeekTo; // when changing this, set the above timer to Sys_Milliseconds().
// Note that this should be thought of more as an up/down bool rather than as a
// number now, in other words set it only to 0 or 255. I'll probably change this
// to actually be a bool later.
int iXFadeVolume; // 0 = silent, 255 = max mixer vol, though still modulated via overall music_volume
float fSmoothedOutVolume;
qboolean bActive; // whether playing or not
qboolean bExists; // whether was even loaded for this level (ie don't try and start playing it)
//
// new dynamic fields...
//
qboolean bTrackSwitchPending;
MusicState_e eTS_NewState;
float fTS_NewTime;
//
// Generic...
//
fileHandle_t s_backgroundFile; // valid handle, else -1 if an MP3 (so that NZ compares still work)
wavinfo_t s_backgroundInfo;
int s_backgroundSamples;
void Rewind()
{
MP3Stream_Rewind( &chMP3_Bgrnd );
s_backgroundSamples = sfxMP3_Bgrnd.iSoundLengthInSamples;
}
void SeekTo(float fTime)
{
chMP3_Bgrnd.iMP3SlidingDecodeWindowPos = 0;
chMP3_Bgrnd.iMP3SlidingDecodeWritePos = 0;
MP3Stream_SeekTo( &chMP3_Bgrnd, fTime );
s_backgroundSamples = sfxMP3_Bgrnd.iSoundLengthInSamples;
}
} MusicInfo_t;
static void S_SetDynamicMusicState( MusicState_e musicState );
#define fDYNAMIC_XFADE_SECONDS (1.0f)
static MusicInfo_t tMusic_Info[eBGRNDTRACK_NUMBEROF] = {0};
static qboolean bMusic_IsDynamic = qfalse;
static MusicState_e eMusic_StateActual = eBGRNDTRACK_EXPLORE; // actual state, can be any enum
static MusicState_e eMusic_StateRequest = eBGRNDTRACK_EXPLORE; // requested state, can only be explore, action, boss, or silence
static char sMusic_BackgroundLoop[MAX_QPATH] = {0}; // only valid for non-dynamic music
static char sInfoOnly_CurrentDynamicMusicSet[64]; // any old reasonable size, only has to fit stuff like "kejim_post"
//
//////////////////////////
// =======================================================================
// Internal sound data & structures
// =======================================================================
// only begin attenuating sound volumes when outside the FULLVOLUME range
#define SOUND_FULLVOLUME 256
#define SOUND_ATTENUATE 0.0008f
#define VOICE_ATTENUATE 0.004f
const float SOUND_FMAXVOL=0.75;//1.0;
const int SOUND_MAXVOL=255;
channel_t s_channels[MAX_CHANNELS];
int s_soundStarted;
qboolean s_soundMuted;
dma_t dma;
int listener_number;
vec3_t listener_origin;
vec3_t listener_axis[3];
int s_soundtime; // sample PAIRS
int s_paintedtime; // sample PAIRS
// MAX_SFX may be larger than MAX_SOUNDS because
// of custom player sounds
#define MAX_SFX 10000 //512 * 2
sfx_t s_knownSfx[MAX_SFX];
int s_numSfx;
#define LOOP_HASH 128
static sfx_t *sfxHash[LOOP_HASH];
cvar_t *s_volume;
cvar_t *s_volumeVoice;
cvar_t *s_testsound;
cvar_t *s_khz;
cvar_t *s_allowDynamicMusic;
cvar_t *s_show;
cvar_t *s_mixahead;
cvar_t *s_mixPreStep;
cvar_t *s_musicVolume;
cvar_t *s_separation;
cvar_t *s_lip_threshold_1;
cvar_t *s_lip_threshold_2;
cvar_t *s_lip_threshold_3;
cvar_t *s_lip_threshold_4;
cvar_t *s_CPUType;
cvar_t *s_language; // note that this is distinct from "g_language"
cvar_t *s_dynamix;
cvar_t *s_debugdynamic;
typedef struct
{
unsigned char volume;
vec3_t origin;
vec3_t velocity;
/* const*/ sfx_t *sfx;
int mergeFrame;
int entnum;
// For Open AL
bool bProcessed;
bool bRelative;
} loopSound_t;
#define MAX_LOOP_SOUNDS 32
int numLoopSounds;
loopSound_t loopSounds[MAX_LOOP_SOUNDS];
int s_rawend;
portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES];
vec3_t s_entityPosition[MAX_GENTITIES];
int s_entityWavVol[MAX_GENTITIES];
int s_entityWavVol_back[MAX_GENTITIES];
/**************************************************************************************************\
*
* Open AL Specific
*
\**************************************************************************************************/
int s_UseOpenAL = false; // Determines if using Open AL or the default software mixer
ALfloat listener_pos[3]; // Listener Position
ALfloat listener_ori[6]; // Listener Orientation
int s_numChannels; // Number of AL Sources == Num of Channels
short s_rawdata[MAX_RAW_SAMPLES*2]; // Used for Raw Samples (Music etc...)
channel_t *S_OpenALPickChannel(int entnum, int entchannel);
int S_MP3PreProcessLipSync(channel_t *ch, short *data);
void UpdateSingleShotSounds();
void UpdateLoopingSounds();
void AL_UpdateRawSamples();
void S_SetLipSyncs();
// EAX Related
ALboolean s_bEAX; // Is EAX 3.0 support is available
bool s_bEALFileLoaded; // Has an .eal file been loaded for the current level
bool s_bInWater; // Underwater effect currently active
int s_EnvironmentID; // EAGLE ID of current environment
LPEAXMANAGER s_lpEAXManager; // Pointer to EAXManager object
HINSTANCE s_hEAXManInst; // Handle of EAXManager DLL
EAXSet s_eaxSet; // EAXSet() function
EAXGet s_eaxGet; // EAXGet() function
bool s_eaxMorphing; // Is EAX Morphing in progress
int s_eaxMorphStartTime;// EAX Morph start time
int s_eaxMorphCount; // EAX Morph count (1 ... 10)
EAXLISTENERPROPERTIES s_eaxLPSource; // Source EAX Parameters
EAXLISTENERPROPERTIES s_eaxLPCur; // Current EAX Parameters
EAXLISTENERPROPERTIES s_eaxLPDest; // Destination EAX Parameters
void InitEAXManager();
void ReleaseEAXManager();
bool LoadEALFile(char *szEALFilename);
void UnloadEALFile();
void UpdateEAXListener(bool bUseDefault, bool bUseMorphing);
void UpdateEAXBuffer(channel_t *ch);
void EALFileInit(char *level);
void EAXMorph();
void Clamp(EAXVECTOR *eaxVector);
bool CheckEAX3LP(LPEAXLISTENERPROPERTIES lpEAX3LP);
bool EAX3ListenerInterpolate(EAXLISTENERPROPERTIES *lpStartEAX3LP, EAXLISTENERPROPERTIES *lpFinishEAX3LP,
float flRatio, EAXLISTENERPROPERTIES *lpResultEAX3LP, bool bCheckValues = false);
// EAX 3.0 GUIDS ... confidential information ...
const GUID DSPROPSETID_EAX30_ListenerProperties
= { 0xa8fa6882, 0xb476, 0x11d3, { 0xbd, 0xb9, 0x00, 0xc0, 0xf0, 0x2d, 0xdf, 0x87} };
const GUID DSPROPSETID_EAX30_BufferProperties
= { 0xa8fa6881, 0xb476, 0x11d3, { 0xbd, 0xb9, 0x0, 0xc0, 0xf0, 0x2d, 0xdf, 0x87} };
/**************************************************************************************************\
*
* End of Open AL Specific
*
\**************************************************************************************************/
// instead of clearing a whole channel_t struct, we're going to skip the MP3SlidingDecodeBuffer[] buffer in the middle...
//
static inline void Channel_Clear(channel_t *ch)
{
// memset (ch, 0, sizeof(*ch));
memset(ch,0,offsetof(channel_t,MP3SlidingDecodeBuffer));
byte *const p = (byte *)ch + offsetof(channel_t,MP3SlidingDecodeBuffer) + sizeof(ch->MP3SlidingDecodeBuffer);
memset(p,0,(sizeof(*ch) - offsetof(channel_t,MP3SlidingDecodeBuffer)) - sizeof(ch->MP3SlidingDecodeBuffer));
}
// ====================================================================
// User-setable variables
// ====================================================================
static void DynamicMusicInfoPrint(void)
{
if (bMusic_IsDynamic)
{
// horribly lazy... ;-)
//
LPCSTR psRequestMusicState = Music_BaseStateToString( eMusic_StateRequest );
LPCSTR psActualMusicState = Music_BaseStateToString( eMusic_StateActual, qtrue );
if (psRequestMusicState == NULL)
{
psRequestMusicState = "<unknown>";
}
if (psActualMusicState == NULL)
{
psActualMusicState = "<unknown>";
}
Com_Printf("( Dynamic music ON, request state: '%s'(%d), actual: '%s' (%d) )\n", psRequestMusicState, eMusic_StateRequest, psActualMusicState, eMusic_StateActual);
}
else
{
Com_Printf("( Dynamic music OFF )\n");
}
}
void S_SoundInfo_f(void) {
Com_Printf("----- Sound Info -----\n" );
if (!s_soundStarted) {
Com_Printf ("sound system not started\n");
} else {
if ( s_soundMuted ) {
Com_Printf ("sound system is muted\n");
}
Com_Printf("%5d stereo\n", dma.channels - 1);
Com_Printf("%5d samples\n", dma.samples);
Com_Printf("%5d samplebits\n", dma.samplebits);
Com_Printf("%5d submission_chunk\n", dma.submission_chunk);
Com_Printf("%5d speed\n", dma.speed);
Com_Printf("0x%x dma buffer\n", dma.buffer);
if (bMusic_IsDynamic)
{
DynamicMusicInfoPrint();
Com_Printf("( Dynamic music set name: \"%s\" )\n",sInfoOnly_CurrentDynamicMusicSet);
}
else
{
if (!s_allowDynamicMusic->integer)
{
Com_Printf("( Dynamic music inhibited (s_allowDynamicMusic == 0) )\n", sMusic_BackgroundLoop );
}
if ( tMusic_Info[eBGRNDTRACK_NONDYNAMIC].s_backgroundFile )
{
Com_Printf("Background file: %s\n", sMusic_BackgroundLoop );
}
else
{
Com_Printf("No background file.\n" );
}
}
}
S_DisplayFreeMemory();
Com_Printf("----------------------\n" );
}
/*
================
S_Init
================
*/
void S_Init( void ) {
ALCcontext *ALCContext = NULL;
ALCdevice *ALCDevice = NULL;
ALfloat listenerPos[]={0.0,0.0,0.0};
ALfloat listenerVel[]={0.0,0.0,0.0};
ALfloat listenerOri[]={0.0,0.0,-1.0, 0.0,1.0,0.0};
cvar_t *cv;
qboolean r;
int i, j;
channel_t *ch;
Com_Printf("\n------- sound initialization -------\n");
s_volume = Cvar_Get ("s_volume", "0.5", CVAR_ARCHIVE);
s_volumeVoice= Cvar_Get ("s_volumeVoice", "1.0", CVAR_ARCHIVE);
s_musicVolume = Cvar_Get ("s_musicvolume", "0.25", CVAR_ARCHIVE);
s_separation = Cvar_Get ("s_separation", "0.5", CVAR_ARCHIVE);
s_khz = Cvar_Get ("s_khz", "22", CVAR_ARCHIVE|CVAR_LATCH);
s_allowDynamicMusic = Cvar_Get ("s_allowDynamicMusic", "1", CVAR_ARCHIVE);
s_mixahead = Cvar_Get ("s_mixahead", "0.2", CVAR_ARCHIVE);
s_mixPreStep = Cvar_Get ("s_mixPreStep", "0.05", CVAR_ARCHIVE);
s_show = Cvar_Get ("s_show", "0", CVAR_CHEAT);
s_testsound = Cvar_Get ("s_testsound", "0", CVAR_CHEAT);
s_debugdynamic = Cvar_Get("s_debugdynamic","0", CVAR_CHEAT);
s_lip_threshold_1 = Cvar_Get("s_threshold1" , "0.5",0);
s_lip_threshold_2 = Cvar_Get("s_threshold2" , "4.0",0);
s_lip_threshold_3 = Cvar_Get("s_threshold3" , "7.0",0);
s_lip_threshold_4 = Cvar_Get("s_threshold4" , "8.0",0);
s_language = Cvar_Get("s_language","english",CVAR_ARCHIVE | CVAR_NORESTART);
MP3_InitCvars();
s_CPUType = Cvar_Get("sys_cpuid","",0);
#if !(defined __linux__ && defined __i386__)
#if !id386
#else
extern unsigned int uiMMXAvailable;
uiMMXAvailable = !!(s_CPUType->integer >= CPUID_INTEL_MMX);
#endif
#endif
cv = Cvar_Get ("s_initsound", "1", CVAR_ROM);
if ( !cv->integer ) {
s_soundStarted = 0; // needed in case you set s_initsound to 0 midgame then snd_restart (div0 err otherwise later)
Com_Printf ("not initializing.\n");
Com_Printf("------------------------------------\n");
return;
}
Cmd_AddCommand("play", S_Play_f);
Cmd_AddCommand("music", S_Music_f);
Cmd_AddCommand("soundlist", S_SoundList_f);
Cmd_AddCommand("soundinfo", S_SoundInfo_f);
Cmd_AddCommand("soundstop", S_StopAllSounds);
Cmd_AddCommand("mp3_calcvols", S_MP3_CalcVols_f);
Cmd_AddCommand("s_dynamic", S_SetDynamicMusic_f);
cv = Cvar_Get("s_UseOpenAL" , "0",CVAR_ARCHIVE|CVAR_LATCH);
s_UseOpenAL = !!(cv->integer);
if (s_UseOpenAL)
{
ALCDevice = alcOpenDevice((ALubyte*)"DirectSound3D");
if (!ALCDevice)
return;
//Create context(s)
ALCContext = alcCreateContext(ALCDevice, NULL);
if (!ALCContext)
return;
//Set active context
alcMakeContextCurrent(ALCContext);
if (alcGetError(ALCDevice) != ALC_NO_ERROR)
return;
s_soundStarted = 1;
s_soundMuted = 1;
s_soundtime = 0;
s_paintedtime = 0;
s_rawend = 0;
S_StopAllSounds();
S_SoundInfo_f();
// Set Listener attributes
alListenerfv(AL_POSITION,listenerPos);
alListenerfv(AL_VELOCITY,listenerVel);
alListenerfv(AL_ORIENTATION,listenerOri);
InitEAXManager();
memset(s_channels, 0, sizeof(s_channels));
s_numChannels = 0;
// Create as many AL Sources (up to Max) as possible
for (i = 0; i < MAX_CHANNELS; i++)
{
alGenSources(1, &s_channels[i].alSource); // &g_Sources[i]);
if (alGetError() != AL_NO_ERROR)
{
// Reached limit of sources
break;
}
alSourcef(s_channels[i].alSource, AL_REFERENCE_DISTANCE, 400.0f);
if (alGetError() != AL_NO_ERROR)
{
break;
}
s_numChannels++;
}
// Generate AL Buffers for streaming audio playback (used for MP3s)
ch = s_channels + 1;
for (i = 1; i < s_numChannels; i++, ch++)
{
for (j = 0; j < NUM_STREAMING_BUFFERS; j++)
{
alGenBuffers(1, &(ch->buffers[j].BufferID));
ch->buffers[j].Status = UNQUEUED;
ch->buffers[j].Data = (char *)Z_Malloc(STREAMING_BUFFER_SIZE, TAG_SND_RAWDATA, qfalse);
}
}
// clear out the lip synching override array
memset(s_entityWavVol, 0, sizeof(s_entityWavVol));
/*
if (s_khz->integer == 44)
dma.speed = 44100;
else if (s_khz->integer == 22)
dma.speed = 22050;
else
dma.speed = 11025;
*/
// Always at 22KHz for OpenAL
dma.speed = 22050;
// These aren't really relevant for Open AL, but for completeness ...
dma.channels = 2;
dma.samplebits = 16;
dma.samples = 0;
dma.submission_chunk = 0;
dma.buffer = NULL;
// Clamp sound volumes between 0.0f and 1.0f
if (s_volume->value < 0.f)
s_volume->value = 0.f;
if (s_volume->value > 1.f)
s_volume->value = 1.f;
if (s_volumeVoice->value < 0.f)
s_volumeVoice->value = 0.f;
if (s_volumeVoice->value > 1.f)
s_volumeVoice->value = 1.f;
if (s_musicVolume->value < 0.f)
s_musicVolume->value = 0.f;
if (s_musicVolume->value > 1.f)
s_musicVolume->value = 1.f;
}
else
{
r = SNDDMA_Init();
if ( r ) {
s_soundStarted = 1;
s_soundMuted = 1;
// s_numSfx = 0; // do NOT do this here now!!!
s_soundtime = 0;
s_paintedtime = 0;
S_StopAllSounds ();
S_SoundInfo_f();
}
}
Com_Printf("------------------------------------\n");
Com_Printf("\n--- ambient sound initialization ---\n");
AS_Init();
}
// only called from snd_restart. QA request...
//
void S_ReloadAllUsedSounds(void)
{
if (s_soundStarted && !s_soundMuted )
{
// new bit, reload all soundsthat are used on the current level...
//
for (int i=1 ; i < s_numSfx ; i++) // start @ 1 to skip freeing default sound
{
sfx_t *sfx = &s_knownSfx[i];
if (!sfx->bInMemory && !sfx->bDefaultSound && sfx->iLastLevelUsedOn == RE_RegisterMedia_GetLevel()){
S_memoryLoad(sfx);
}
}
}
}
// =======================================================================
// Shutdown sound engine
// =======================================================================
void S_Shutdown( void )
{
ALCcontext *ALCContext;
ALCdevice *ALCDevice;
channel_t *ch;
int i, j;
if ( !s_soundStarted ) {
return;
}
S_FreeAllSFXMem();
S_UnCacheDynamicMusic();
if (s_UseOpenAL)
{
// Release all the AL Sources (including Music channel (Source 0))
for (i = 0; i < s_numChannels; i++)
{
alDeleteSources(1, &(s_channels[i].alSource));
}
// Release Streaming AL Buffers
ch = s_channels + 1;
for (i = 1; i < s_numChannels; i++, ch++)
{
for (j = 0; j < NUM_STREAMING_BUFFERS; j++)
{
alDeleteBuffers(1, &(ch->buffers[j].BufferID));
ch->buffers[j].BufferID = 0;
ch->buffers[j].Status = UNQUEUED;
if (ch->buffers[j].Data)
{
Z_Free(ch->buffers[j].Data);
ch->buffers[j].Data = NULL;
}
}
}
// Get active context
ALCContext = alcGetCurrentContext();
// Get device for active context
ALCDevice = alcGetContextsDevice(ALCContext);
// Release context(s)
alcDestroyContext(ALCContext);
// Close device
alcCloseDevice(ALCDevice);
ReleaseEAXManager();
s_numChannels = 0;
}
else
{
SNDDMA_Shutdown();
}
s_soundStarted = 0;
Cmd_RemoveCommand("play");
Cmd_RemoveCommand("music");
Cmd_RemoveCommand("stopsound");
Cmd_RemoveCommand("soundlist");
Cmd_RemoveCommand("soundinfo");
Cmd_RemoveCommand("mp3_calcvols");
Cmd_RemoveCommand("s_dynamic");
AS_Free();
}
/*
Mutes / Unmutes all OpenAL sound
*/
void S_AL_MuteAllSounds(qboolean bMute)
{
if (!s_soundStarted)
return;
if (!s_UseOpenAL)
return;
if (bMute)
{
alListenerf(AL_GAIN, 0.0f);
}
else
{
alListenerf(AL_GAIN, 1.0f);
}
}
// =======================================================================
// Load a sound
// =======================================================================
/*
================
return a hash value for the sfx name
================
*/
static long S_HashSFXName(const char *name) {
int i;
long hash;
char letter;
hash = 0;
i = 0;
while (name[i] != '\0') {
letter = tolower(name[i]);
if (letter =='.') break; // don't include extension
if (letter =='\\') letter = '/'; // damn path names
hash+=(long)(letter)*(i+119);
i++;
}
hash &= (LOOP_HASH-1);
return hash;
}
/*
==================
S_FindName
Will allocate a new sfx if it isn't found
==================
*/
sfx_t *S_FindName( const char *name ) {
int i;
int hash;
sfx_t *sfx;
if (!name) {
Com_Error (ERR_FATAL, "S_FindName: NULL\n");
}
if (!name[0]) {
Com_Error (ERR_FATAL, "S_FindName: empty name\n");
}
if (strlen(name) >= MAX_QPATH) {
Com_Error (ERR_FATAL, "Sound name too long: %s", name);
}
char sSoundNameNoExt[MAX_QPATH];
COM_StripExtension(name,sSoundNameNoExt);
hash = S_HashSFXName(sSoundNameNoExt);
sfx = sfxHash[hash];
// see if already loaded
while (sfx) {
if (!Q_stricmp(sfx->sSoundName, sSoundNameNoExt) ) {
return sfx;
}
sfx = sfx->next;
}
/*
// find a free sfx
for (i=0 ; i < s_numSfx ; i++) {
if (!s_knownSfx[i].soundName[0]) {
break;
}
}
*/
i = s_numSfx; //we don't clear the soundName after failed loads any more, so it'll always be the last entry
if (s_numSfx == MAX_SFX)
{
// ok, no sfx's free, but are there any with defaultSound set? (which the registering ent will never
// see because he gets zero returned if it's default...)
//
for (i=0 ; i < s_numSfx ; i++) {
if (s_knownSfx[i].bDefaultSound) {
break;
}
}
if (i==s_numSfx)
{
// genuinely out of handles...
// if we ever reach this, let me know and I'll either boost the array or put in a map-used-on
// reference to enable sfx_t recycling. TA codebase relies on being able to have structs for every sound
// used anywhere, ever, all at once (though audio bit-buffer gets recycled). SOF1 used about 1900 distinct
// events, so current MAX_SFX limit should do, or only need a small boost... -ste
//
Com_Error (ERR_FATAL, "S_FindName: out of sfx_t");
}
}
else
{
s_numSfx++;
}
sfx = &s_knownSfx[i];
memset (sfx, 0, sizeof(*sfx));
Q_strncpyz(sfx->sSoundName, sSoundNameNoExt, sizeof(sfx->sSoundName));
sfx->next = sfxHash[hash];
sfxHash[hash] = sfx;
return sfx;
}
/*
=================
S_DefaultSound
=================
*/
void S_DefaultSound( sfx_t *sfx ) {
int i;
sfx->iSoundLengthInSamples = 512; // #samples, ie shorts
sfx->pSoundData = (short *) SND_malloc(512*2, sfx); // ... so *2 for alloc bytes
sfx->bInMemory = qtrue;
for ( i=0 ; i < sfx->iSoundLengthInSamples ; i++ )
{
sfx->pSoundData[i] = i;
}
}
/*
===================
S_DisableSounds
Disables sounds until the next S_BeginRegistration.
This is called when the hunk is cleared and the sounds
are no longer valid.
===================
*/
void S_DisableSounds( void ) {
S_StopAllSounds();
s_soundMuted = qtrue;
}
/*
=====================
S_BeginRegistration
=====================
*/
void S_BeginRegistration( void )
{
char *mapname;
s_soundMuted = qfalse; // we can play again
// Find name of level so we can load in the appropriate EAL file
if (s_UseOpenAL)
{
mapname = Cvar_VariableString( "mapname" );
EALFileInit(mapname);
}
if (s_numSfx == 0) {
SND_setup();
s_numSfx = 0;
memset( s_knownSfx, 0, sizeof( s_knownSfx ) );
memset(sfxHash, 0, sizeof(sfx_t *)*LOOP_HASH);
#ifdef _DEBUG
sfx_t *sfx = S_FindName( "***DEFAULT***" );
S_DefaultSound( sfx );
#else
S_RegisterSound("sound/null.wav");
#endif
}
}
void EALFileInit(char *level)
{
long lRoom;
char name[MAX_QPATH];
char szEALFilename[MAX_QPATH];
// If an EAL File is already unloaded, remove it
if (s_bEALFileLoaded)
{
UnloadEALFile();
}
// Reset variables
s_bInWater = false;
// Try and load an EAL file for the new level
COM_StripExtension(level, name);
Com_sprintf(szEALFilename, MAX_QPATH, "eagle/%s.eal", name);
s_bEALFileLoaded = LoadEALFile(szEALFilename);
if (s_bEALFileLoaded)
{
UpdateEAXListener(true, false);
}
else
{
if ((s_bEAX)&&(s_eaxSet))
{
lRoom = -10000;
s_eaxSet(&DSPROPSETID_EAX_ListenerProperties, DSPROPERTY_EAXLISTENER_ROOM,
NULL, &lRoom, sizeof(long));
}
}
}
/*
==================
S_RegisterSound
Creates a default buzz sound if the file can't be loaded
==================
*/
sfxHandle_t S_RegisterSound( const char *name)
{
sfx_t *sfx;
if (!s_soundStarted) {
return 0;
}
if ( strlen( name ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_RED"Sound name exceeds MAX_QPATH - %s\n", name );
return 0;
}
sfx = S_FindName( name );
SND_TouchSFX(sfx);
if ( sfx->bDefaultSound )
return 0;
if (s_UseOpenAL)
{
if ((sfx->pSoundData) || (sfx->Buffer))
return sfx - s_knownSfx;
}
else
{
if ( sfx->pSoundData )
{
return sfx - s_knownSfx;
}
}
sfx->bInMemory = qfalse;
S_memoryLoad(sfx);
if ( sfx->bDefaultSound ) {
#ifndef FINAL_BUILD
Com_Printf( S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->sSoundName );
#endif
return 0;
}
return sfx - s_knownSfx;
}
void S_memoryLoad(sfx_t *sfx)
{
// load the sound file...
//
if ( !S_LoadSound( sfx ) )
{
// Com_Printf( S_COLOR_YELLOW "WARNING: couldn't load sound: %s\n", sfx->sSoundName );
sfx->bDefaultSound = qtrue;
}
sfx->bInMemory = qtrue;
}
//=============================================================================
static qboolean S_CheckChannelStomp( int chan1, int chan2 )
{
if ( chan1 == chan2 )
{
return qtrue;
}
if ( ( chan1 == CHAN_VOICE || chan1 == CHAN_VOICE_ATTEN || chan1 == CHAN_VOICE_GLOBAL ) && ( chan2 == CHAN_VOICE || chan2 == CHAN_VOICE_ATTEN || chan2 == CHAN_VOICE_GLOBAL ) )
{
return qtrue;
}
return qfalse;
}
/*
=================
S_PickChannel
=================
*/
// there were 2 versions of this, one for A3D and one normal, but the normal one wouldn't compile because
// it hadn't been updated for some time, so rather than risk anything weird/out of date, I just removed the
// A3D lines from this version and deleted the other one.
//
// If this really bothers you then feel free to play with it. -Ste.
//
channel_t *S_PickChannel(int entnum, int entchannel)
{
int ch_idx;
channel_t *ch, *firstToDie;
qboolean foundChan = qfalse;
if (s_UseOpenAL)
return S_OpenALPickChannel(entnum, entchannel);
if ( entchannel<0 ) {
Com_Error (ERR_DROP, "S_PickChannel: entchannel<0");
}
// Check for replacement sound, or find the best one to replace
firstToDie = &s_channels[0];
for ( int pass = 0; (pass < ((entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN)?1:2)) && !foundChan; pass++ )
{
for (ch_idx = 0, ch = &s_channels[0]; ch_idx < MAX_CHANNELS ; ch_idx++, ch++ )
{
if ( entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN || pass > 0 )