Debian Codegraph @

code/client/snd_openal.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4 Copyright (C) 2005 Stuart Dalton ([email protected])
5
6 This file is part of Quake III Arena source code.
7
8 Quake III Arena source code is free software; you can redistribute it
9 and/or modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2 of the License,
11 or (at your option) any later version.
12
13 Quake III Arena source code is distributed in the hope that it will be
14 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with Quake III Arena source code; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 ===========================================================================
22 */
23
24 #include "snd_local.h"
25 #include "snd_codec.h"
26 #include "client.h"
27
28 #ifdef USE_OPENAL
29
30 #include "qal.h"
31
32 // Console variables specific to OpenAL
33 cvar_t *s_alPrecache;
34 cvar_t *s_alGain;
35 cvar_t *s_alSources;
36 cvar_t *s_alDopplerFactor;
37 cvar_t *s_alDopplerSpeed;
38 cvar_t *s_alMinDistance;
39 cvar_t *s_alMaxDistance;
40 cvar_t *s_alRolloff;
41 cvar_t *s_alGraceDistance;
42 cvar_t *s_alDriver;
43 cvar_t *s_alDevice;
44 cvar_t *s_alInputDevice;
45 cvar_t *s_alAvailableDevices;
46 cvar_t *s_alAvailableInputDevices;
47
48 static qboolean enumeration_ext = qfalse;
49 static qboolean enumeration_all_ext = qfalse;
50 #ifdef USE_VOIP
51 static qboolean capture_ext = qfalse;
52 #endif
53
54 /*
55 =================
56 S_AL_Format
57 =================
58 */
59 static
60 ALuint S_AL_Format(int width, int channels)
61 {
62 ALuint format = AL_FORMAT_MONO16;
63
64 // Work out format
65 if(width == 1)
66 {
67 if(channels == 1)
68 format = AL_FORMAT_MONO8;
69 else if(channels == 2)
70 format = AL_FORMAT_STEREO8;
71 }
72 else if(width == 2)
73 {
74 if(channels == 1)
75 format = AL_FORMAT_MONO16;
76 else if(channels == 2)
77 format = AL_FORMAT_STEREO16;
78 }
79
80 return format;
81 }
82
83 /*
84 =================
85 S_AL_ErrorMsg
86 =================
87 */
88 static const char *S_AL_ErrorMsg(ALenum error)
89 {
90 switch(error)
91 {
92 case AL_NO_ERROR:
93 return "No error";
94 case AL_INVALID_NAME:
95 return "Invalid name";
96 case AL_INVALID_ENUM:
97 return "Invalid enumerator";
98 case AL_INVALID_VALUE:
99 return "Invalid value";
100 case AL_INVALID_OPERATION:
101 return "Invalid operation";
102 case AL_OUT_OF_MEMORY:
103 return "Out of memory";
104 default:
105 return "Unknown error";
106 }
107 }
108
109 /*
110 =================
111 S_AL_ClearError
112 =================
113 */
114 static void S_AL_ClearError( qboolean quiet )
115 {
116 int error = qalGetError();
117
118 if( quiet )
119 return;
120 if(error != AL_NO_ERROR)
121 {
122 Com_Printf(S_COLOR_YELLOW "WARNING: unhandled AL error: %s\n",
123 S_AL_ErrorMsg(error));
124 }
125 }
126
127
128 //===========================================================================
129
130
131 typedef struct alSfx_s
132 {
133 char filename[MAX_QPATH];
134 ALuint buffer; // OpenAL buffer
135 snd_info_t info; // information for this sound like rate, sample count..
136
137 qboolean isDefault; // Couldn't be loaded - use default FX
138 qboolean isDefaultChecked; // Sound has been check if it isDefault
139 qboolean inMemory; // Sound is stored in memory
140 qboolean isLocked; // Sound is locked (can not be unloaded)
141 int lastUsedTime; // Time last used
142
143 int loopCnt; // number of loops using this sfx
144 int loopActiveCnt; // number of playing loops using this sfx
145 int masterLoopSrc; // All other sources looping this buffer are synced to this master src
146 } alSfx_t;
147
148 static qboolean alBuffersInitialised = qfalse;
149
150 // Sound effect storage, data structures
151 #define MAX_SFX 4096
152 static alSfx_t knownSfx[MAX_SFX];
153 static sfxHandle_t numSfx = 0;
154
155 static sfxHandle_t default_sfx;
156
157 /*
158 =================
159 S_AL_BufferFindFree
160
161 Find a free handle
162 =================
163 */
164 static sfxHandle_t S_AL_BufferFindFree( void )
165 {
166 int i;
167
168 for(i = 0; i < MAX_SFX; i++)
169 {
170 // Got one
171 if(knownSfx[i].filename[0] == '\0')
172 {
173 if(i >= numSfx)
174 numSfx = i + 1;
175 return i;
176 }
177 }
178
179 // Shit...
180 Com_Error(ERR_FATAL, "S_AL_BufferFindFree: No free sound handles");
181 return -1;
182 }
183
184 /*
185 =================
186 S_AL_BufferFind
187
188 Find a sound effect if loaded, set up a handle otherwise
189 =================
190 */
191 static sfxHandle_t S_AL_BufferFind(const char *filename)
192 {
193 // Look it up in the table
194 sfxHandle_t sfx = -1;
195 int i;
196
197 if ( !filename ) {
198 Com_Error( ERR_FATAL, "Sound name is NULL" );
199 }
200
201 if ( !filename[0] ) {
202 Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
203 return 0;
204 }
205
206 if ( strlen( filename ) >= MAX_QPATH ) {
207 Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
208 return 0;
209 }
210
211 if ( filename[0] == '*' ) {
212 Com_Printf( S_COLOR_YELLOW "WARNING: Tried to load player sound directly: %s\n", filename );
213 return 0;
214 }
215
216 for(i = 0; i < numSfx; i++)
217 {
218 if(!Q_stricmp(knownSfx[i].filename, filename))
219 {
220 sfx = i;
221 break;
222 }
223 }
224
225 // Not found in table?
226 if(sfx == -1)
227 {
228 alSfx_t *ptr;
229
230 sfx = S_AL_BufferFindFree();
231
232 // Clear and copy the filename over
233 ptr = &knownSfx[sfx];
234 memset(ptr, 0, sizeof(*ptr));
235 ptr->masterLoopSrc = -1;
236 strcpy(ptr->filename, filename);
237 }
238
239 // Return the handle
240 return sfx;
241 }
242
243 /*
244 =================
245 S_AL_BufferUseDefault
246 =================
247 */
248 static void S_AL_BufferUseDefault(sfxHandle_t sfx)
249 {
250 if(sfx == default_sfx)
251 Com_Error(ERR_FATAL, "Can't load default sound effect %s", knownSfx[sfx].filename);
252
253 Com_Printf( S_COLOR_YELLOW "WARNING: Using default sound for %s\n", knownSfx[sfx].filename);
254 knownSfx[sfx].isDefault = qtrue;
255 knownSfx[sfx].buffer = knownSfx[default_sfx].buffer;
256 }
257
258 /*
259 =================
260 S_AL_BufferUnload
261 =================
262 */
263 static void S_AL_BufferUnload(sfxHandle_t sfx)
264 {
265 if(knownSfx[sfx].filename[0] == '\0')
266 return;
267
268 if(!knownSfx[sfx].inMemory)
269 return;
270
271 // Delete it
272 S_AL_ClearError( qfalse );
273 qalDeleteBuffers(1, &knownSfx[sfx].buffer);
274 if(qalGetError() != AL_NO_ERROR)
275 Com_Printf( S_COLOR_RED "ERROR: Can't delete sound buffer for %s\n",
276 knownSfx[sfx].filename);
277
278 knownSfx[sfx].inMemory = qfalse;
279 }
280
281 /*
282 =================
283 S_AL_BufferEvict
284 =================
285 */
286 static qboolean S_AL_BufferEvict( void )
287 {
288 int i, oldestBuffer = -1;
289 int oldestTime = Sys_Milliseconds( );
290
291 for( i = 0; i < numSfx; i++ )
292 {
293 if( !knownSfx[ i ].filename[ 0 ] )
294 continue;
295
296 if( !knownSfx[ i ].inMemory )
297 continue;
298
299 if( knownSfx[ i ].lastUsedTime < oldestTime )
300 {
301 oldestTime = knownSfx[ i ].lastUsedTime;
302 oldestBuffer = i;
303 }
304 }
305
306 if( oldestBuffer >= 0 )
307 {
308 S_AL_BufferUnload( oldestBuffer );
309 return qtrue;
310 }
311 else
312 return qfalse;
313 }
314
315 /*
316 =================
317 S_AL_GenBuffers
318 =================
319 */
320 static qboolean S_AL_GenBuffers(ALsizei numBuffers, ALuint *buffers, const char *name)
321 {
322 ALenum error;
323
324 S_AL_ClearError( qfalse );
325 qalGenBuffers( numBuffers, buffers );
326 error = qalGetError();
327
328 // If we ran out of buffers, start evicting the least recently used sounds
329 while( error == AL_INVALID_VALUE )
330 {
331 if( !S_AL_BufferEvict( ) )
332 {
333 Com_Printf( S_COLOR_RED "ERROR: Out of audio buffers\n");
334 return qfalse;
335 }
336
337 // Try again
338 S_AL_ClearError( qfalse );
339 qalGenBuffers( numBuffers, buffers );
340 error = qalGetError();
341 }
342
343 if( error != AL_NO_ERROR )
344 {
345 Com_Printf( S_COLOR_RED "ERROR: Can't create a sound buffer for %s - %s\n",
346 name, S_AL_ErrorMsg(error));
347 return qfalse;
348 }
349
350 return qtrue;
351 }
352
353 /*
354 =================
355 S_AL_BufferLoad
356 =================
357 */
358 static void S_AL_BufferLoad(sfxHandle_t sfx, qboolean cache)
359 {
360 ALenum error;
361 ALuint format;
362
363 void *data;
364 snd_info_t info;
365 alSfx_t *curSfx = &knownSfx[sfx];
366
367 // Nothing?
368 if(curSfx->filename[0] == '\0')
369 return;
370
371 // Already done?
372 if((curSfx->inMemory) || (curSfx->isDefault) || (!cache && curSfx->isDefaultChecked))
373 return;
374
375 // Try to load
376 data = S_CodecLoad(curSfx->filename, &info);
377 if(!data)
378 {
379 S_AL_BufferUseDefault(sfx);
380 return;
381 }
382
383 curSfx->isDefaultChecked = qtrue;
384
385 if (!cache)
386 {
387 // Don't create AL cache
388 Hunk_FreeTempMemory(data);
389 return;
390 }
391
392 format = S_AL_Format(info.width, info.channels);
393
394 // Create a buffer
395 if (!S_AL_GenBuffers(1, &curSfx->buffer, curSfx->filename))
396 {
397 S_AL_BufferUseDefault(sfx);
398 Hunk_FreeTempMemory(data);
399 return;
400 }
401
402 // Fill the buffer
403 if( info.size == 0 )
404 {
405 // We have no data to buffer, so buffer silence
406 byte dummyData[ 2 ] = { 0 };
407
408 qalBufferData(curSfx->buffer, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050);
409 }
410 else
411 qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
412
413 error = qalGetError();
414
415 // If we ran out of memory, start evicting the least recently used sounds
416 while(error == AL_OUT_OF_MEMORY)
417 {
418 if( !S_AL_BufferEvict( ) )
419 {
420 qalDeleteBuffers(1, &curSfx->buffer);
421 S_AL_BufferUseDefault(sfx);
422 Hunk_FreeTempMemory(data);
423 Com_Printf( S_COLOR_RED "ERROR: Out of memory loading %s\n", curSfx->filename);
424 return;
425 }
426
427 // Try load it again
428 qalBufferData(curSfx->buffer, format, data, info.size, info.rate);
429 error = qalGetError();
430 }
431
432 // Some other error condition
433 if(error != AL_NO_ERROR)
434 {
435 qalDeleteBuffers(1, &curSfx->buffer);
436 S_AL_BufferUseDefault(sfx);
437 Hunk_FreeTempMemory(data);
438 Com_Printf( S_COLOR_RED "ERROR: Can't fill sound buffer for %s - %s\n",
439 curSfx->filename, S_AL_ErrorMsg(error));
440 return;
441 }
442
443 curSfx->info = info;
444
445 // Free the memory
446 Hunk_FreeTempMemory(data);
447
448 // Woo!
449 curSfx->inMemory = qtrue;
450 }
451
452 /*
453 =================
454 S_AL_BufferUse
455 =================
456 */
457 static
458 void S_AL_BufferUse(sfxHandle_t sfx)
459 {
460 if(knownSfx[sfx].filename[0] == '\0')
461 return;
462
463 if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
464 S_AL_BufferLoad(sfx, qtrue);
465 knownSfx[sfx].lastUsedTime = Sys_Milliseconds();
466 }
467
468 /*
469 =================
470 S_AL_BufferInit
471 =================
472 */
473 static
474 qboolean S_AL_BufferInit( void )
475 {
476 if(alBuffersInitialised)
477 return qtrue;
478
479 // Clear the hash table, and SFX table
480 memset(knownSfx, 0, sizeof(knownSfx));
481 numSfx = 0;
482
483 // Load the default sound, and lock it
484 default_sfx = S_AL_BufferFind("sound/feedback/hit.wav");
485 S_AL_BufferUse(default_sfx);
486 knownSfx[default_sfx].isLocked = qtrue;
487
488 // All done
489 alBuffersInitialised = qtrue;
490 return qtrue;
491 }
492
493 /*
494 =================
495 S_AL_BufferShutdown
496 =================
497 */
498 static
499 void S_AL_BufferShutdown( void )
500 {
501 int i;
502
503 if(!alBuffersInitialised)
504 return;
505
506 // Unlock the default sound effect
507 knownSfx[default_sfx].isLocked = qfalse;
508
509 // Free all used effects
510 for(i = 0; i < numSfx; i++)
511 S_AL_BufferUnload(i);
512
513 // Clear the tables
514 numSfx = 0;
515
516 // All undone
517 alBuffersInitialised = qfalse;
518 }
519
520 /*
521 =================
522 S_AL_RegisterSound
523 =================
524 */
525 static
526 sfxHandle_t S_AL_RegisterSound( const char *sample, qboolean compressed )
527 {
528 sfxHandle_t sfx = S_AL_BufferFind(sample);
529
530 if((!knownSfx[sfx].inMemory) && (!knownSfx[sfx].isDefault))
531 S_AL_BufferLoad(sfx, s_alPrecache->integer);
532 knownSfx[sfx].lastUsedTime = Com_Milliseconds();
533
534 if (knownSfx[sfx].isDefault) {
535 return 0;
536 }
537
538 return sfx;
539 }
540
541 /*
542 =================
543 S_AL_BufferGet
544
545 Return's a sfx's buffer
546 =================
547 */
548 static
549 ALuint S_AL_BufferGet(sfxHandle_t sfx)
550 {
551 return knownSfx[sfx].buffer;
552 }
553
554
555 //===========================================================================
556
557
558 typedef struct src_s
559 {
560 ALuint alSource; // OpenAL source object
561 sfxHandle_t sfx; // Sound effect in use
562
563 int lastUsedTime; // Last time used
564 alSrcPriority_t priority; // Priority
565 int entity; // Owning entity (-1 if none)
566 int channel; // Associated channel (-1 if none)
567
568 qboolean isActive; // Is this source currently in use?
569 qboolean isPlaying; // Is this source currently playing, or stopped?
570 qboolean isLocked; // This is locked (un-allocatable)
571 qboolean isLooping; // Is this a looping effect (attached to an entity)
572 qboolean isTracking; // Is this object tracking its owner
573 qboolean isStream; // Is this source a stream
574
575 float curGain; // gain employed if source is within maxdistance.
576 float scaleGain; // Last gain value for this source. 0 if muted.
577
578 float lastTimePos; // On stopped loops, the last position in the buffer
579 int lastSampleTime; // Time when this was stopped
580 vec3_t loopSpeakerPos; // Origin of the loop speaker
581
582 qboolean local; // Is this local (relative to the cam)
583 } src_t;
584
585 #ifdef __APPLE__
586 #define MAX_SRC 64
587 #else
588 #define MAX_SRC 128
589 #endif
590 static src_t srcList[MAX_SRC];
591 static int srcCount = 0;
592 static int srcActiveCnt = 0;
593 static qboolean alSourcesInitialised = qfalse;
594 static int lastListenerNumber = -1;
595 static vec3_t lastListenerOrigin = { 0.0f, 0.0f, 0.0f };
596
597 typedef struct sentity_s
598 {
599 vec3_t origin;
600
601 qboolean srcAllocated; // If a src_t has been allocated to this entity
602 int srcIndex;
603
604 qboolean loopAddedThisFrame;
605 alSrcPriority_t loopPriority;
606 sfxHandle_t loopSfx;
607 qboolean startLoopingSound;
608 } sentity_t;
609
610 static sentity_t entityList[MAX_GENTITIES];
611
612 /*
613 =================
614 S_AL_SanitiseVector
615 =================
616 */
617 #define S_AL_SanitiseVector(v) _S_AL_SanitiseVector(v,__LINE__)
618 static void _S_AL_SanitiseVector( vec3_t v, int line )
619 {
620 if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
621 {
622 Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
623 "being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
624 VectorClear( v );
625 }
626 }
627
628 /*
629 =================
630 S_AL_Gain
631 Set gain to 0 if muted, otherwise set it to given value.
632 =================
633 */
634
635 static void S_AL_Gain(ALuint source, float gainval)
636 {
637 if(s_muted->integer)
638 qalSourcef(source, AL_GAIN, 0.0f);
639 else
640 qalSourcef(source, AL_GAIN, gainval);
641 }
642
643 /*
644 =================
645 S_AL_ScaleGain
646 Adapt the gain if necessary to get a quicker fadeout when the source is too far away.
647 =================
648 */
649
650 static void S_AL_ScaleGain(src_t *chksrc, vec3_t origin)
651 {
652 float distance = 0.0f;
653
654 if(!chksrc->local)
655 distance = Distance(origin, lastListenerOrigin);
656
657 // If we exceed a certain distance, scale the gain linearly until the sound
658 // vanishes into nothingness.
659 if(!chksrc->local && (distance -= s_alMaxDistance->value) > 0)
660 {
661 float scaleFactor;
662
663 if(distance >= s_alGraceDistance->value)
664 scaleFactor = 0.0f;
665 else
666 scaleFactor = 1.0f - distance / s_alGraceDistance->value;
667
668 scaleFactor *= chksrc->curGain;
669
670 if(chksrc->scaleGain != scaleFactor)
671 {
672 chksrc->scaleGain = scaleFactor;
673 S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
674 }
675 }
676 else if(chksrc->scaleGain != chksrc->curGain)
677 {
678 chksrc->scaleGain = chksrc->curGain;
679 S_AL_Gain(chksrc->alSource, chksrc->scaleGain);
680 }
681 }
682
683 /*
684 =================
685 S_AL_HearingThroughEntity
686
687 Also see S_Base_HearingThroughEntity
688 =================
689 */
690 static qboolean S_AL_HearingThroughEntity( int entityNum )
691 {
692 float distanceSq;
693
694 if( lastListenerNumber == entityNum )
695 {
696 // This is an outrageous hack to detect
697 // whether or not the player is rendering in third person or not. We can't
698 // ask the renderer because the renderer has no notion of entities and we
699 // can't ask cgame since that would involve changing the API and hence mod
700 // compatibility. I don't think there is any way around this, but I'll leave
701 // the FIXME just in case anyone has a bright idea.
702 distanceSq = DistanceSquared(
703 entityList[ entityNum ].origin,
704 lastListenerOrigin );
705
706 if( distanceSq > THIRD_PERSON_THRESHOLD_SQ )
707 return qfalse; //we're the player, but third person
708 else
709 return qtrue; //we're the player
710 }
711 else
712 return qfalse; //not the player
713 }
714
715 /*
716 =================
717 S_AL_SrcInit
718 =================
719 */
720 static
721 qboolean S_AL_SrcInit( void )
722 {
723 int i;
724 int limit;
725
726 // Clear the sources data structure
727 memset(srcList, 0, sizeof(srcList));
728 srcCount = 0;
729 srcActiveCnt = 0;
730
731 // Cap s_alSources to MAX_SRC
732 limit = s_alSources->integer;
733 if(limit > MAX_SRC)
734 limit = MAX_SRC;
735 else if(limit < 16)
736 limit = 16;
737
738 S_AL_ClearError( qfalse );
739 // Allocate as many sources as possible
740 for(i = 0; i < limit; i++)
741 {
742 qalGenSources(1, &srcList[i].alSource);
743 if(qalGetError() != AL_NO_ERROR)
744 break;
745 srcCount++;
746 }
747
748 // All done. Print this for informational purposes
749 Com_Printf( "Allocated %d sources.\n", srcCount);
750 alSourcesInitialised = qtrue;
751 return qtrue;
752 }
753
754 /*
755 =================
756 S_AL_SrcShutdown
757 =================
758 */
759 static
760 void S_AL_SrcShutdown( void )
761 {
762 int i;
763 src_t *curSource;
764
765 if(!alSourcesInitialised)
766 return;
767
768 // Destroy all the sources
769 for(i = 0; i < srcCount; i++)
770 {
771 curSource = &srcList[i];
772
773 if(curSource->isLocked)
774 Com_DPrintf( S_COLOR_YELLOW "WARNING: Source %d is locked\n", i);
775
776 if(curSource->entity > 0)
777 entityList[curSource->entity].srcAllocated = qfalse;
778
779 qalSourceStop(srcList[i].alSource);
780 qalDeleteSources(1, &srcList[i].alSource);
781 }
782
783 memset(srcList, 0, sizeof(srcList));
784
785 alSourcesInitialised = qfalse;
786 }
787
788 /*
789 =================
790 S_AL_SrcSetup
791 =================
792 */
793 static void S_AL_SrcSetup(srcHandle_t src, sfxHandle_t sfx, alSrcPriority_t priority,
794 int entity, int channel, qboolean local)
795 {
796 src_t *curSource;
797
798 // Set up src struct
799 curSource = &srcList[src];
800
801 curSource->lastUsedTime = Sys_Milliseconds();
802 curSource->sfx = sfx;
803 curSource->priority = priority;
804 curSource->entity = entity;
805 curSource->channel = channel;
806 curSource->isPlaying = qfalse;
807 curSource->isLocked = qfalse;
808 curSource->isLooping = qfalse;
809 curSource->isTracking = qfalse;
810 curSource->isStream = qfalse;
811 curSource->curGain = s_alGain->value * s_volume->value;
812 curSource->scaleGain = curSource->curGain;
813 curSource->local = local;
814
815 // Set up OpenAL source
816 if(sfx >= 0)
817 {
818 // Mark the SFX as used, and grab the raw AL buffer
819 S_AL_BufferUse(sfx);
820 qalSourcei(curSource->alSource, AL_BUFFER, S_AL_BufferGet(sfx));
821 }
822
823 qalSourcef(curSource->alSource, AL_PITCH, 1.0f);
824 S_AL_Gain(curSource->alSource, curSource->curGain);
825 qalSourcefv(curSource->alSource, AL_POSITION, vec3_origin);
826 qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
827 qalSourcei(curSource->alSource, AL_LOOPING, AL_FALSE);
828 qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
829
830 if(local)
831 {
832 qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
833 qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
834 }
835 else
836 {
837 qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
838 qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
839 }
840 }
841
842 /*
843 =================
844 S_AL_SaveLoopPos
845 Remove given source as loop master if it is the master and hand off master status to another source in this case.
846 =================
847 */
848
849 static void S_AL_SaveLoopPos(src_t *dest, ALuint alSource)
850 {
851 int error;
852
853 S_AL_ClearError(qfalse);
854
855 qalGetSourcef(alSource, AL_SEC_OFFSET, &dest->lastTimePos);
856 if((error = qalGetError()) != AL_NO_ERROR)
857 {
858 // Old OpenAL implementations don't support AL_SEC_OFFSET
859
860 if(error != AL_INVALID_ENUM)
861 {
862 Com_Printf(S_COLOR_YELLOW "WARNING: Could not get time offset for alSource %d: %s\n",
863 alSource, S_AL_ErrorMsg(error));
864 }
865
866 dest->lastTimePos = -1;
867 }
868 else
869 dest->lastSampleTime = Sys_Milliseconds();
870 }
871
872 /*
873 =================
874 S_AL_NewLoopMaster
875 Remove given source as loop master if it is the master and hand off master status to another source in this case.
876 =================
877 */
878
879 static void S_AL_NewLoopMaster(src_t *rmSource, qboolean iskilled)
880 {
881 int index;
882 src_t *curSource = NULL;
883 alSfx_t *curSfx;
884
885 curSfx = &knownSfx[rmSource->sfx];
886
887 if(rmSource->isPlaying)
888 curSfx->loopActiveCnt--;
889 if(iskilled)
890 curSfx->loopCnt--;
891
892 if(curSfx->loopCnt)
893 {
894 if(rmSource->priority == SRCPRI_ENTITY)
895 {
896 if(!iskilled && rmSource->isPlaying)
897 {
898 // only sync ambient loops...
899 // It makes more sense to have sounds for weapons/projectiles unsynced
900 S_AL_SaveLoopPos(rmSource, rmSource->alSource);
901 }
902 }
903 else if(curSfx->masterLoopSrc != -1 &&
904 rmSource == &srcList[curSfx->masterLoopSrc])
905 {
906 int firstInactive = -1;
907
908 // Only if rmSource was the master and if there are still playing loops for
909 // this sound will we need to find a new master.
910
911 if(iskilled || curSfx->loopActiveCnt)
912 {
913 for(index = 0; index < srcCount; index++)
914 {
915 curSource = &srcList[index];
916
917 if(curSource->sfx == rmSource->sfx && curSource != rmSource &&
918 curSource->isActive && curSource->isLooping && curSource->priority == SRCPRI_AMBIENT)
919 {
920 if(curSource->isPlaying)
921 {
922 curSfx->masterLoopSrc = index;
923 break;
924 }
925 else if(firstInactive < 0)
926 firstInactive = index;
927 }
928 }
929 }
930
931 if(!curSfx->loopActiveCnt)
932 {
933 if(firstInactive < 0)
934 {
935 if(iskilled)
936 {
937 curSfx->masterLoopSrc = -1;
938 return;
939 }
940 else
941 curSource = rmSource;
942 }
943 else
944 curSource = &srcList[firstInactive];
945
946 if(rmSource->isPlaying)
947 {
948 // this was the last not stopped source, save last sample position + time
949 S_AL_SaveLoopPos(curSource, rmSource->alSource);
950 }
951 else
952 {
953 // second case: all loops using this sound have stopped due to listener being of of range,
954 // and now the inactive master gets deleted. Just move over the soundpos settings to the
955 // new master.
956 curSource->lastTimePos = rmSource->lastTimePos;
957 curSource->lastSampleTime = rmSource->lastSampleTime;
958 }
959 }
960 }
961 }
962 else
963 curSfx->masterLoopSrc = -1;
964 }
965
966 /*
967 =================
968 S_AL_SrcKill
969 =================
970 */
971 static void S_AL_SrcKill(srcHandle_t src)
972 {
973 src_t *curSource = &srcList[src];
974
975 // I'm not touching it. Unlock it first.
976 if(curSource->isLocked)
977 return;
978
979 // Remove the entity association and loop master status
980 if(curSource->isLooping)
981 {
982 curSource->isLooping = qfalse;
983
984 if(curSource->entity != -1)
985 {
986 sentity_t *curEnt = &entityList[curSource->entity];
987
988 curEnt->srcAllocated = qfalse;
989 curEnt->srcIndex = -1;
990 curEnt->loopAddedThisFrame = qfalse;
991 curEnt->startLoopingSound = qfalse;
992 }
993
994 S_AL_NewLoopMaster(curSource, qtrue);
995 }
996
997 // Stop it if it's playing
998 if(curSource->isPlaying)
999 {
1000 qalSourceStop(curSource->alSource);
1001 curSource->isPlaying = qfalse;
1002 }
1003
1004 // Detach any buffers
1005 qalSourcei(curSource->alSource, AL_BUFFER, 0);
1006
1007 curSource->sfx = 0;
1008 curSource->lastUsedTime = 0;
1009 curSource->priority = 0;
1010 curSource->entity = -1;
1011 curSource->channel = -1;
1012 if(curSource->isActive)
1013 {
1014 curSource->isActive = qfalse;
1015 srcActiveCnt--;
1016 }
1017 curSource->isLocked = qfalse;
1018 curSource->isTracking = qfalse;
1019 curSource->local = qfalse;
1020 }
1021
1022 /*
1023 =================
1024 S_AL_SrcAlloc
1025 =================
1026 */
1027 static
1028 srcHandle_t S_AL_SrcAlloc( alSrcPriority_t priority, int entnum, int channel )
1029 {
1030 int i;
1031 int empty = -1;
1032 int weakest = -1;
1033 int weakest_time = Sys_Milliseconds();
1034 int weakest_pri = 999;
1035 float weakest_gain = 1000.0;
1036 qboolean weakest_isplaying = qtrue;
1037 int weakest_numloops = 0;
1038 src_t *curSource;
1039
1040 for(i = 0; i < srcCount; i++)
1041 {
1042 curSource = &srcList[i];
1043
1044 // If it's locked, we aren't even going to look at it
1045 if(curSource->isLocked)
1046 continue;
1047
1048 // Is it empty or not?
1049 if(!curSource->isActive)
1050 {
1051 empty = i;
1052 break;
1053 }
1054
1055 if(curSource->isPlaying)
1056 {
1057 if(weakest_isplaying && curSource->priority < priority &&
1058 (curSource->priority < weakest_pri ||
1059 (!curSource->isLooping && (curSource->scaleGain < weakest_gain || curSource->lastUsedTime < weakest_time))))
1060 {
1061 // If it has lower priority, is fainter or older, flag it as weak
1062 // the last two values are only compared if it's not a looping sound, because we want to prevent two
1063 // loops (loops are added EVERY frame) fighting for a slot
1064 weakest_pri = curSource->priority;
1065 weakest_time = curSource->lastUsedTime;
1066 weakest_gain = curSource->scaleGain;
1067 weakest = i;
1068 }
1069 }
1070 else
1071 {
1072 weakest_isplaying = qfalse;
1073
1074 if(weakest < 0 ||
1075 knownSfx[curSource->sfx].loopCnt > weakest_numloops ||
1076 curSource->priority < weakest_pri ||
1077 curSource->lastUsedTime < weakest_time)
1078 {
1079 // Sources currently not playing of course have lowest priority
1080 // also try to always keep at least one loop master for every loop sound
1081 weakest_pri = curSource->priority;
1082 weakest_time = curSource->lastUsedTime;
1083 weakest_numloops = knownSfx[curSource->sfx].loopCnt;
1084 weakest = i;
1085 }
1086 }
1087
1088 // The channel system is not actually adhered to by baseq3, and not
1089 // implemented in snd_dma.c, so while the following is strictly correct, it
1090 // causes incorrect behaviour versus defacto baseq3
1091 #if 0
1092 // Is it an exact match, and not on channel 0?
1093 if((curSource->entity == entnum) && (curSource->channel == channel) && (channel != 0))
1094 {
1095 S_AL_SrcKill(i);
1096 return i;
1097 }
1098 #endif
1099 }
1100
1101 if(empty == -1)
1102 empty = weakest;
1103
1104 if(empty >= 0)
1105 {
1106 S_AL_SrcKill(empty);
1107 srcList[empty].isActive = qtrue;
1108 srcActiveCnt++;
1109 }
1110
1111 return empty;
1112 }
1113
1114 /*
1115 =================
1116 S_AL_SrcFind
1117
1118 Finds an active source with matching entity and channel numbers
1119 Returns -1 if there isn't one
1120 =================
1121 */
1122 #if 0
1123 static
1124 srcHandle_t S_AL_SrcFind(int entnum, int channel)
1125 {
1126 int i;
1127 for(i = 0; i < srcCount; i++)
1128 {
1129 if(!srcList[i].isActive)
1130 continue;
1131 if((srcList[i].entity == entnum) && (srcList[i].channel == channel))
1132 return i;
1133 }
1134 return -1;
1135 }
1136 #endif
1137
1138 /*
1139 =================
1140 S_AL_SrcLock
1141
1142 Locked sources will not be automatically reallocated or managed
1143 =================
1144 */
1145 static
1146 void S_AL_SrcLock(srcHandle_t src)
1147 {
1148 srcList[src].isLocked = qtrue;
1149 }
1150
1151 /*
1152 =================
1153 S_AL_SrcUnlock
1154
1155 Once unlocked, the source may be reallocated again
1156 =================
1157 */
1158 static
1159 void S_AL_SrcUnlock(srcHandle_t src)
1160 {
1161 srcList[src].isLocked = qfalse;
1162 }
1163
1164 /*
1165 =================
1166 S_AL_UpdateEntityPosition
1167 =================
1168 */
1169 static
1170 void S_AL_UpdateEntityPosition( int entityNum, const vec3_t origin )
1171 {
1172 vec3_t sanOrigin;
1173
1174 VectorCopy( origin, sanOrigin );
1175 S_AL_SanitiseVector( sanOrigin );
1176 if ( entityNum < 0 || entityNum >= MAX_GENTITIES )
1177 Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum );
1178 VectorCopy( sanOrigin, entityList[entityNum].origin );
1179 }
1180
1181 /*
1182 =================
1183 S_AL_CheckInput
1184 Check whether input values from mods are out of range.
1185 Necessary for i.g. Western Quake3 mod which is buggy.
1186 =================
1187 */
1188 static qboolean S_AL_CheckInput(int entityNum, sfxHandle_t sfx)
1189 {
1190 if (entityNum < 0 || entityNum >= MAX_GENTITIES)
1191 Com_Error(ERR_DROP, "ERROR: S_AL_CheckInput: bad entitynum %i", entityNum);
1192
1193 if (sfx < 0 || sfx >= numSfx)
1194 {
1195 Com_Printf(S_COLOR_RED "ERROR: S_AL_CheckInput: handle %i out of range\n", sfx);
1196 return qtrue;
1197 }
1198
1199 return qfalse;
1200 }
1201
1202 /*
1203 =================
1204 S_AL_StartLocalSound
1205
1206 Play a local (non-spatialized) sound effect
1207 =================
1208 */
1209 static
1210 void S_AL_StartLocalSound(sfxHandle_t sfx, int channel)
1211 {
1212 srcHandle_t src;
1213
1214 if(S_AL_CheckInput(0, sfx))
1215 return;
1216
1217 // Try to grab a source
1218 src = S_AL_SrcAlloc(SRCPRI_LOCAL, -1, channel);
1219
1220 if(src == -1)
1221 return;
1222
1223 // Set up the effect
1224 S_AL_SrcSetup(src, sfx, SRCPRI_LOCAL, -1, channel, qtrue);
1225
1226 // Start it playing
1227 srcList[src].isPlaying = qtrue;
1228 qalSourcePlay(srcList[src].alSource);
1229 }
1230
1231 /*
1232 =================
1233 S_AL_StartSound
1234
1235 Play a one-shot sound effect
1236 =================
1237 */
1238 static void S_AL_StartSound( vec3_t origin, int entnum, int entchannel, sfxHandle_t sfx )
1239 {
1240 vec3_t sorigin;
1241 srcHandle_t src;
1242 src_t *curSource;
1243
1244 if(origin)
1245 {
1246 if(S_AL_CheckInput(0, sfx))
1247 return;
1248
1249 VectorCopy(origin, sorigin);
1250 }
1251 else
1252 {
1253 if(S_AL_CheckInput(entnum, sfx))
1254 return;
1255
1256 if(S_AL_HearingThroughEntity(entnum))
1257 {
1258 S_AL_StartLocalSound(sfx, entchannel);
1259 return;
1260 }
1261
1262 VectorCopy(entityList[entnum].origin, sorigin);
1263 }
1264
1265 S_AL_SanitiseVector(sorigin);
1266
1267 if((srcActiveCnt > 5 * srcCount / 3) &&
1268 (DistanceSquared(sorigin, lastListenerOrigin) >=
1269 (s_alMaxDistance->value + s_alGraceDistance->value) * (s_alMaxDistance->value + s_alGraceDistance->value)))
1270 {
1271 // We're getting tight on sources and source is not within hearing distance so don't add it
1272 return;
1273 }
1274
1275 // Try to grab a source
1276 src = S_AL_SrcAlloc(SRCPRI_ONESHOT, entnum, entchannel);
1277 if(src == -1)
1278 return;
1279
1280 S_AL_SrcSetup(src, sfx, SRCPRI_ONESHOT, entnum, entchannel, qfalse);
1281
1282 curSource = &srcList[src];
1283
1284 if(!origin)
1285 curSource->isTracking = qtrue;
1286
1287 qalSourcefv(curSource->alSource, AL_POSITION, sorigin );
1288 S_AL_ScaleGain(curSource, sorigin);
1289
1290 // Start it playing
1291 curSource->isPlaying = qtrue;
1292 qalSourcePlay(curSource->alSource);
1293 }
1294
1295 /*
1296 =================
1297 S_AL_ClearLoopingSounds
1298 =================
1299 */
1300 static
1301 void S_AL_ClearLoopingSounds( qboolean killall )
1302 {
1303 int i;
1304 for(i = 0; i < srcCount; i++)
1305 {
1306 if((srcList[i].isLooping) && (srcList[i].entity != -1))
1307 entityList[srcList[i].entity].loopAddedThisFrame = qfalse;
1308 }
1309 }
1310
1311 /*
1312 =================
1313 S_AL_SrcLoop
1314 =================
1315 */
1316 static void S_AL_SrcLoop( alSrcPriority_t priority, sfxHandle_t sfx,
1317 const vec3_t origin, const vec3_t velocity, int entityNum )
1318 {
1319 int src;
1320 sentity_t *sent = &entityList[ entityNum ];
1321 src_t *curSource;
1322 vec3_t sorigin, svelocity;
1323
1324 if(S_AL_CheckInput(entityNum, sfx))
1325 return;
1326
1327 // Do we need to allocate a new source for this entity
1328 if( !sent->srcAllocated )
1329 {
1330 // Try to get a channel
1331 src = S_AL_SrcAlloc( priority, entityNum, -1 );
1332 if( src == -1 )
1333 {
1334 Com_DPrintf( S_COLOR_YELLOW "WARNING: Failed to allocate source "
1335 "for loop sfx %d on entity %d\n", sfx, entityNum );
1336 return;
1337 }
1338
1339 curSource = &srcList[src];
1340
1341 sent->startLoopingSound = qtrue;
1342
1343 curSource->lastTimePos = -1.0;
1344 curSource->lastSampleTime = Sys_Milliseconds();
1345 }
1346 else
1347 {
1348 src = sent->srcIndex;
1349 curSource = &srcList[src];
1350 }
1351
1352 sent->srcAllocated = qtrue;
1353 sent->srcIndex = src;
1354
1355 sent->loopPriority = priority;
1356 sent->loopSfx = sfx;
1357
1358 // If this is not set then the looping sound is stopped.
1359 sent->loopAddedThisFrame = qtrue;
1360
1361 // UGH
1362 // These lines should be called via S_AL_SrcSetup, but we
1363 // can't call that yet as it buffers sfxes that may change
1364 // with subsequent calls to S_AL_SrcLoop
1365 curSource->entity = entityNum;
1366 curSource->isLooping = qtrue;
1367
1368 if( S_AL_HearingThroughEntity( entityNum ) )
1369 {
1370 curSource->local = qtrue;
1371
1372 VectorClear(sorigin);
1373
1374 qalSourcefv(curSource->alSource, AL_POSITION, sorigin);
1375 qalSourcefv(curSource->alSource, AL_VELOCITY, vec3_origin);
1376 }
1377 else
1378 {
1379 curSource->local = qfalse;
1380
1381 if(origin)
1382 VectorCopy(origin, sorigin);
1383 else
1384 VectorCopy(sent->origin, sorigin);
1385
1386 S_AL_SanitiseVector(sorigin);
1387
1388 VectorCopy(sorigin, curSource->loopSpeakerPos);
1389
1390 if(velocity)
1391 {
1392 VectorCopy(velocity, svelocity);
1393 S_AL_SanitiseVector(svelocity);
1394 }
1395 else
1396 VectorClear(svelocity);
1397
1398 qalSourcefv(curSource->alSource, AL_POSITION, (ALfloat *) sorigin);
1399 qalSourcefv(curSource->alSource, AL_VELOCITY, (ALfloat *) svelocity);
1400 }
1401 }
1402
1403 /*
1404 =================
1405 S_AL_AddLoopingSound
1406 =================
1407 */
1408 static void S_AL_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx)
1409 {
1410 S_AL_SrcLoop(SRCPRI_ENTITY, sfx, origin, velocity, entityNum);
1411 }
1412
1413 /*
1414 =================
1415 S_AL_AddRealLoopingSound
1416 =================
1417 */
1418 static void S_AL_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx)
1419 {
1420 S_AL_SrcLoop(SRCPRI_AMBIENT, sfx, origin, velocity, entityNum);
1421 }
1422
1423 /*
1424 =================
1425 S_AL_StopLoopingSound
1426 =================
1427 */
1428 static
1429 void S_AL_StopLoopingSound(int entityNum )
1430 {
1431 if(entityList[entityNum].srcAllocated)
1432 S_AL_SrcKill(entityList[entityNum].srcIndex);
1433 }
1434
1435 /*
1436 =================
1437 S_AL_SrcUpdate
1438
1439 Update state (move things around, manage sources, and so on)
1440 =================
1441 */
1442 static
1443 void S_AL_SrcUpdate( void )
1444 {
1445 int i;
1446 int entityNum;
1447 ALint state;
1448 src_t *curSource;
1449
1450 for(i = 0; i < srcCount; i++)
1451 {
1452 entityNum = srcList[i].entity;
1453 curSource = &srcList[i];
1454
1455 if(curSource->isLocked)
1456 continue;
1457
1458 if(!curSource->isActive)
1459 continue;
1460
1461 // Update source parameters
1462 if((s_alGain->modified) || (s_volume->modified))
1463 curSource->curGain = s_alGain->value * s_volume->value;
1464 if((s_alRolloff->modified) && (!curSource->local))
1465 qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
1466 if(s_alMinDistance->modified)
1467 qalSourcef(curSource->alSource, AL_REFERENCE_DISTANCE, s_alMinDistance->value);
1468
1469 if(curSource->isLooping)
1470 {
1471 sentity_t *sent = &entityList[ entityNum ];
1472
1473 // If a looping effect hasn't been touched this frame, pause or kill it
1474 if(sent->loopAddedThisFrame)
1475 {
1476 alSfx_t *curSfx;
1477
1478 // The sound has changed without an intervening removal
1479 if(curSource->isActive && !sent->startLoopingSound &&
1480 curSource->sfx != sent->loopSfx)
1481 {
1482 S_AL_NewLoopMaster(curSource, qtrue);
1483
1484 curSource->isPlaying = qfalse;
1485 qalSourceStop(curSource->alSource);
1486 qalSourcei(curSource->alSource, AL_BUFFER, 0);
1487 sent->startLoopingSound = qtrue;
1488 }
1489
1490 // The sound hasn't been started yet
1491 if(sent->startLoopingSound)
1492 {
1493 S_AL_SrcSetup(i, sent->loopSfx, sent->loopPriority,
1494 entityNum, -1, curSource->local);
1495 curSource->isLooping = qtrue;
1496
1497 knownSfx[curSource->sfx].loopCnt++;
1498 sent->startLoopingSound = qfalse;
1499 }
1500
1501 curSfx = &knownSfx[curSource->sfx];
1502
1503 S_AL_ScaleGain(curSource, curSource->loopSpeakerPos);
1504 if(!curSource->scaleGain)
1505 {
1506 if(curSource->isPlaying)
1507 {
1508 // Sound is mute, stop playback until we are in range again
1509 S_AL_NewLoopMaster(curSource, qfalse);
1510 qalSourceStop(curSource->alSource);
1511 curSource->isPlaying = qfalse;
1512 }
1513 else if(!curSfx->loopActiveCnt && curSfx->masterLoopSrc < 0)
1514 curSfx->masterLoopSrc = i;
1515
1516 continue;
1517 }
1518
1519 if(!curSource->isPlaying)
1520 {
1521 qalSourcei(curSource->alSource, AL_LOOPING, AL_TRUE);
1522 curSource->isPlaying = qtrue;
1523 qalSourcePlay(curSource->alSource);
1524
1525 if(curSource->priority == SRCPRI_AMBIENT)
1526 {
1527 // If there are other ambient looping sources with the same sound,
1528 // make sure the sound of these sources are in sync.
1529
1530 if(curSfx->loopActiveCnt)
1531 {
1532 int offset, error;
1533
1534 // we already have a master loop playing, get buffer position.
1535 S_AL_ClearError(qfalse);
1536 qalGetSourcei(srcList[curSfx->masterLoopSrc].alSource, AL_SAMPLE_OFFSET, &offset);
1537 if((error = qalGetError()) != AL_NO_ERROR)
1538 {
1539 if(error != AL_INVALID_ENUM)
1540 {
1541 Com_Printf(S_COLOR_YELLOW "WARNING: Cannot get sample offset from source %d: "
1542 "%s\n", i, S_AL_ErrorMsg(error));
1543 }
1544 }
1545 else
1546 qalSourcei(curSource->alSource, AL_SAMPLE_OFFSET, offset);
1547 }
1548 else if(curSfx->loopCnt && curSfx->masterLoopSrc >= 0)
1549 {
1550 float secofs;
1551
1552 src_t *master = &srcList[curSfx->masterLoopSrc];
1553 // This loop sound used to be played, but all sources are stopped. Use last sample position/time
1554 // to calculate offset so the player thinks the sources continued playing while they were inaudible.
1555
1556 if(master->lastTimePos >= 0)
1557 {
1558 secofs = master->lastTimePos + (Sys_Milliseconds() - master->lastSampleTime) / 1000.0f;
1559 secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
1560
1561 qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
1562 }
1563
1564 // I be the master now
1565 curSfx->masterLoopSrc = i;
1566 }
1567 else
1568 curSfx->masterLoopSrc = i;
1569 }
1570 else if(curSource->lastTimePos >= 0)
1571 {
1572 float secofs;
1573
1574 // For unsynced loops (SRCPRI_ENTITY) just carry on playing as if the sound was never stopped
1575
1576 secofs = curSource->lastTimePos + (Sys_Milliseconds() - curSource->lastSampleTime) / 1000.0f;
1577 secofs = fmodf(secofs, (float) curSfx->info.samples / curSfx->info.rate);
1578 qalSourcef(curSource->alSource, AL_SEC_OFFSET, secofs);
1579 }
1580
1581 curSfx->loopActiveCnt++;
1582 }
1583
1584 // Update locality
1585 if(curSource->local)
1586 {
1587 qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_TRUE);
1588 qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, 0.0f);
1589 }
1590 else
1591 {
1592 qalSourcei(curSource->alSource, AL_SOURCE_RELATIVE, AL_FALSE);
1593 qalSourcef(curSource->alSource, AL_ROLLOFF_FACTOR, s_alRolloff->value);
1594 }
1595
1596 }
1597 else if(curSource->priority == SRCPRI_AMBIENT)
1598 {
1599 if(curSource->isPlaying)
1600 {
1601 S_AL_NewLoopMaster(curSource, qfalse);
1602 qalSourceStop(curSource->alSource);
1603 curSource->isPlaying = qfalse;
1604 }
1605 }
1606 else
1607 S_AL_SrcKill(i);
1608
1609 continue;
1610 }
1611
1612 if(!curSource->isStream)
1613 {
1614 // Check if it's done, and flag it
1615 qalGetSourcei(curSource->alSource, AL_SOURCE_STATE, &state);
1616 if(state == AL_STOPPED)
1617 {
1618 curSource->isPlaying = qfalse;
1619 S_AL_SrcKill(i);
1620 continue;
1621 }
1622 }
1623
1624 // Query relativity of source, don't move if it's true
1625 qalGetSourcei(curSource->alSource, AL_SOURCE_RELATIVE, &state);
1626
1627 // See if it needs to be moved
1628 if(curSource->isTracking && !state)
1629 {
1630 qalSourcefv(curSource->alSource, AL_POSITION, entityList[entityNum].origin);
1631 S_AL_ScaleGain(curSource, entityList[entityNum].origin);
1632 }
1633 }
1634 }
1635
1636 /*
1637 =================
1638 S_AL_SrcShutup
1639 =================
1640 */
1641 static
1642 void S_AL_SrcShutup( void )
1643 {
1644 int i;
1645 for(i = 0; i < srcCount; i++)
1646 S_AL_SrcKill(i);
1647 }
1648
1649 /*
1650 =================
1651 S_AL_SrcGet
1652 =================
1653 */
1654 static
1655 ALuint S_AL_SrcGet(srcHandle_t src)
1656 {
1657 return srcList[src].alSource;
1658 }
1659
1660
1661 //===========================================================================
1662
1663 // Q3A cinematics use up to 12 buffers at once
1664 #define MAX_STREAM_BUFFERS 20
1665
1666 static srcHandle_t streamSourceHandles[MAX_RAW_STREAMS];
1667 static qboolean streamPlaying[MAX_RAW_STREAMS];
1668 static ALuint streamSources[MAX_RAW_STREAMS];
1669 static ALuint streamBuffers[MAX_RAW_STREAMS][MAX_STREAM_BUFFERS];
1670 static int streamNumBuffers[MAX_RAW_STREAMS];
1671 static int streamBufIndex[MAX_RAW_STREAMS];
1672
1673 /*
1674 =================
1675 S_AL_AllocateStreamChannel
1676 =================
1677 */
1678 static void S_AL_AllocateStreamChannel(int stream, int entityNum)
1679 {
1680 srcHandle_t cursrc;
1681 ALuint alsrc;
1682
1683 if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
1684 return;
1685
1686 if(entityNum >= 0)
1687 {
1688 // This is a stream that tracks an entity
1689 // Allocate a streamSource at normal priority
1690 cursrc = S_AL_SrcAlloc(SRCPRI_ENTITY, entityNum, 0);
1691 if(cursrc < 0)
1692 return;
1693
1694 S_AL_SrcSetup(cursrc, -1, SRCPRI_ENTITY, entityNum, 0, qfalse);
1695 alsrc = S_AL_SrcGet(cursrc);
1696 srcList[cursrc].isTracking = qtrue;
1697 srcList[cursrc].isStream = qtrue;
1698 }
1699 else
1700 {
1701 // Unspatialized stream source
1702
1703 // Allocate a streamSource at high priority
1704 cursrc = S_AL_SrcAlloc(SRCPRI_STREAM, -2, 0);
1705 if(cursrc < 0)
1706 return;
1707
1708 alsrc = S_AL_SrcGet(cursrc);
1709
1710 // Lock the streamSource so nobody else can use it, and get the raw streamSource
1711 S_AL_SrcLock(cursrc);
1712
1713 // make sure that after unmuting the S_AL_Gain in S_Update() does not turn
1714 // volume up prematurely for this source
1715 srcList[cursrc].scaleGain = 0.0f;
1716
1717 // Set some streamSource parameters
1718 qalSourcei (alsrc, AL_BUFFER, 0 );
1719 qalSourcei (alsrc, AL_LOOPING, AL_FALSE );
1720 qalSource3f(alsrc, AL_POSITION, 0.0, 0.0, 0.0);
1721 qalSource3f(alsrc, AL_VELOCITY, 0.0, 0.0, 0.0);
1722 qalSource3f(alsrc, AL_DIRECTION, 0.0, 0.0, 0.0);
1723 qalSourcef (alsrc, AL_ROLLOFF_FACTOR, 0.0 );
1724 qalSourcei (alsrc, AL_SOURCE_RELATIVE, AL_TRUE );
1725 }
1726
1727 streamSourceHandles[stream] = cursrc;
1728 streamSources[stream] = alsrc;
1729
1730 streamNumBuffers[stream] = 0;
1731 streamBufIndex[stream] = 0;
1732 }
1733
1734 /*
1735 =================
1736 S_AL_FreeStreamChannel
1737 =================
1738 */
1739 static void S_AL_FreeStreamChannel( int stream )
1740 {
1741 if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
1742 return;
1743
1744 // Detach any buffers
1745 qalSourcei(streamSources[stream], AL_BUFFER, 0);
1746
1747 // Delete the buffers
1748 if (streamNumBuffers[stream] > 0) {
1749 qalDeleteBuffers(streamNumBuffers[stream], streamBuffers[stream]);
1750 streamNumBuffers[stream] = 0;
1751 }
1752
1753 // Release the output streamSource
1754 S_AL_SrcUnlock(streamSourceHandles[stream]);
1755 S_AL_SrcKill(streamSourceHandles[stream]);
1756 streamSources[stream] = 0;
1757 streamSourceHandles[stream] = -1;
1758 }
1759
1760 /*
1761 =================
1762 S_AL_RawSamples
1763 =================
1764 */
1765 static
1766 void S_AL_RawSamples(int stream, int samples, int rate, int width, int channels, const byte *data, float volume, int entityNum)
1767 {
1768 int numBuffers;
1769 ALuint buffer;
1770 ALuint format;
1771
1772 if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
1773 return;
1774
1775 format = S_AL_Format( width, channels );
1776
1777 // Create the streamSource if necessary
1778 if(streamSourceHandles[stream] == -1)
1779 {
1780 S_AL_AllocateStreamChannel(stream, entityNum);
1781
1782 // Failed?
1783 if(streamSourceHandles[stream] == -1)
1784 {
1785 Com_Printf( S_COLOR_RED "ERROR: Can't allocate streaming streamSource\n");
1786 return;
1787 }
1788 }
1789
1790 qalGetSourcei(streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers);
1791
1792 if (numBuffers == MAX_STREAM_BUFFERS)
1793 {
1794 Com_DPrintf(S_COLOR_RED"WARNING: Steam dropping raw samples, reached MAX_STREAM_BUFFERS\n");
1795 return;
1796 }
1797
1798 // Allocate a new AL buffer if needed
1799 if (numBuffers == streamNumBuffers[stream])
1800 {
1801 ALuint oldBuffers[MAX_STREAM_BUFFERS];
1802 int i;
1803
1804 if (!S_AL_GenBuffers(1, &buffer, "stream"))
1805 return;
1806
1807 Com_Memcpy(oldBuffers, &streamBuffers[stream], sizeof (oldBuffers));
1808
1809 // Reorder buffer array in order of oldest to newest
1810 for ( i = 0; i < streamNumBuffers[stream]; ++i )
1811 streamBuffers[stream][i] = oldBuffers[(streamBufIndex[stream] + i) % streamNumBuffers[stream]];
1812
1813 // Add the new buffer to end
1814 streamBuffers[stream][streamNumBuffers[stream]] = buffer;
1815 streamBufIndex[stream] = streamNumBuffers[stream];
1816 streamNumBuffers[stream]++;
1817 }
1818
1819 // Select next buffer in loop
1820 buffer = streamBuffers[stream][ streamBufIndex[stream] ];
1821 streamBufIndex[stream] = (streamBufIndex[stream] + 1) % streamNumBuffers[stream];
1822
1823 // Fill buffer
1824 qalBufferData(buffer, format, (ALvoid *)data, (samples * width * channels), rate);
1825
1826 // Shove the data onto the streamSource
1827 qalSourceQueueBuffers(streamSources[stream], 1, &buffer);
1828
1829 if(entityNum < 0)
1830 {
1831 // Volume
1832 S_AL_Gain (streamSources[stream], volume * s_volume->value * s_alGain->value);
1833 }
1834
1835 // Start stream
1836 if(!streamPlaying[stream])
1837 {
1838 qalSourcePlay( streamSources[stream] );
1839 streamPlaying[stream] = qtrue;
1840 }
1841 }
1842
1843 /*
1844 =================
1845 S_AL_StreamUpdate
1846 =================
1847 */
1848 static
1849 void S_AL_StreamUpdate( int stream )
1850 {
1851 int numBuffers;
1852 ALint state;
1853
1854 if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
1855 return;
1856
1857 if(streamSourceHandles[stream] == -1)
1858 return;
1859
1860 // Un-queue any buffers
1861 qalGetSourcei( streamSources[stream], AL_BUFFERS_PROCESSED, &numBuffers );
1862 while( numBuffers-- )
1863 {
1864 ALuint buffer;
1865 qalSourceUnqueueBuffers(streamSources[stream], 1, &buffer);
1866 }
1867
1868 // Start the streamSource playing if necessary
1869 qalGetSourcei( streamSources[stream], AL_BUFFERS_QUEUED, &numBuffers );
1870
1871 qalGetSourcei(streamSources[stream], AL_SOURCE_STATE, &state);
1872 if(state == AL_STOPPED)
1873 {
1874 streamPlaying[stream] = qfalse;
1875
1876 // If there are no buffers queued up, release the streamSource
1877 if( !numBuffers )
1878 S_AL_FreeStreamChannel( stream );
1879 }
1880
1881 if( !streamPlaying[stream] && numBuffers )
1882 {
1883 qalSourcePlay( streamSources[stream] );
1884 streamPlaying[stream] = qtrue;
1885 }
1886 }
1887
1888 /*
1889 =================
1890 S_AL_StreamDie
1891 =================
1892 */
1893 static
1894 void S_AL_StreamDie( int stream )
1895 {
1896 if ((stream < 0) || (stream >= MAX_RAW_STREAMS))
1897 return;
1898
1899 if(streamSourceHandles[stream] == -1)
1900 return;
1901
1902 streamPlaying[stream] = qfalse;
1903 qalSourceStop(streamSources[stream]);
1904
1905 S_AL_FreeStreamChannel(stream);
1906 }
1907
1908
1909 //===========================================================================
1910
1911
1912 #define NUM_MUSIC_BUFFERS 4
1913 #define MUSIC_BUFFER_SIZE 4096
1914
1915 static qboolean musicPlaying = qfalse;
1916 static srcHandle_t musicSourceHandle = -1;
1917 static ALuint musicSource;
1918 static ALuint musicBuffers[NUM_MUSIC_BUFFERS];
1919
1920 static snd_stream_t *mus_stream;
1921 static snd_stream_t *intro_stream;
1922 static char s_backgroundLoop[MAX_QPATH];
1923
1924 static byte decode_buffer[MUSIC_BUFFER_SIZE];
1925
1926 /*
1927 =================
1928 S_AL_MusicSourceGet
1929 =================
1930 */
1931 static void S_AL_MusicSourceGet( void )
1932 {
1933 // Allocate a musicSource at high priority
1934 musicSourceHandle = S_AL_SrcAlloc(SRCPRI_STREAM, -2, 0);
1935 if(musicSourceHandle == -1)
1936 return;
1937
1938 // Lock the musicSource so nobody else can use it, and get the raw musicSource
1939 S_AL_SrcLock(musicSourceHandle);
1940 musicSource = S_AL_SrcGet(musicSourceHandle);
1941
1942 // make sure that after unmuting the S_AL_Gain in S_Update() does not turn
1943 // volume up prematurely for this source
1944 srcList[musicSourceHandle].scaleGain = 0.0f;
1945
1946 // Set some musicSource parameters
1947 qalSource3f(musicSource, AL_POSITION, 0.0, 0.0, 0.0);
1948 qalSource3f(musicSource, AL_VELOCITY, 0.0, 0.0, 0.0);
1949 qalSource3f(musicSource, AL_DIRECTION, 0.0, 0.0, 0.0);
1950 qalSourcef (musicSource, AL_ROLLOFF_FACTOR, 0.0 );
1951 qalSourcei (musicSource, AL_SOURCE_RELATIVE, AL_TRUE );
1952 }
1953
1954 /*
1955 =================
1956 S_AL_MusicSourceFree
1957 =================
1958 */
1959 static void S_AL_MusicSourceFree( void )
1960 {
1961 // Release the output musicSource
1962 S_AL_SrcUnlock(musicSourceHandle);
1963 S_AL_SrcKill(musicSourceHandle);
1964 musicSource = 0;
1965 musicSourceHandle = -1;
1966 }
1967
1968 /*
1969 =================
1970 S_AL_CloseMusicFiles
1971 =================
1972 */
1973 static void S_AL_CloseMusicFiles(void)
1974 {
1975 if(intro_stream)
1976 {
1977 S_CodecCloseStream(intro_stream);
1978 intro_stream = NULL;
1979 }
1980
1981 if(mus_stream)
1982 {
1983 S_CodecCloseStream(mus_stream);
1984 mus_stream = NULL;
1985 }
1986 }
1987
1988 /*
1989 =================
1990 S_AL_StopBackgroundTrack
1991 =================
1992 */
1993 static
1994 void S_AL_StopBackgroundTrack( void )
1995 {
1996 if(!musicPlaying)
1997 return;
1998
1999 // Stop playing
2000 qalSourceStop(musicSource);
2001
2002 // Detach any buffers
2003 qalSourcei(musicSource, AL_BUFFER, 0);
2004
2005 // Delete the buffers
2006 qalDeleteBuffers(NUM_MUSIC_BUFFERS, musicBuffers);
2007
2008 // Free the musicSource
2009 S_AL_MusicSourceFree();
2010
2011 // Unload the stream
2012 S_AL_CloseMusicFiles();
2013
2014 musicPlaying = qfalse;
2015 }
2016
2017 /*
2018 =================
2019 S_AL_MusicProcess
2020 =================
2021 */
2022 static
2023 void S_AL_MusicProcess(ALuint b)
2024 {
2025 ALenum error;
2026 int l;
2027 ALuint format;
2028 snd_stream_t *curstream;
2029
2030 S_AL_ClearError( qfalse );
2031
2032 if(intro_stream)
2033 curstream = intro_stream;
2034 else
2035 curstream = mus_stream;
2036
2037 if(!curstream)
2038 return;
2039
2040 l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
2041
2042 // Run out data to read, start at the beginning again
2043 if(l == 0)
2044 {
2045 S_CodecCloseStream(curstream);
2046
2047 // the intro stream just finished playing so we don't need to reopen
2048 // the music stream.
2049 if(intro_stream)
2050 intro_stream = NULL;
2051 else
2052 mus_stream = S_CodecOpenStream(s_backgroundLoop);
2053
2054 curstream = mus_stream;
2055
2056 if(!curstream)
2057 {
2058 S_AL_StopBackgroundTrack();
2059 return;
2060 }
2061
2062 l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
2063 }
2064
2065 format = S_AL_Format(curstream->info.width, curstream->info.channels);
2066
2067 if( l == 0 )
2068 {
2069 // We have no data to buffer, so buffer silence
2070 byte dummyData[ 2 ] = { 0 };
2071
2072 qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
2073 }
2074 else
2075 qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
2076
2077 if( ( error = qalGetError( ) ) != AL_NO_ERROR )
2078 {
2079 S_AL_StopBackgroundTrack( );
2080 Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
2081 S_AL_ErrorMsg( error ) );
2082 return;
2083 }
2084 }
2085
2086 /*
2087 =================
2088 S_AL_StartBackgroundTrack
2089 =================
2090 */
2091 static
2092 void S_AL_StartBackgroundTrack( const char *intro, const char *loop )
2093 {
2094 int i;
2095 qboolean issame;
2096
2097 // Stop any existing music that might be playing
2098 S_AL_StopBackgroundTrack();
2099
2100 if((!intro || !*intro) && (!loop || !*loop))
2101 return;
2102
2103 // Allocate a musicSource
2104 S_AL_MusicSourceGet();
2105 if(musicSourceHandle == -1)
2106 return;
2107
2108 if (!loop || !*loop)
2109 {
2110 loop = intro;
2111 issame = qtrue;
2112 }
2113 else if(intro && *intro && !strcmp(intro, loop))
2114 issame = qtrue;
2115 else
2116 issame = qfalse;
2117
2118 // Copy the loop over
2119 Q_strncpyz( s_backgroundLoop, loop, sizeof( s_backgroundLoop ) );
2120
2121 if(!issame)
2122 {
2123 // Open the intro and don't mind whether it succeeds.
2124 // The important part is the loop.
2125 intro_stream = S_CodecOpenStream(intro);
2126 }
2127 else
2128 intro_stream = NULL;
2129
2130 mus_stream = S_CodecOpenStream(s_backgroundLoop);
2131 if(!mus_stream)
2132 {
2133 S_AL_CloseMusicFiles();
2134 S_AL_MusicSourceFree();
2135 return;
2136 }
2137
2138 // Generate the musicBuffers
2139 if (!S_AL_GenBuffers(NUM_MUSIC_BUFFERS, musicBuffers, "music"))
2140 return;
2141
2142 // Queue the musicBuffers up
2143 for(i = 0; i < NUM_MUSIC_BUFFERS; i++)
2144 {
2145 S_AL_MusicProcess(musicBuffers[i]);
2146 }
2147
2148 qalSourceQueueBuffers(musicSource, NUM_MUSIC_BUFFERS, musicBuffers);
2149
2150 // Set the initial gain property
2151 S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
2152
2153 // Start playing
2154 qalSourcePlay(musicSource);
2155
2156 musicPlaying = qtrue;
2157 }
2158
2159 /*
2160 =================
2161 S_AL_MusicUpdate
2162 =================
2163 */
2164 static
2165 void S_AL_MusicUpdate( void )
2166 {
2167 int numBuffers;
2168 ALint state;
2169
2170 if(!musicPlaying)
2171 return;
2172
2173 qalGetSourcei( musicSource, AL_BUFFERS_PROCESSED, &numBuffers );
2174 while( numBuffers-- )
2175 {
2176 ALuint b;
2177 qalSourceUnqueueBuffers(musicSource, 1, &b);
2178 S_AL_MusicProcess(b);
2179 qalSourceQueueBuffers(musicSource, 1, &b);
2180 }
2181
2182 // Hitches can cause OpenAL to be starved of buffers when streaming.
2183 // If this happens, it will stop playback. This restarts the source if
2184 // it is no longer playing, and if there are buffers available
2185 qalGetSourcei( musicSource, AL_SOURCE_STATE, &state );
2186 qalGetSourcei( musicSource, AL_BUFFERS_QUEUED, &numBuffers );
2187 if( state == AL_STOPPED && numBuffers )
2188 {
2189 Com_DPrintf( S_COLOR_YELLOW "Restarted OpenAL music\n" );
2190 qalSourcePlay(musicSource);
2191 }
2192
2193 // Set the gain property
2194 S_AL_Gain(musicSource, s_alGain->value * s_musicVolume->value);
2195 }
2196
2197
2198 //===========================================================================
2199
2200
2201 // Local state variables
2202 static ALCdevice *alDevice;
2203 static ALCcontext *alContext;
2204
2205 #ifdef USE_VOIP
2206 static ALCdevice *alCaptureDevice;
2207 static cvar_t *s_alCapture;
2208 #endif
2209
2210 #if defined(_WIN64)
2211 #define ALDRIVER_DEFAULT "OpenAL64.dll"
2212 #elif defined(_WIN32)
2213 #define ALDRIVER_DEFAULT "OpenAL32.dll"
2214 #elif defined(__APPLE__)
2215 #define ALDRIVER_DEFAULT "/System/Library/Frameworks/OpenAL.framework/OpenAL"
2216 #elif defined(__OpenBSD__)
2217 #define ALDRIVER_DEFAULT "libopenal.so"
2218 #else
2219 #define ALDRIVER_DEFAULT "libopenal.so.1"
2220 #endif
2221
2222 /*
2223 =================
2224 S_AL_StopAllSounds
2225 =================
2226 */
2227 static
2228 void S_AL_StopAllSounds( void )
2229 {
2230 int i;
2231 S_AL_SrcShutup();
2232 S_AL_StopBackgroundTrack();
2233 for (i = 0; i < MAX_RAW_STREAMS; i++)
2234 S_AL_StreamDie(i);
2235 }
2236
2237 /*
2238 =================
2239 S_AL_Respatialize
2240 =================
2241 */
2242 static
2243 void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
2244 {
2245 float orientation[6];
2246 vec3_t sorigin;
2247
2248 VectorCopy( origin, sorigin );
2249 S_AL_SanitiseVector( sorigin );
2250
2251 S_AL_SanitiseVector( axis[ 0 ] );
2252 S_AL_SanitiseVector( axis[ 1 ] );
2253 S_AL_SanitiseVector( axis[ 2 ] );
2254
2255 orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
2256 orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
2257
2258 lastListenerNumber = entityNum;
2259 VectorCopy( sorigin, lastListenerOrigin );
2260
2261 // Set OpenAL listener paramaters
2262 qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
2263 qalListenerfv(AL_VELOCITY, vec3_origin);
2264 qalListenerfv(AL_ORIENTATION, orientation);
2265 }
2266
2267 /*
2268 =================
2269 S_AL_Update
2270 =================
2271 */
2272 static
2273 void S_AL_Update( void )
2274 {
2275 int i;
2276
2277 if(s_muted->modified)
2278 {
2279 // muted state changed. Let S_AL_Gain turn up all sources again.
2280 for(i = 0; i < srcCount; i++)
2281 {
2282 if(srcList[i].isActive)
2283 S_AL_Gain(srcList[i].alSource, srcList[i].scaleGain);
2284 }
2285
2286 s_muted->modified = qfalse;
2287 }
2288
2289 // Update SFX channels
2290 S_AL_SrcUpdate();
2291
2292 // Update streams
2293 for (i = 0; i < MAX_RAW_STREAMS; i++)
2294 S_AL_StreamUpdate(i);
2295 S_AL_MusicUpdate();
2296
2297 // Doppler
2298 if(s_doppler->modified)
2299 {
2300 s_alDopplerFactor->modified = qtrue;
2301 s_doppler->modified = qfalse;
2302 }
2303
2304 // Doppler parameters
2305 if(s_alDopplerFactor->modified)
2306 {
2307 if(s_doppler->integer)
2308 qalDopplerFactor(s_alDopplerFactor->value);
2309 else
2310 qalDopplerFactor(0.0f);
2311 s_alDopplerFactor->modified = qfalse;
2312 }
2313 if(s_alDopplerSpeed->modified)
2314 {
2315 qalSpeedOfSound(s_alDopplerSpeed->value);
2316 s_alDopplerSpeed->modified = qfalse;
2317 }
2318
2319 // Clear the modified flags on the other cvars
2320 s_alGain->modified = qfalse;
2321 s_volume->modified = qfalse;
2322 s_musicVolume->modified = qfalse;
2323 s_alMinDistance->modified = qfalse;
2324 s_alRolloff->modified = qfalse;
2325 }
2326
2327 /*
2328 =================
2329 S_AL_DisableSounds
2330 =================
2331 */
2332 static
2333 void S_AL_DisableSounds( void )
2334 {
2335 S_AL_StopAllSounds();
2336 }
2337
2338 /*
2339 =================
2340 S_AL_BeginRegistration
2341 =================
2342 */
2343 static
2344 void S_AL_BeginRegistration( void )
2345 {
2346 if(!numSfx)
2347 S_AL_BufferInit();
2348 }
2349
2350 /*
2351 =================
2352 S_AL_ClearSoundBuffer
2353 =================
2354 */
2355 static
2356 void S_AL_ClearSoundBuffer( void )
2357 {
2358 }
2359
2360 /*
2361 =================
2362 S_AL_SoundList
2363 =================
2364 */
2365 static
2366 void S_AL_SoundList( void )
2367 {
2368 int i;
2369 alSfx_t *sfx;
2370 int size, total;
2371
2372 total = 0;
2373 for (sfx=knownSfx, i=0 ; i<numSfx ; i++, sfx++) {
2374 size = sfx->info.samples;
2375 total += size;
2376 Com_Printf("%6i : %s[%s]\n", size,
2377 sfx->filename, sfx->inMemory ? "resident " : "paged out");
2378 }
2379 Com_Printf ("Total resident: %i\n", total);
2380 }
2381
2382 #ifdef USE_VOIP
2383 static
2384 void S_AL_StartCapture( void )
2385 {
2386 if (alCaptureDevice != NULL)
2387 qalcCaptureStart(alCaptureDevice);
2388 }
2389
2390 static
2391 int S_AL_AvailableCaptureSamples( void )
2392 {
2393 int retval = 0;
2394 if (alCaptureDevice != NULL)
2395 {
2396 ALint samples = 0;
2397 qalcGetIntegerv(alCaptureDevice, ALC_CAPTURE_SAMPLES, sizeof (samples), &samples);
2398 retval = (int) samples;
2399 }
2400 return retval;
2401 }
2402
2403 static
2404 void S_AL_Capture( int samples, byte *data )
2405 {
2406 if (alCaptureDevice != NULL)
2407 qalcCaptureSamples(alCaptureDevice, data, samples);
2408 }
2409
2410 void S_AL_StopCapture( void )
2411 {
2412 if (alCaptureDevice != NULL)
2413 qalcCaptureStop(alCaptureDevice);
2414 }
2415
2416 void S_AL_MasterGain( float gain )
2417 {
2418 qalListenerf(AL_GAIN, gain);
2419 }
2420 #endif
2421
2422
2423 /*
2424 =================
2425 S_AL_SoundInfo
2426 =================
2427 */
2428 static void S_AL_SoundInfo(void)
2429 {
2430 Com_Printf( "OpenAL info:\n" );
2431 Com_Printf( " Vendor: %s\n", qalGetString( AL_VENDOR ) );
2432 Com_Printf( " Version: %s\n", qalGetString( AL_VERSION ) );
2433 Com_Printf( " Renderer: %s\n", qalGetString( AL_RENDERER ) );
2434 Com_Printf( " AL Extensions: %s\n", qalGetString( AL_EXTENSIONS ) );
2435 Com_Printf( " ALC Extensions: %s\n", qalcGetString( alDevice, ALC_EXTENSIONS ) );
2436
2437 if(enumeration_all_ext)
2438 Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_ALL_DEVICES_SPECIFIER));
2439 else if(enumeration_ext)
2440 Com_Printf(" Device: %s\n", qalcGetString(alDevice, ALC_DEVICE_SPECIFIER));
2441
2442 if(enumeration_all_ext || enumeration_ext)
2443 Com_Printf(" Available Devices:\n%s", s_alAvailableDevices->string);
2444
2445 #ifdef USE_VOIP
2446 if(capture_ext)
2447 {
2448 Com_Printf(" Input Device: %s\n", qalcGetString(alCaptureDevice, ALC_CAPTURE_DEVICE_SPECIFIER));
2449 Com_Printf(" Available Input Devices:\n%s", s_alAvailableInputDevices->string);
2450 }
2451 #endif
2452 }
2453
2454
2455
2456 /*
2457 =================
2458 S_AL_Shutdown
2459 =================
2460 */
2461 static
2462 void S_AL_Shutdown( void )
2463 {
2464 // Shut down everything
2465 int i;
2466 for (i = 0; i < MAX_RAW_STREAMS; i++)
2467 S_AL_StreamDie(i);
2468 S_AL_StopBackgroundTrack( );
2469 S_AL_SrcShutdown( );
2470 S_AL_BufferShutdown( );
2471
2472 qalcDestroyContext(alContext);
2473 qalcCloseDevice(alDevice);
2474
2475 #ifdef USE_VOIP
2476 if (alCaptureDevice != NULL) {
2477 qalcCaptureStop(alCaptureDevice);
2478 qalcCaptureCloseDevice(alCaptureDevice);
2479 alCaptureDevice = NULL;
2480 Com_Printf( "OpenAL capture device closed.\n" );
2481 }
2482 #endif
2483
2484 for (i = 0; i < MAX_RAW_STREAMS; i++) {
2485 streamSourceHandles[i] = -1;
2486 streamPlaying[i] = qfalse;
2487 streamSources[i] = 0;
2488 }
2489
2490 QAL_Shutdown();
2491 }
2492
2493 #endif
2494
2495 /*
2496 =================
2497 S_AL_Init
2498 =================
2499 */
2500 qboolean S_AL_Init( soundInterface_t *si )
2501 {
2502 #ifdef USE_OPENAL
2503 const char* device = NULL;
2504 const char* inputdevice = NULL;
2505 int i;
2506
2507 if( !si ) {
2508 return qfalse;
2509 }
2510
2511 for (i = 0; i < MAX_RAW_STREAMS; i++) {
2512 streamSourceHandles[i] = -1;
2513 streamPlaying[i] = qfalse;
2514 streamSources[i] = 0;
2515 streamNumBuffers[i] = 0;
2516 streamBufIndex[i] = 0;
2517 }
2518
2519 // New console variables
2520 s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
2521 s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
2522 s_alSources = Cvar_Get( "s_alSources", "96", CVAR_ARCHIVE );
2523 s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
2524 s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
2525 s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
2526 s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
2527 s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
2528 s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
2529
2530 s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED );
2531
2532 s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
2533 s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
2534
2535 // Load QAL
2536 if( !QAL_Init( s_alDriver->string ) )
2537 {
2538 Com_Printf( "Failed to load library: \"%s\".\n", s_alDriver->string );
2539 if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
2540 return qfalse;
2541 }
2542 }
2543
2544 device = s_alDevice->string;
2545 if(device && !*device)
2546 device = NULL;
2547
2548 inputdevice = s_alInputDevice->string;
2549 if(inputdevice && !*inputdevice)
2550 inputdevice = NULL;
2551
2552
2553 // Device enumeration support
2554 enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
2555 enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
2556
2557 if(enumeration_ext || enumeration_all_ext)
2558 {
2559 char devicenames[16384] = "";
2560 const char *devicelist;
2561 #ifdef _WIN32
2562 const char *defaultdevice;
2563 #endif
2564 int curlen;
2565
2566 // get all available devices + the default device name.
2567 if(enumeration_all_ext)
2568 {
2569 devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
2570 #ifdef _WIN32
2571 defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
2572 #endif
2573 }
2574 else
2575 {
2576 // We don't have ALC_ENUMERATE_ALL_EXT but normal enumeration.
2577 devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
2578 #ifdef _WIN32
2579 defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
2580 #endif
2581 enumeration_ext = qtrue;
2582 }
2583
2584 #ifdef _WIN32
2585 // check whether the default device is generic hardware. If it is, change to
2586 // Generic Software as that one works more reliably with various sound systems.
2587 // If it's not, use OpenAL's default selection as we don't want to ignore
2588 // native hardware acceleration.
2589 if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
2590 device = "Generic Software";
2591 #endif
2592
2593 // dump a list of available devices to a cvar for the user to see.
2594
2595 if(devicelist)
2596 {
2597 while((curlen = strlen(devicelist)))
2598 {
2599 Q_strcat(devicenames, sizeof(devicenames), devicelist);
2600 Q_strcat(devicenames, sizeof(devicenames), "\n");
2601
2602 devicelist += curlen + 1;
2603 }
2604 }
2605
2606 s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
2607 }
2608
2609 alDevice = qalcOpenDevice(device);
2610 if( !alDevice && device )
2611 {
2612 Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
2613 alDevice = qalcOpenDevice(NULL);
2614 }
2615
2616 if( !alDevice )
2617 {
2618 QAL_Shutdown( );
2619 Com_Printf( "Failed to open OpenAL device.\n" );
2620 return qfalse;
2621 }
2622
2623 // Create OpenAL context
2624 alContext = qalcCreateContext( alDevice, NULL );
2625 if( !alContext )
2626 {
2627 QAL_Shutdown( );
2628 qalcCloseDevice( alDevice );
2629 Com_Printf( "Failed to create OpenAL context.\n" );
2630 return qfalse;
2631 }
2632 qalcMakeContextCurrent( alContext );
2633
2634 // Initialize sources, buffers, music
2635 S_AL_BufferInit( );
2636 S_AL_SrcInit( );
2637
2638 // Set up OpenAL parameters (doppler, etc)
2639 qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
2640 qalDopplerFactor( s_alDopplerFactor->value );
2641 qalSpeedOfSound( s_alDopplerSpeed->value );
2642
2643 #ifdef USE_VOIP
2644 // !!! FIXME: some of these alcCaptureOpenDevice() values should be cvars.
2645 // !!! FIXME: add support for capture device enumeration.
2646 // !!! FIXME: add some better error reporting.
2647 s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
2648 if (!s_alCapture->integer)
2649 {
2650 Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
2651 }
2652 #if USE_MUMBLE
2653 else if (cl_useMumble->integer)
2654 {
2655 Com_Printf("OpenAL capture support disabled for Mumble support\n");
2656 }
2657 #endif
2658 else
2659 {
2660 #ifdef __APPLE__
2661 // !!! FIXME: Apple has a 1.1-compliant OpenAL, which includes
2662 // !!! FIXME: capture support, but they don't list it in the
2663 // !!! FIXME: extension string. We need to check the version string,
2664 // !!! FIXME: then the extension string, but that's too much trouble,
2665 // !!! FIXME: so we'll just check the function pointer for now.
2666 if (qalcCaptureOpenDevice == NULL)
2667 #else
2668 if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
2669 #endif
2670 {
2671 Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
2672 }
2673 else
2674 {
2675 char inputdevicenames[16384] = "";
2676 const char *inputdevicelist;
2677 const char *defaultinputdevice;
2678 int curlen;
2679
2680 capture_ext = qtrue;
2681
2682 // get all available input devices + the default input device name.
2683 inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
2684 defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
2685
2686 // dump a list of available devices to a cvar for the user to see.
2687 if (inputdevicelist)
2688 {
2689 while((curlen = strlen(inputdevicelist)))
2690 {
2691 Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
2692 Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
2693 inputdevicelist += curlen + 1;
2694 }
2695 }
2696
2697 s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
2698
2699 Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
2700 alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
2701 if( !alCaptureDevice && inputdevice )
2702 {
2703 Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
2704 alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
2705 }
2706 Com_Printf( "OpenAL capture device %s.\n",
2707 (alCaptureDevice == NULL) ? "failed to open" : "opened");
2708 }
2709 }
2710 #endif
2711
2712 si->Shutdown = S_AL_Shutdown;
2713 si->StartSound = S_AL_StartSound;
2714 si->StartLocalSound = S_AL_StartLocalSound;
2715 si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
2716 si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
2717 si->RawSamples = S_AL_RawSamples;
2718 si->StopAllSounds = S_AL_StopAllSounds;
2719 si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
2720 si->AddLoopingSound = S_AL_AddLoopingSound;
2721 si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
2722 si->StopLoopingSound = S_AL_StopLoopingSound;
2723 si->Respatialize = S_AL_Respatialize;
2724 si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
2725 si->Update = S_AL_Update;
2726 si->DisableSounds = S_AL_DisableSounds;
2727 si->BeginRegistration = S_AL_BeginRegistration;
2728 si->RegisterSound = S_AL_RegisterSound;
2729 si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
2730 si->SoundInfo = S_AL_SoundInfo;
2731 si->SoundList = S_AL_SoundList;
2732
2733 #ifdef USE_VOIP
2734 si->StartCapture = S_AL_StartCapture;
2735 si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
2736 si->Capture = S_AL_Capture;
2737 si->StopCapture = S_AL_StopCapture;
2738 si->MasterGain = S_AL_MasterGain;
2739 #endif
2740
2741 return qtrue;
2742 #else
2743 return qfalse;
2744 #endif
2745 }
2746