Remove an unnecessary else statement
[openal-soft/android.git] / Alc / ALc.c
blobe0cb3efc7ed7f6faf2df61b7b97869c8df061271
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <math.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <memory.h>
27 #include <ctype.h>
28 #include <signal.h>
30 #include "alMain.h"
31 #include "alSource.h"
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "alThunk.h"
35 #include "alSource.h"
36 #include "alBuffer.h"
37 #include "alAuxEffectSlot.h"
38 #include "alError.h"
39 #include "bs2b.h"
40 #include "alu.h"
43 #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
44 static struct BackendInfo BackendList[] = {
45 #ifdef HAVE_PULSEAUDIO
46 { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs },
47 #endif
48 #ifdef HAVE_ALSA
49 { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs },
50 #endif
51 #ifdef HAVE_COREAUDIO
52 { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs },
53 #endif
54 #ifdef HAVE_OSS
55 { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs },
56 #endif
57 #ifdef HAVE_SOLARIS
58 { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs },
59 #endif
60 #ifdef HAVE_SNDIO
61 { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs },
62 #endif
63 #ifdef HAVE_MMDEVAPI
64 { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs },
65 #endif
66 #ifdef HAVE_DSOUND
67 { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs },
68 #endif
69 #ifdef HAVE_WINMM
70 { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs },
71 #endif
72 #ifdef HAVE_PORTAUDIO
73 { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs },
74 #endif
75 #ifdef HAVE_OPENSL
76 { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs },
77 #endif
79 { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs },
80 #ifdef HAVE_WAVE
81 { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs },
82 #endif
84 { NULL, NULL, NULL, NULL, EmptyFuncs }
86 static struct BackendInfo BackendLoopback = {
87 "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs
89 #undef EmptyFuncs
91 static struct BackendInfo PlaybackBackend;
92 static struct BackendInfo CaptureBackend;
94 ///////////////////////////////////////////////////////
95 // STRING and EXTENSIONS
97 typedef struct ALCfunction {
98 const ALCchar *funcName;
99 ALCvoid *address;
100 } ALCfunction;
102 typedef struct ALCenums {
103 const ALCchar *enumName;
104 ALCenum value;
105 } ALCenums;
108 static const ALCfunction alcFunctions[] = {
109 { "alcCreateContext", (ALCvoid *) alcCreateContext },
110 { "alcMakeContextCurrent", (ALCvoid *) alcMakeContextCurrent },
111 { "alcProcessContext", (ALCvoid *) alcProcessContext },
112 { "alcSuspendContext", (ALCvoid *) alcSuspendContext },
113 { "alcDestroyContext", (ALCvoid *) alcDestroyContext },
114 { "alcGetCurrentContext", (ALCvoid *) alcGetCurrentContext },
115 { "alcGetContextsDevice", (ALCvoid *) alcGetContextsDevice },
116 { "alcOpenDevice", (ALCvoid *) alcOpenDevice },
117 { "alcCloseDevice", (ALCvoid *) alcCloseDevice },
118 { "alcGetError", (ALCvoid *) alcGetError },
119 { "alcIsExtensionPresent", (ALCvoid *) alcIsExtensionPresent },
120 { "alcGetProcAddress", (ALCvoid *) alcGetProcAddress },
121 { "alcGetEnumValue", (ALCvoid *) alcGetEnumValue },
122 { "alcGetString", (ALCvoid *) alcGetString },
123 { "alcGetIntegerv", (ALCvoid *) alcGetIntegerv },
124 { "alcCaptureOpenDevice", (ALCvoid *) alcCaptureOpenDevice },
125 { "alcCaptureCloseDevice", (ALCvoid *) alcCaptureCloseDevice },
126 { "alcCaptureStart", (ALCvoid *) alcCaptureStart },
127 { "alcCaptureStop", (ALCvoid *) alcCaptureStop },
128 { "alcCaptureSamples", (ALCvoid *) alcCaptureSamples },
130 { "alcSetThreadContext", (ALCvoid *) alcSetThreadContext },
131 { "alcGetThreadContext", (ALCvoid *) alcGetThreadContext },
133 { "alcLoopbackOpenDeviceSOFT", (ALCvoid *) alcLoopbackOpenDeviceSOFT},
134 { "alcIsRenderFormatSupportedSOFT",(ALCvoid *) alcIsRenderFormatSupportedSOFT},
135 { "alcRenderSamplesSOFT", (ALCvoid *) alcRenderSamplesSOFT },
137 { "alEnable", (ALCvoid *) alEnable },
138 { "alDisable", (ALCvoid *) alDisable },
139 { "alIsEnabled", (ALCvoid *) alIsEnabled },
140 { "alGetString", (ALCvoid *) alGetString },
141 { "alGetBooleanv", (ALCvoid *) alGetBooleanv },
142 { "alGetIntegerv", (ALCvoid *) alGetIntegerv },
143 { "alGetFloatv", (ALCvoid *) alGetFloatv },
144 { "alGetDoublev", (ALCvoid *) alGetDoublev },
145 { "alGetBoolean", (ALCvoid *) alGetBoolean },
146 { "alGetInteger", (ALCvoid *) alGetInteger },
147 { "alGetFloat", (ALCvoid *) alGetFloat },
148 { "alGetDouble", (ALCvoid *) alGetDouble },
149 { "alGetError", (ALCvoid *) alGetError },
150 { "alIsExtensionPresent", (ALCvoid *) alIsExtensionPresent },
151 { "alGetProcAddress", (ALCvoid *) alGetProcAddress },
152 { "alGetEnumValue", (ALCvoid *) alGetEnumValue },
153 { "alListenerf", (ALCvoid *) alListenerf },
154 { "alListener3f", (ALCvoid *) alListener3f },
155 { "alListenerfv", (ALCvoid *) alListenerfv },
156 { "alListeneri", (ALCvoid *) alListeneri },
157 { "alListener3i", (ALCvoid *) alListener3i },
158 { "alListeneriv", (ALCvoid *) alListeneriv },
159 { "alGetListenerf", (ALCvoid *) alGetListenerf },
160 { "alGetListener3f", (ALCvoid *) alGetListener3f },
161 { "alGetListenerfv", (ALCvoid *) alGetListenerfv },
162 { "alGetListeneri", (ALCvoid *) alGetListeneri },
163 { "alGetListener3i", (ALCvoid *) alGetListener3i },
164 { "alGetListeneriv", (ALCvoid *) alGetListeneriv },
165 { "alGenSources", (ALCvoid *) alGenSources },
166 { "alDeleteSources", (ALCvoid *) alDeleteSources },
167 { "alIsSource", (ALCvoid *) alIsSource },
168 { "alSourcef", (ALCvoid *) alSourcef },
169 { "alSource3f", (ALCvoid *) alSource3f },
170 { "alSourcefv", (ALCvoid *) alSourcefv },
171 { "alSourcei", (ALCvoid *) alSourcei },
172 { "alSource3i", (ALCvoid *) alSource3i },
173 { "alSourceiv", (ALCvoid *) alSourceiv },
174 { "alGetSourcef", (ALCvoid *) alGetSourcef },
175 { "alGetSource3f", (ALCvoid *) alGetSource3f },
176 { "alGetSourcefv", (ALCvoid *) alGetSourcefv },
177 { "alGetSourcei", (ALCvoid *) alGetSourcei },
178 { "alGetSource3i", (ALCvoid *) alGetSource3i },
179 { "alGetSourceiv", (ALCvoid *) alGetSourceiv },
180 { "alSourcePlayv", (ALCvoid *) alSourcePlayv },
181 { "alSourceStopv", (ALCvoid *) alSourceStopv },
182 { "alSourceRewindv", (ALCvoid *) alSourceRewindv },
183 { "alSourcePausev", (ALCvoid *) alSourcePausev },
184 { "alSourcePlay", (ALCvoid *) alSourcePlay },
185 { "alSourceStop", (ALCvoid *) alSourceStop },
186 { "alSourceRewind", (ALCvoid *) alSourceRewind },
187 { "alSourcePause", (ALCvoid *) alSourcePause },
188 { "alSourceQueueBuffers", (ALCvoid *) alSourceQueueBuffers },
189 { "alSourceUnqueueBuffers", (ALCvoid *) alSourceUnqueueBuffers },
190 { "alGenBuffers", (ALCvoid *) alGenBuffers },
191 { "alDeleteBuffers", (ALCvoid *) alDeleteBuffers },
192 { "alIsBuffer", (ALCvoid *) alIsBuffer },
193 { "alBufferData", (ALCvoid *) alBufferData },
194 { "alBufferf", (ALCvoid *) alBufferf },
195 { "alBuffer3f", (ALCvoid *) alBuffer3f },
196 { "alBufferfv", (ALCvoid *) alBufferfv },
197 { "alBufferi", (ALCvoid *) alBufferi },
198 { "alBuffer3i", (ALCvoid *) alBuffer3i },
199 { "alBufferiv", (ALCvoid *) alBufferiv },
200 { "alGetBufferf", (ALCvoid *) alGetBufferf },
201 { "alGetBuffer3f", (ALCvoid *) alGetBuffer3f },
202 { "alGetBufferfv", (ALCvoid *) alGetBufferfv },
203 { "alGetBufferi", (ALCvoid *) alGetBufferi },
204 { "alGetBuffer3i", (ALCvoid *) alGetBuffer3i },
205 { "alGetBufferiv", (ALCvoid *) alGetBufferiv },
206 { "alDopplerFactor", (ALCvoid *) alDopplerFactor },
207 { "alDopplerVelocity", (ALCvoid *) alDopplerVelocity },
208 { "alSpeedOfSound", (ALCvoid *) alSpeedOfSound },
209 { "alDistanceModel", (ALCvoid *) alDistanceModel },
211 { "alGenFilters", (ALCvoid *) alGenFilters },
212 { "alDeleteFilters", (ALCvoid *) alDeleteFilters },
213 { "alIsFilter", (ALCvoid *) alIsFilter },
214 { "alFilteri", (ALCvoid *) alFilteri },
215 { "alFilteriv", (ALCvoid *) alFilteriv },
216 { "alFilterf", (ALCvoid *) alFilterf },
217 { "alFilterfv", (ALCvoid *) alFilterfv },
218 { "alGetFilteri", (ALCvoid *) alGetFilteri },
219 { "alGetFilteriv", (ALCvoid *) alGetFilteriv },
220 { "alGetFilterf", (ALCvoid *) alGetFilterf },
221 { "alGetFilterfv", (ALCvoid *) alGetFilterfv },
222 { "alGenEffects", (ALCvoid *) alGenEffects },
223 { "alDeleteEffects", (ALCvoid *) alDeleteEffects },
224 { "alIsEffect", (ALCvoid *) alIsEffect },
225 { "alEffecti", (ALCvoid *) alEffecti },
226 { "alEffectiv", (ALCvoid *) alEffectiv },
227 { "alEffectf", (ALCvoid *) alEffectf },
228 { "alEffectfv", (ALCvoid *) alEffectfv },
229 { "alGetEffecti", (ALCvoid *) alGetEffecti },
230 { "alGetEffectiv", (ALCvoid *) alGetEffectiv },
231 { "alGetEffectf", (ALCvoid *) alGetEffectf },
232 { "alGetEffectfv", (ALCvoid *) alGetEffectfv },
233 { "alGenAuxiliaryEffectSlots", (ALCvoid *) alGenAuxiliaryEffectSlots},
234 { "alDeleteAuxiliaryEffectSlots",(ALCvoid *) alDeleteAuxiliaryEffectSlots},
235 { "alIsAuxiliaryEffectSlot", (ALCvoid *) alIsAuxiliaryEffectSlot },
236 { "alAuxiliaryEffectSloti", (ALCvoid *) alAuxiliaryEffectSloti },
237 { "alAuxiliaryEffectSlotiv", (ALCvoid *) alAuxiliaryEffectSlotiv },
238 { "alAuxiliaryEffectSlotf", (ALCvoid *) alAuxiliaryEffectSlotf },
239 { "alAuxiliaryEffectSlotfv", (ALCvoid *) alAuxiliaryEffectSlotfv },
240 { "alGetAuxiliaryEffectSloti", (ALCvoid *) alGetAuxiliaryEffectSloti},
241 { "alGetAuxiliaryEffectSlotiv", (ALCvoid *) alGetAuxiliaryEffectSlotiv},
242 { "alGetAuxiliaryEffectSlotf", (ALCvoid *) alGetAuxiliaryEffectSlotf},
243 { "alGetAuxiliaryEffectSlotfv", (ALCvoid *) alGetAuxiliaryEffectSlotfv},
245 { "alBufferSubDataSOFT", (ALCvoid *) alBufferSubDataSOFT },
247 { "alBufferSamplesSOFT", (ALCvoid *) alBufferSamplesSOFT },
248 { "alBufferSubSamplesSOFT", (ALCvoid *) alBufferSubSamplesSOFT },
249 { "alGetBufferSamplesSOFT", (ALCvoid *) alGetBufferSamplesSOFT },
250 { "alIsBufferFormatSupportedSOFT",(ALCvoid *) alIsBufferFormatSupportedSOFT},
252 { "alDeferUpdatesSOFT", (ALCvoid *) alDeferUpdatesSOFT },
253 { "alProcessUpdatesSOFT", (ALCvoid *) alProcessUpdatesSOFT },
255 { NULL, (ALCvoid *) NULL }
258 static const ALCenums enumeration[] = {
259 // Types
260 { "ALC_INVALID", ALC_INVALID },
261 { "ALC_FALSE", ALC_FALSE },
262 { "ALC_TRUE", ALC_TRUE },
264 // ALC Properties
265 { "ALC_MAJOR_VERSION", ALC_MAJOR_VERSION },
266 { "ALC_MINOR_VERSION", ALC_MINOR_VERSION },
267 { "ALC_ATTRIBUTES_SIZE", ALC_ATTRIBUTES_SIZE },
268 { "ALC_ALL_ATTRIBUTES", ALC_ALL_ATTRIBUTES },
269 { "ALC_DEFAULT_DEVICE_SPECIFIER", ALC_DEFAULT_DEVICE_SPECIFIER },
270 { "ALC_DEVICE_SPECIFIER", ALC_DEVICE_SPECIFIER },
271 { "ALC_ALL_DEVICES_SPECIFIER", ALC_ALL_DEVICES_SPECIFIER },
272 { "ALC_DEFAULT_ALL_DEVICES_SPECIFIER", ALC_DEFAULT_ALL_DEVICES_SPECIFIER },
273 { "ALC_EXTENSIONS", ALC_EXTENSIONS },
274 { "ALC_FREQUENCY", ALC_FREQUENCY },
275 { "ALC_REFRESH", ALC_REFRESH },
276 { "ALC_SYNC", ALC_SYNC },
277 { "ALC_MONO_SOURCES", ALC_MONO_SOURCES },
278 { "ALC_STEREO_SOURCES", ALC_STEREO_SOURCES },
279 { "ALC_CAPTURE_DEVICE_SPECIFIER", ALC_CAPTURE_DEVICE_SPECIFIER },
280 { "ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER", ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER},
281 { "ALC_CAPTURE_SAMPLES", ALC_CAPTURE_SAMPLES },
282 { "ALC_CONNECTED", ALC_CONNECTED },
284 // EFX Properties
285 { "ALC_EFX_MAJOR_VERSION", ALC_EFX_MAJOR_VERSION },
286 { "ALC_EFX_MINOR_VERSION", ALC_EFX_MINOR_VERSION },
287 { "ALC_MAX_AUXILIARY_SENDS", ALC_MAX_AUXILIARY_SENDS },
289 // Loopback device Properties
290 { "ALC_FORMAT_CHANNELS_SOFT", ALC_FORMAT_CHANNELS_SOFT },
291 { "ALC_FORMAT_TYPE_SOFT", ALC_FORMAT_TYPE_SOFT },
293 // Buffer Channel Configurations
294 { "ALC_MONO_SOFT", ALC_MONO_SOFT },
295 { "ALC_STEREO_SOFT", ALC_STEREO_SOFT },
296 { "ALC_QUAD_SOFT", ALC_QUAD_SOFT },
297 { "ALC_5POINT1_SOFT", ALC_5POINT1_SOFT },
298 { "ALC_6POINT1_SOFT", ALC_6POINT1_SOFT },
299 { "ALC_7POINT1_SOFT", ALC_7POINT1_SOFT },
301 // Buffer Sample Types
302 { "ALC_BYTE_SOFT", ALC_BYTE_SOFT },
303 { "ALC_UNSIGNED_BYTE_SOFT", ALC_UNSIGNED_BYTE_SOFT },
304 { "ALC_SHORT_SOFT", ALC_SHORT_SOFT },
305 { "ALC_UNSIGNED_SHORT_SOFT", ALC_UNSIGNED_SHORT_SOFT },
306 { "ALC_INT_SOFT", ALC_INT_SOFT },
307 { "ALC_UNSIGNED_INT_SOFT", ALC_UNSIGNED_INT_SOFT },
308 { "ALC_FLOAT_SOFT", ALC_FLOAT_SOFT },
310 // ALC Error Message
311 { "ALC_NO_ERROR", ALC_NO_ERROR },
312 { "ALC_INVALID_DEVICE", ALC_INVALID_DEVICE },
313 { "ALC_INVALID_CONTEXT", ALC_INVALID_CONTEXT },
314 { "ALC_INVALID_ENUM", ALC_INVALID_ENUM },
315 { "ALC_INVALID_VALUE", ALC_INVALID_VALUE },
316 { "ALC_OUT_OF_MEMORY", ALC_OUT_OF_MEMORY },
318 { NULL, (ALCenum)0 }
320 // Error strings
321 static const ALCchar alcNoError[] = "No Error";
322 static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
323 static const ALCchar alcErrInvalidContext[] = "Invalid Context";
324 static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
325 static const ALCchar alcErrInvalidValue[] = "Invalid Value";
326 static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
328 /* Device lists. Sizes only include the first ending null character, not the
329 * second */
330 static ALCchar *alcDeviceList;
331 static size_t alcDeviceListSize;
332 static ALCchar *alcAllDeviceList;
333 static size_t alcAllDeviceListSize;
334 static ALCchar *alcCaptureDeviceList;
335 static size_t alcCaptureDeviceListSize;
336 /* Default is always the first in the list */
337 static ALCchar *alcDefaultDeviceSpecifier;
338 static ALCchar *alcDefaultAllDeviceSpecifier;
339 static ALCchar *alcCaptureDefaultDeviceSpecifier;
342 static const ALCchar alcNoDeviceExtList[] =
343 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
344 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
345 static const ALCchar alcExtensionList[] =
346 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
347 "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
348 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
349 static const ALCint alcMajorVersion = 1;
350 static const ALCint alcMinorVersion = 1;
352 static const ALCint alcEFXMajorVersion = 1;
353 static const ALCint alcEFXMinorVersion = 0;
355 ///////////////////////////////////////////////////////
358 ///////////////////////////////////////////////////////
359 // Global Variables
361 static CRITICAL_SECTION ListLock;
363 /* Device List */
364 static ALCdevice *volatile DeviceList = NULL;
366 // Thread-local current context
367 static pthread_key_t LocalContext;
368 // Process-wide current context
369 static ALCcontext *GlobalContext;
371 /* Device Error */
372 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
374 // Default context extensions
375 static const ALchar alExtList[] =
376 "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 "
377 "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
378 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
379 "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data "
380 "AL_SOFTX_deferred_updates AL_SOFT_loop_points "
381 "AL_SOFTX_non_virtual_channels";
383 // Mixing Priority Level
384 ALint RTPrioLevel;
386 // Output Log File
387 FILE *LogFile;
389 // Output Log Level
390 #ifdef _DEBUG
391 enum LogLevel LogLevel = LogWarning;
392 #else
393 enum LogLevel LogLevel = LogError;
394 #endif
396 /* Flag to trap ALC device errors */
397 static ALCboolean TrapALCError = ALC_FALSE;
399 /* One-time configuration init control */
400 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
402 /* Forced effect that applies to sources that don't have an effect on send 0 */
403 static ALeffect ForcedEffect;
405 ///////////////////////////////////////////////////////
408 ///////////////////////////////////////////////////////
409 // ALC Related helper functions
410 static void ReleaseALC(void);
411 static void ReleaseThreadCtx(void *ptr);
413 static void alc_initconfig(void);
414 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
416 #if defined(_WIN32)
417 static void alc_init(void);
418 static void alc_deinit(void);
419 static void alc_deinit_safe(void);
421 UIntMap TlsDestructor;
423 #ifndef AL_LIBTYPE_STATIC
424 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
426 ALsizei i;
427 (void)hModule;
429 // Perform actions based on the reason for calling.
430 switch(ul_reason_for_call)
432 case DLL_PROCESS_ATTACH:
433 InitUIntMap(&TlsDestructor, ~0);
434 alc_init();
435 break;
437 case DLL_THREAD_DETACH:
438 LockUIntMapRead(&TlsDestructor);
439 for(i = 0;i < TlsDestructor.size;i++)
441 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
442 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
443 if(ptr && callback)
444 callback(ptr);
446 UnlockUIntMapRead(&TlsDestructor);
447 break;
449 case DLL_PROCESS_DETACH:
450 if(!lpReserved)
451 alc_deinit();
452 else
453 alc_deinit_safe();
454 ResetUIntMap(&TlsDestructor);
455 break;
457 return TRUE;
459 #elif defined(_MSC_VER)
460 #pragma section(".CRT$XCU",read)
461 static void alc_constructor(void);
462 static void alc_destructor(void);
463 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
465 static void alc_constructor(void)
467 atexit(alc_destructor);
468 alc_init();
471 static void alc_destructor(void)
473 alc_deinit();
475 #elif defined(HAVE_GCC_DESTRUCTOR)
476 static void alc_init(void) __attribute__((constructor));
477 static void alc_deinit(void) __attribute__((destructor));
478 #else
479 #error "No static initialization available on this platform!"
480 #endif
481 #elif defined(HAVE_GCC_DESTRUCTOR)
482 static void alc_init(void) __attribute__((constructor));
483 static void alc_deinit(void) __attribute__((destructor));
484 #else
485 #error "No global initialization available on this platform!"
486 #endif
488 static void alc_init(void)
490 const char *str;
492 LogFile = stderr;
494 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
495 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
496 ConeScale = 1.0f;
498 str = getenv("__ALSOFT_REVERSE_Z");
499 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
500 ZScale = -1.0f;
502 str = getenv("__ALSOFT_TRAP_ERROR");
503 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
505 TrapALError = AL_TRUE;
506 TrapALCError = AL_TRUE;
508 else
510 str = getenv("__ALSOFT_TRAP_AL_ERROR");
511 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
512 TrapALError = AL_TRUE;
514 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
515 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
516 TrapALCError = ALC_TRUE;
519 pthread_key_create(&LocalContext, ReleaseThreadCtx);
520 InitializeCriticalSection(&ListLock);
521 ThunkInit();
524 static void alc_deinit_safe(void)
526 ReleaseALC();
528 FreeHrtf();
529 FreeALConfig();
531 ThunkExit();
532 DeleteCriticalSection(&ListLock);
533 pthread_key_delete(LocalContext);
535 if(LogFile != stderr)
536 fclose(LogFile);
537 LogFile = NULL;
540 static void alc_deinit(void)
542 int i;
544 ReleaseALC();
546 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
547 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
549 for(i = 0;BackendList[i].Deinit;i++)
550 BackendList[i].Deinit();
551 BackendLoopback.Deinit();
553 alc_deinit_safe();
556 static void alc_initconfig(void)
558 const char *devs, *str;
559 float valf;
560 int i, n;
562 str = getenv("ALSOFT_LOGLEVEL");
563 if(str)
565 long lvl = strtol(str, NULL, 0);
566 if(lvl >= NoLog && lvl <= LogRef)
567 LogLevel = lvl;
570 str = getenv("ALSOFT_LOGFILE");
571 if(str && str[0])
573 FILE *logfile = fopen(str, "wat");
574 if(logfile) LogFile = logfile;
575 else ERR("Failed to open log file '%s'\n", str);
578 ReadALConfig();
580 InitHrtf();
582 #ifdef _WIN32
583 RTPrioLevel = 1;
584 #else
585 RTPrioLevel = 0;
586 #endif
587 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
589 if(ConfigValueStr(NULL, "resampler", &str))
591 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
592 DefaultResampler = POINT_RESAMPLER;
593 else if(strcasecmp(str, "linear") == 0)
594 DefaultResampler = LINEAR_RESAMPLER;
595 else if(strcasecmp(str, "cubic") == 0)
596 DefaultResampler = CUBIC_RESAMPLER;
597 else
599 char *end;
601 n = strtol(str, &end, 0);
602 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
603 DefaultResampler = n;
604 else
605 WARN("Invalid resampler: %s\n", str);
609 if(!TrapALCError)
610 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
612 if(!TrapALError)
613 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
615 if(ConfigValueFloat("reverb", "boost", &valf))
616 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
618 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
620 if(ConfigValueStr(NULL, "drivers", &devs))
622 int n;
623 size_t len;
624 const char *next = devs;
625 int endlist, delitem;
627 i = 0;
628 do {
629 devs = next;
630 next = strchr(devs, ',');
632 delitem = (devs[0] == '-');
633 if(devs[0] == '-') devs++;
635 if(!devs[0] || devs[0] == ',')
637 endlist = 0;
638 continue;
640 endlist = 1;
642 len = (next ? ((size_t)(next-devs)) : strlen(devs));
643 for(n = i;BackendList[n].Init;n++)
645 if(len == strlen(BackendList[n].name) &&
646 strncmp(BackendList[n].name, devs, len) == 0)
648 if(delitem)
650 do {
651 BackendList[n] = BackendList[n+1];
652 ++n;
653 } while(BackendList[n].Init);
655 else
657 struct BackendInfo Bkp = BackendList[n];
658 while(n > i)
660 BackendList[n] = BackendList[n-1];
661 --n;
663 BackendList[n] = Bkp;
665 i++;
667 break;
670 } while(next++);
672 if(endlist)
674 BackendList[i].name = NULL;
675 BackendList[i].Init = NULL;
676 BackendList[i].Deinit = NULL;
677 BackendList[i].Probe = NULL;
681 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
683 if(!BackendList[i].Init(&BackendList[i].Funcs))
685 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
686 continue;
689 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
690 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
692 PlaybackBackend = BackendList[i];
693 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
695 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
697 CaptureBackend = BackendList[i];
698 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
701 BackendLoopback.Init(&BackendLoopback.Funcs);
703 if(ConfigValueStr(NULL, "excludefx", &str))
705 size_t len;
706 const char *next = str;
708 do {
709 str = next;
710 next = strchr(str, ',');
712 if(!str[0] || next == str)
713 continue;
715 len = (next ? ((size_t)(next-str)) : strlen(str));
716 for(n = 0;EffectList[n].name;n++)
718 if(len == strlen(EffectList[n].name) &&
719 strncmp(EffectList[n].name, str, len) == 0)
720 DisabledEffects[EffectList[n].type] = AL_TRUE;
722 } while(next++);
725 str = getenv("__ALSOFT_DEFAULT_REVERB");
726 if(str && str[0])
727 GetReverbEffect(str, &ForcedEffect);
728 else if(ConfigValueStr(NULL, "default-reverb", &str))
729 GetReverbEffect(str, &ForcedEffect);
733 static void LockLists(void)
735 EnterCriticalSection(&ListLock);
738 static void UnlockLists(void)
740 LeaveCriticalSection(&ListLock);
744 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
746 DO_INITCONFIG();
748 LockLists();
749 free(*list);
750 *list = NULL;
751 *listsize = 0;
753 if(type == CAPTURE_DEVICE_PROBE)
754 CaptureBackend.Probe(type);
755 else
756 PlaybackBackend.Probe(type);
757 UnlockLists();
760 static void ProbeDeviceList(void)
761 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
762 static void ProbeAllDeviceList(void)
763 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
764 static void ProbeCaptureDeviceList(void)
765 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
768 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
770 size_t len = strlen(name);
771 void *temp;
773 if(len == 0)
774 return;
776 temp = realloc(*List, (*ListSize) + len + 2);
777 if(!temp)
779 ERR("Realloc failed to add %s!\n", name);
780 return;
782 *List = temp;
784 memcpy((*List)+(*ListSize), name, len+1);
785 *ListSize += len+1;
786 (*List)[*ListSize] = 0;
789 #define DECL_APPEND_LIST_FUNC(type) \
790 void Append##type##List(const ALCchar *name) \
791 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
793 DECL_APPEND_LIST_FUNC(Device)
794 DECL_APPEND_LIST_FUNC(AllDevice)
795 DECL_APPEND_LIST_FUNC(CaptureDevice)
797 #undef DECL_APPEND_LIST_FUNC
800 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
801 void SetDefaultChannelOrder(ALCdevice *device)
803 switch(device->FmtChans)
805 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
806 device->DevChannels[1] = FRONT_RIGHT;
807 device->DevChannels[2] = BACK_LEFT;
808 device->DevChannels[3] = BACK_RIGHT;
809 device->DevChannels[4] = FRONT_CENTER;
810 device->DevChannels[5] = LFE;
811 return;
813 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
814 device->DevChannels[1] = FRONT_RIGHT;
815 device->DevChannels[2] = BACK_LEFT;
816 device->DevChannels[3] = BACK_RIGHT;
817 device->DevChannels[4] = FRONT_CENTER;
818 device->DevChannels[5] = LFE;
819 device->DevChannels[6] = SIDE_LEFT;
820 device->DevChannels[7] = SIDE_RIGHT;
821 return;
823 /* Same as WFX order */
824 case DevFmtMono:
825 case DevFmtStereo:
826 case DevFmtQuad:
827 case DevFmtX51Side:
828 case DevFmtX61:
829 break;
831 SetDefaultWFXChannelOrder(device);
833 /* Sets the default order used by WaveFormatEx */
834 void SetDefaultWFXChannelOrder(ALCdevice *device)
836 switch(device->FmtChans)
838 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
840 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
841 device->DevChannels[1] = FRONT_RIGHT; break;
843 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
844 device->DevChannels[1] = FRONT_RIGHT;
845 device->DevChannels[2] = BACK_LEFT;
846 device->DevChannels[3] = BACK_RIGHT; break;
848 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
849 device->DevChannels[1] = FRONT_RIGHT;
850 device->DevChannels[2] = FRONT_CENTER;
851 device->DevChannels[3] = LFE;
852 device->DevChannels[4] = BACK_LEFT;
853 device->DevChannels[5] = BACK_RIGHT; break;
855 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
856 device->DevChannels[1] = FRONT_RIGHT;
857 device->DevChannels[2] = FRONT_CENTER;
858 device->DevChannels[3] = LFE;
859 device->DevChannels[4] = SIDE_LEFT;
860 device->DevChannels[5] = SIDE_RIGHT; break;
862 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
863 device->DevChannels[1] = FRONT_RIGHT;
864 device->DevChannels[2] = FRONT_CENTER;
865 device->DevChannels[3] = LFE;
866 device->DevChannels[4] = BACK_CENTER;
867 device->DevChannels[5] = SIDE_LEFT;
868 device->DevChannels[6] = SIDE_RIGHT; break;
870 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
871 device->DevChannels[1] = FRONT_RIGHT;
872 device->DevChannels[2] = FRONT_CENTER;
873 device->DevChannels[3] = LFE;
874 device->DevChannels[4] = BACK_LEFT;
875 device->DevChannels[5] = BACK_RIGHT;
876 device->DevChannels[6] = SIDE_LEFT;
877 device->DevChannels[7] = SIDE_RIGHT; break;
882 const ALCchar *DevFmtTypeString(enum DevFmtType type)
884 switch(type)
886 case DevFmtByte: return "Signed Byte";
887 case DevFmtUByte: return "Unsigned Byte";
888 case DevFmtShort: return "Signed Short";
889 case DevFmtUShort: return "Unsigned Short";
890 case DevFmtFloat: return "Float";
892 return "(unknown type)";
894 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
896 switch(chans)
898 case DevFmtMono: return "Mono";
899 case DevFmtStereo: return "Stereo";
900 case DevFmtQuad: return "Quadraphonic";
901 case DevFmtX51: return "5.1 Surround";
902 case DevFmtX51Side: return "5.1 Side";
903 case DevFmtX61: return "6.1 Surround";
904 case DevFmtX71: return "7.1 Surround";
906 return "(unknown channels)";
909 ALuint BytesFromDevFmt(enum DevFmtType type)
911 switch(type)
913 case DevFmtByte: return sizeof(ALbyte);
914 case DevFmtUByte: return sizeof(ALubyte);
915 case DevFmtShort: return sizeof(ALshort);
916 case DevFmtUShort: return sizeof(ALushort);
917 case DevFmtFloat: return sizeof(ALfloat);
919 return 0;
921 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
923 switch(chans)
925 case DevFmtMono: return 1;
926 case DevFmtStereo: return 2;
927 case DevFmtQuad: return 4;
928 case DevFmtX51: return 6;
929 case DevFmtX51Side: return 6;
930 case DevFmtX61: return 7;
931 case DevFmtX71: return 8;
933 return 0;
935 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
936 enum DevFmtType *type)
938 static const struct {
939 ALenum format;
940 enum DevFmtChannels channels;
941 enum DevFmtType type;
942 } list[] = {
943 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
944 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
945 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
947 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
948 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
949 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
951 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
952 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
953 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
955 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
956 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
957 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
959 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
960 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
961 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
963 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
964 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
965 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
967 ALuint i;
969 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
971 if(list[i].format == format)
973 *chans = list[i].channels;
974 *type = list[i].type;
975 return AL_TRUE;
979 return AL_FALSE;
982 static ALCboolean IsValidALCType(ALCenum type)
984 switch(type)
986 case ALC_BYTE_SOFT:
987 case ALC_UNSIGNED_BYTE_SOFT:
988 case ALC_SHORT_SOFT:
989 case ALC_UNSIGNED_SHORT_SOFT:
990 case ALC_INT_SOFT:
991 case ALC_UNSIGNED_INT_SOFT:
992 case ALC_FLOAT_SOFT:
993 return ALC_TRUE;
995 return ALC_FALSE;
998 static ALCboolean IsValidALCChannels(ALCenum channels)
1000 switch(channels)
1002 case ALC_MONO_SOFT:
1003 case ALC_STEREO_SOFT:
1004 case ALC_QUAD_SOFT:
1005 case ALC_5POINT1_SOFT:
1006 case ALC_6POINT1_SOFT:
1007 case ALC_7POINT1_SOFT:
1008 return ALC_TRUE;
1010 return ALC_FALSE;
1014 /* alcSetError
1016 * Stores the latest ALC Error
1018 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1020 if(TrapALCError)
1022 #ifdef _WIN32
1023 /* DebugBreak() will cause an exception if there is no debugger */
1024 if(IsDebuggerPresent())
1025 DebugBreak();
1026 #elif defined(SIGTRAP)
1027 raise(SIGTRAP);
1028 #endif
1031 if(device)
1032 device->LastError = errorCode;
1033 else
1034 g_eLastNullDeviceError = errorCode;
1038 /* UpdateDeviceParams
1040 * Updates device parameters according to the attribute list (caller is
1041 * responsible for holding the list lock).
1043 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1045 ALCcontext *context;
1046 enum DevFmtChannels oldChans;
1047 enum DevFmtType oldType;
1048 ALCuint oldFreq;
1049 int oldMode;
1050 ALuint i;
1052 // Check for attributes
1053 if(attrList && attrList[0])
1055 ALCuint freq, numMono, numStereo, numSends;
1056 enum DevFmtChannels schans;
1057 enum DevFmtType stype;
1058 ALuint attrIdx;
1060 // If a context is already running on the device, stop playback so the
1061 // device attributes can be updated
1062 if((device->Flags&DEVICE_RUNNING))
1063 ALCdevice_StopPlayback(device);
1064 device->Flags &= ~DEVICE_RUNNING;
1066 freq = device->Frequency;
1067 schans = device->FmtChans;
1068 stype = device->FmtType;
1069 numMono = device->NumMonoSources;
1070 numStereo = device->NumStereoSources;
1071 numSends = device->NumAuxSends;
1073 attrIdx = 0;
1074 while(attrList[attrIdx])
1076 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1077 device->IsLoopbackDevice)
1079 ALCint val = attrList[attrIdx + 1];
1080 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1082 alcSetError(device, ALC_INVALID_VALUE);
1083 return ALC_FALSE;
1085 schans = val;
1088 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1089 device->IsLoopbackDevice)
1091 ALCint val = attrList[attrIdx + 1];
1092 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1094 alcSetError(device, ALC_INVALID_VALUE);
1095 return ALC_FALSE;
1097 stype = val;
1100 if(attrList[attrIdx] == ALC_FREQUENCY)
1102 if(device->IsLoopbackDevice)
1104 freq = attrList[attrIdx + 1];
1105 if(freq < 8000)
1107 alcSetError(device, ALC_INVALID_VALUE);
1108 return ALC_FALSE;
1111 else
1113 freq = attrList[attrIdx + 1];
1114 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1118 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1120 numStereo = attrList[attrIdx + 1];
1121 if(numStereo > device->MaxNoOfSources)
1122 numStereo = device->MaxNoOfSources;
1124 numMono = device->MaxNoOfSources - numStereo;
1127 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1128 numSends = attrList[attrIdx + 1];
1130 attrIdx += 2;
1133 if(!device->IsLoopbackDevice)
1135 ConfigValueUInt(NULL, "frequency", &freq);
1136 freq = maxu(freq, 8000);
1138 ConfigValueUInt(NULL, "sends", &numSends);
1139 numSends = minu(MAX_SENDS, numSends);
1141 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1142 device->Frequency;
1144 device->Frequency = freq;
1145 device->FmtChans = schans;
1146 device->FmtType = stype;
1147 device->NumMonoSources = numMono;
1148 device->NumStereoSources = numStereo;
1149 device->NumAuxSends = numSends;
1152 if((device->Flags&DEVICE_RUNNING))
1153 return ALC_TRUE;
1155 LockDevice(device);
1157 oldFreq = device->Frequency;
1158 oldChans = device->FmtChans;
1159 oldType = device->FmtType;
1161 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1162 DevFmtChannelsString(device->FmtChans),
1163 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1164 DevFmtTypeString(device->FmtType), device->Frequency,
1165 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1166 device->UpdateSize, device->NumUpdates);
1167 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1169 UnlockDevice(device);
1170 return ALC_FALSE;
1172 device->Flags |= DEVICE_RUNNING;
1174 if(device->FmtChans != oldChans)
1176 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1177 ERR("Failed to set %s, got %s instead\n",
1178 DevFmtChannelsString(oldChans),
1179 DevFmtChannelsString(device->FmtChans));
1180 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1182 if(device->Frequency != oldFreq)
1184 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1185 ERR("Failed to set %uhz, got %uhz instead\n",
1186 oldFreq, device->Frequency);
1187 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1190 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1191 DevFmtChannelsString(device->FmtChans),
1192 DevFmtTypeString(device->FmtType), device->Frequency,
1193 device->UpdateSize, device->NumUpdates);
1195 aluInitPanning(device);
1197 for(i = 0;i < MAXCHANNELS;i++)
1199 device->ClickRemoval[i] = 0.0f;
1200 device->PendingClicks[i] = 0.0f;
1203 device->Hrtf = NULL;
1204 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1205 device->Hrtf = GetHrtf(device);
1206 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1208 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1210 if(!device->Bs2b)
1212 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1213 bs2b_clear(device->Bs2b);
1215 bs2b_set_srate(device->Bs2b, device->Frequency);
1216 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1217 TRACE("BS2B level %d\n", device->Bs2bLevel);
1219 else
1221 free(device->Bs2b);
1222 device->Bs2b = NULL;
1223 TRACE("BS2B disabled\n");
1226 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1227 switch(device->FmtChans)
1229 case DevFmtMono:
1230 case DevFmtStereo:
1231 break;
1232 case DevFmtQuad:
1233 case DevFmtX51:
1234 case DevFmtX51Side:
1235 case DevFmtX61:
1236 case DevFmtX71:
1237 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1238 device->Flags |= DEVICE_DUPLICATE_STEREO;
1239 break;
1241 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1243 oldMode = SetMixerFPUMode();
1244 context = device->ContextList;
1245 while(context)
1247 ALsizei pos;
1249 context->UpdateSources = AL_FALSE;
1250 LockUIntMapRead(&context->EffectSlotMap);
1251 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1253 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1255 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1257 UnlockUIntMapRead(&context->EffectSlotMap);
1258 RestoreFPUMode(oldMode);
1259 UnlockDevice(device);
1260 ALCdevice_StopPlayback(device);
1261 device->Flags &= ~DEVICE_RUNNING;
1262 return ALC_FALSE;
1264 slot->NeedsUpdate = AL_FALSE;
1265 ALeffectState_Update(slot->EffectState, context, slot);
1267 UnlockUIntMapRead(&context->EffectSlotMap);
1269 LockUIntMapRead(&context->SourceMap);
1270 for(pos = 0;pos < context->SourceMap.size;pos++)
1272 ALsource *source = context->SourceMap.array[pos].value;
1273 ALuint s = device->NumAuxSends;
1274 while(s < MAX_SENDS)
1276 if(source->Send[s].Slot)
1277 DecrementRef(&source->Send[s].Slot->ref);
1278 source->Send[s].Slot = NULL;
1279 source->Send[s].WetGain = 1.0f;
1280 source->Send[s].WetGainHF = 1.0f;
1281 s++;
1283 source->NeedsUpdate = AL_FALSE;
1284 ALsource_Update(source, context);
1286 UnlockUIntMapRead(&context->SourceMap);
1288 context = context->next;
1290 RestoreFPUMode(oldMode);
1291 UnlockDevice(device);
1293 return ALC_TRUE;
1296 /* FreeDevice
1298 * Frees the device structure, and destroys any objects the app failed to
1299 * delete. Called once there's no more references on the device.
1301 static ALCvoid FreeDevice(ALCdevice *device)
1303 TRACE("%p\n", device);
1305 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1306 device->DefaultSlot->EffectState = NULL;
1308 if(device->BufferMap.size > 0)
1310 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1311 ReleaseALBuffers(device);
1313 ResetUIntMap(&device->BufferMap);
1315 if(device->EffectMap.size > 0)
1317 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1318 ReleaseALEffects(device);
1320 ResetUIntMap(&device->EffectMap);
1322 if(device->FilterMap.size > 0)
1324 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1325 ReleaseALFilters(device);
1327 ResetUIntMap(&device->FilterMap);
1329 free(device->Bs2b);
1330 device->Bs2b = NULL;
1332 free(device->szDeviceName);
1333 device->szDeviceName = NULL;
1335 DeleteCriticalSection(&device->Mutex);
1337 free(device);
1341 void ALCdevice_IncRef(ALCdevice *device)
1343 RefCount ref;
1344 ref = IncrementRef(&device->ref);
1345 TRACEREF("%p increasing refcount to %u\n", device, ref);
1348 void ALCdevice_DecRef(ALCdevice *device)
1350 RefCount ref;
1351 ref = DecrementRef(&device->ref);
1352 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1353 if(ref == 0) FreeDevice(device);
1356 /* VerifyDevice
1358 * Checks if the device handle is valid, and increments its ref count if so.
1360 static ALCdevice *VerifyDevice(ALCdevice *device)
1362 ALCdevice *tmpDevice;
1364 if(!device)
1365 return NULL;
1367 LockLists();
1368 tmpDevice = DeviceList;
1369 while(tmpDevice && tmpDevice != device)
1370 tmpDevice = tmpDevice->next;
1372 if(tmpDevice)
1373 ALCdevice_IncRef(tmpDevice);
1374 UnlockLists();
1375 return tmpDevice;
1379 /* InitContext
1381 * Initializes context variables
1383 static ALvoid InitContext(ALCcontext *pContext)
1385 ALint i, j;
1387 //Initialise listener
1388 pContext->Listener.Gain = 1.0f;
1389 pContext->Listener.MetersPerUnit = 1.0f;
1390 pContext->Listener.Position[0] = 0.0f;
1391 pContext->Listener.Position[1] = 0.0f;
1392 pContext->Listener.Position[2] = 0.0f;
1393 pContext->Listener.Velocity[0] = 0.0f;
1394 pContext->Listener.Velocity[1] = 0.0f;
1395 pContext->Listener.Velocity[2] = 0.0f;
1396 pContext->Listener.Forward[0] = 0.0f;
1397 pContext->Listener.Forward[1] = 0.0f;
1398 pContext->Listener.Forward[2] = -1.0f;
1399 pContext->Listener.Up[0] = 0.0f;
1400 pContext->Listener.Up[1] = 1.0f;
1401 pContext->Listener.Up[2] = 0.0f;
1402 for(i = 0;i < 4;i++)
1404 for(j = 0;j < 4;j++)
1405 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1408 //Validate pContext
1409 pContext->LastError = AL_NO_ERROR;
1410 pContext->UpdateSources = AL_FALSE;
1411 pContext->ActiveSourceCount = 0;
1412 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1413 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1415 //Set globals
1416 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1417 pContext->SourceDistanceModel = AL_FALSE;
1418 pContext->DopplerFactor = 1.0f;
1419 pContext->DopplerVelocity = 1.0f;
1420 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1421 pContext->DeferUpdates = AL_FALSE;
1423 pContext->ExtensionList = alExtList;
1427 /* FreeContext
1429 * Cleans up the context, and destroys any remaining objects the app failed to
1430 * delete. Called once there's no more references on the context.
1432 static ALCvoid FreeContext(ALCcontext *context)
1434 TRACE("%p\n", context);
1436 if(context->SourceMap.size > 0)
1438 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1439 ReleaseALSources(context);
1441 ResetUIntMap(&context->SourceMap);
1443 if(context->EffectSlotMap.size > 0)
1445 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1446 ReleaseALAuxiliaryEffectSlots(context);
1448 ResetUIntMap(&context->EffectSlotMap);
1450 context->ActiveSourceCount = 0;
1451 free(context->ActiveSources);
1452 context->ActiveSources = NULL;
1453 context->MaxActiveSources = 0;
1455 context->ActiveEffectSlotCount = 0;
1456 free(context->ActiveEffectSlots);
1457 context->ActiveEffectSlots = NULL;
1458 context->MaxActiveEffectSlots = 0;
1460 ALCdevice_DecRef(context->Device);
1461 context->Device = NULL;
1463 //Invalidate context
1464 memset(context, 0, sizeof(ALCcontext));
1465 free(context);
1468 /* ReleaseContext
1470 * Removes the context reference from the given device and removes it from
1471 * being current on the running thread or globally.
1473 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1475 ALCcontext *volatile*tmp_ctx;
1477 if(pthread_getspecific(LocalContext) == context)
1479 WARN("%p released while current on thread\n", context);
1480 pthread_setspecific(LocalContext, NULL);
1481 ALCcontext_DecRef(context);
1484 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1485 ALCcontext_DecRef(context);
1487 LockDevice(device);
1488 tmp_ctx = &device->ContextList;
1489 while(*tmp_ctx)
1491 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1492 break;
1493 tmp_ctx = &(*tmp_ctx)->next;
1495 UnlockDevice(device);
1497 ALCcontext_DecRef(context);
1500 void ALCcontext_IncRef(ALCcontext *context)
1502 RefCount ref;
1503 ref = IncrementRef(&context->ref);
1504 TRACEREF("%p increasing refcount to %u\n", context, ref);
1507 void ALCcontext_DecRef(ALCcontext *context)
1509 RefCount ref;
1510 ref = DecrementRef(&context->ref);
1511 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1512 if(ref == 0) FreeContext(context);
1515 static void ReleaseThreadCtx(void *ptr)
1517 WARN("%p current for thread being destroyed\n", ptr);
1518 ALCcontext_DecRef(ptr);
1521 /* VerifyContext
1523 * Checks that the given context is valid, and increments its reference count.
1525 static ALCcontext *VerifyContext(ALCcontext *context)
1527 ALCdevice *dev;
1529 LockLists();
1530 dev = DeviceList;
1531 while(dev)
1533 ALCcontext *tmp_ctx = dev->ContextList;
1534 while(tmp_ctx)
1536 if(tmp_ctx == context)
1538 ALCcontext_IncRef(tmp_ctx);
1539 UnlockLists();
1540 return tmp_ctx;
1542 tmp_ctx = tmp_ctx->next;
1544 dev = dev->next;
1546 UnlockLists();
1548 return NULL;
1552 /* GetContextRef
1554 * Returns the currently active context, and adds a reference without locking
1555 * it.
1557 ALCcontext *GetContextRef(void)
1559 ALCcontext *context;
1561 context = pthread_getspecific(LocalContext);
1562 if(context)
1563 ALCcontext_IncRef(context);
1564 else
1566 LockLists();
1567 context = GlobalContext;
1568 if(context)
1569 ALCcontext_IncRef(context);
1570 UnlockLists();
1573 return context;
1576 ///////////////////////////////////////////////////////
1579 ///////////////////////////////////////////////////////
1580 // ALC Functions calls
1583 // This should probably move to another c file but for now ...
1584 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1586 ALCdevice *device = NULL;
1587 ALCenum err;
1589 DO_INITCONFIG();
1591 if(!CaptureBackend.name)
1593 alcSetError(NULL, ALC_INVALID_VALUE);
1594 return NULL;
1597 if(SampleSize <= 0)
1599 alcSetError(NULL, ALC_INVALID_VALUE);
1600 return NULL;
1603 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1604 deviceName = NULL;
1606 device = calloc(1, sizeof(ALCdevice));
1607 if(!device)
1609 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1610 return NULL;
1613 //Validate device
1614 device->Funcs = &CaptureBackend.Funcs;
1615 device->ref = 1;
1616 device->Connected = ALC_TRUE;
1617 device->IsCaptureDevice = AL_TRUE;
1618 device->IsLoopbackDevice = AL_FALSE;
1619 InitializeCriticalSection(&device->Mutex);
1621 InitUIntMap(&device->BufferMap, ~0);
1622 InitUIntMap(&device->EffectMap, ~0);
1623 InitUIntMap(&device->FilterMap, ~0);
1625 device->szDeviceName = NULL;
1627 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1628 device->Frequency = frequency;
1630 device->Flags |= DEVICE_CHANNELS_REQUEST;
1631 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1633 DeleteCriticalSection(&device->Mutex);
1634 free(device);
1635 alcSetError(NULL, ALC_INVALID_ENUM);
1636 return NULL;
1639 device->UpdateSize = SampleSize;
1640 device->NumUpdates = 1;
1642 LockLists();
1643 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1645 UnlockLists();
1646 DeleteCriticalSection(&device->Mutex);
1647 free(device);
1648 alcSetError(NULL, err);
1649 return NULL;
1651 UnlockLists();
1653 do {
1654 device->next = DeviceList;
1655 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1657 TRACE("Created device %p\n", device);
1658 return device;
1661 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1663 ALCdevice *volatile*list;
1665 LockLists();
1666 list = &DeviceList;
1667 while(*list && *list != pDevice)
1668 list = &(*list)->next;
1670 if(!*list || !(*list)->IsCaptureDevice)
1672 alcSetError(*list, ALC_INVALID_DEVICE);
1673 UnlockLists();
1674 return ALC_FALSE;
1677 *list = (*list)->next;
1678 UnlockLists();
1680 LockDevice(pDevice);
1681 ALCdevice_CloseCapture(pDevice);
1682 UnlockDevice(pDevice);
1684 ALCdevice_DecRef(pDevice);
1686 return ALC_TRUE;
1689 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1691 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1693 alcSetError(device, ALC_INVALID_DEVICE);
1694 if(device) ALCdevice_DecRef(device);
1695 return;
1697 LockDevice(device);
1698 if(device->Connected)
1699 ALCdevice_StartCapture(device);
1700 UnlockDevice(device);
1702 ALCdevice_DecRef(device);
1705 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1707 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1709 alcSetError(device, ALC_INVALID_DEVICE);
1710 if(device) ALCdevice_DecRef(device);
1711 return;
1713 LockDevice(device);
1714 if(device->Connected)
1715 ALCdevice_StopCapture(device);
1716 UnlockDevice(device);
1718 ALCdevice_DecRef(device);
1721 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1723 ALCenum err = ALC_INVALID_DEVICE;
1724 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1726 err = ALC_INVALID_VALUE;
1727 LockDevice(device);
1728 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1729 err = ALCdevice_CaptureSamples(device, buffer, samples);
1730 UnlockDevice(device);
1732 if(err != ALC_NO_ERROR)
1733 alcSetError(device, err);
1734 if(device) ALCdevice_DecRef(device);
1738 alcGetError
1740 Return last ALC generated error code
1742 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1744 ALCenum errorCode;
1746 if(VerifyDevice(device))
1748 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1749 ALCdevice_DecRef(device);
1751 else
1752 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1754 return errorCode;
1758 /* alcSuspendContext
1760 * Not functional
1762 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1764 (void)Context;
1767 /* alcProcessContext
1769 * Not functional
1771 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1773 (void)Context;
1777 /* alcGetString
1779 * Returns information about the Device, and error strings
1781 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1783 const ALCchar *value = NULL;
1785 switch(param)
1787 case ALC_NO_ERROR:
1788 value = alcNoError;
1789 break;
1791 case ALC_INVALID_ENUM:
1792 value = alcErrInvalidEnum;
1793 break;
1795 case ALC_INVALID_VALUE:
1796 value = alcErrInvalidValue;
1797 break;
1799 case ALC_INVALID_DEVICE:
1800 value = alcErrInvalidDevice;
1801 break;
1803 case ALC_INVALID_CONTEXT:
1804 value = alcErrInvalidContext;
1805 break;
1807 case ALC_OUT_OF_MEMORY:
1808 value = alcErrOutOfMemory;
1809 break;
1811 case ALC_DEVICE_SPECIFIER:
1812 if(VerifyDevice(pDevice))
1814 value = pDevice->szDeviceName;
1815 ALCdevice_DecRef(pDevice);
1817 else
1819 ProbeDeviceList();
1820 value = alcDeviceList;
1822 break;
1824 case ALC_ALL_DEVICES_SPECIFIER:
1825 ProbeAllDeviceList();
1826 value = alcAllDeviceList;
1827 break;
1829 case ALC_CAPTURE_DEVICE_SPECIFIER:
1830 if(VerifyDevice(pDevice))
1832 value = pDevice->szDeviceName;
1833 ALCdevice_DecRef(pDevice);
1835 else
1837 ProbeCaptureDeviceList();
1838 value = alcCaptureDeviceList;
1840 break;
1842 /* Default devices are always first in the list */
1843 case ALC_DEFAULT_DEVICE_SPECIFIER:
1844 if(!alcDeviceList)
1845 ProbeDeviceList();
1847 pDevice = VerifyDevice(pDevice);
1849 free(alcDefaultDeviceSpecifier);
1850 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1851 if(!alcDefaultDeviceSpecifier)
1852 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1854 value = alcDefaultDeviceSpecifier;
1855 if(pDevice) ALCdevice_DecRef(pDevice);
1856 break;
1858 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1859 if(!alcAllDeviceList)
1860 ProbeAllDeviceList();
1862 pDevice = VerifyDevice(pDevice);
1864 free(alcDefaultAllDeviceSpecifier);
1865 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1866 alcAllDeviceList : "");
1867 if(!alcDefaultAllDeviceSpecifier)
1868 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1870 value = alcDefaultAllDeviceSpecifier;
1871 if(pDevice) ALCdevice_DecRef(pDevice);
1872 break;
1874 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1875 if(!alcCaptureDeviceList)
1876 ProbeCaptureDeviceList();
1878 pDevice = VerifyDevice(pDevice);
1880 free(alcCaptureDefaultDeviceSpecifier);
1881 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1882 alcCaptureDeviceList : "");
1883 if(!alcCaptureDefaultDeviceSpecifier)
1884 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1886 value = alcCaptureDefaultDeviceSpecifier;
1887 if(pDevice) ALCdevice_DecRef(pDevice);
1888 break;
1890 case ALC_EXTENSIONS:
1891 if(!VerifyDevice(pDevice))
1892 value = alcNoDeviceExtList;
1893 else
1895 value = alcExtensionList;
1896 ALCdevice_DecRef(pDevice);
1898 break;
1900 default:
1901 pDevice = VerifyDevice(pDevice);
1902 alcSetError(pDevice, ALC_INVALID_ENUM);
1903 if(pDevice) ALCdevice_DecRef(pDevice);
1904 break;
1907 return value;
1911 /* alcGetIntegerv
1913 * Returns information about the Device and the version of Open AL
1915 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1917 device = VerifyDevice(device);
1919 if(size == 0 || data == NULL)
1921 alcSetError(device, ALC_INVALID_VALUE);
1922 if(device) ALCdevice_DecRef(device);
1923 return;
1926 if(!device)
1928 switch(param)
1930 case ALC_MAJOR_VERSION:
1931 *data = alcMajorVersion;
1932 break;
1933 case ALC_MINOR_VERSION:
1934 *data = alcMinorVersion;
1935 break;
1937 case ALC_ATTRIBUTES_SIZE:
1938 case ALC_ALL_ATTRIBUTES:
1939 case ALC_FREQUENCY:
1940 case ALC_REFRESH:
1941 case ALC_SYNC:
1942 case ALC_MONO_SOURCES:
1943 case ALC_STEREO_SOURCES:
1944 case ALC_CAPTURE_SAMPLES:
1945 case ALC_FORMAT_CHANNELS_SOFT:
1946 case ALC_FORMAT_TYPE_SOFT:
1947 alcSetError(NULL, ALC_INVALID_DEVICE);
1948 break;
1950 default:
1951 alcSetError(NULL, ALC_INVALID_ENUM);
1952 break;
1955 else if(device->IsCaptureDevice)
1957 switch(param)
1959 case ALC_CAPTURE_SAMPLES:
1960 LockDevice(device);
1961 *data = ALCdevice_AvailableSamples(device);
1962 UnlockDevice(device);
1963 break;
1965 case ALC_CONNECTED:
1966 *data = device->Connected;
1967 break;
1969 default:
1970 alcSetError(device, ALC_INVALID_ENUM);
1971 break;
1974 else /* render device */
1976 switch(param)
1978 case ALC_MAJOR_VERSION:
1979 *data = alcMajorVersion;
1980 break;
1982 case ALC_MINOR_VERSION:
1983 *data = alcMinorVersion;
1984 break;
1986 case ALC_EFX_MAJOR_VERSION:
1987 *data = alcEFXMajorVersion;
1988 break;
1990 case ALC_EFX_MINOR_VERSION:
1991 *data = alcEFXMinorVersion;
1992 break;
1994 case ALC_ATTRIBUTES_SIZE:
1995 *data = 13;
1996 break;
1998 case ALC_ALL_ATTRIBUTES:
1999 if(size < 13)
2000 alcSetError(device, ALC_INVALID_VALUE);
2001 else
2003 int i = 0;
2005 data[i++] = ALC_FREQUENCY;
2006 data[i++] = device->Frequency;
2008 if(!device->IsLoopbackDevice)
2010 data[i++] = ALC_REFRESH;
2011 data[i++] = device->Frequency / device->UpdateSize;
2013 data[i++] = ALC_SYNC;
2014 data[i++] = ALC_FALSE;
2016 else
2018 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2019 data[i++] = device->FmtChans;
2021 data[i++] = ALC_FORMAT_TYPE_SOFT;
2022 data[i++] = device->FmtType;
2025 data[i++] = ALC_MONO_SOURCES;
2026 data[i++] = device->NumMonoSources;
2028 data[i++] = ALC_STEREO_SOURCES;
2029 data[i++] = device->NumStereoSources;
2031 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2032 data[i++] = device->NumAuxSends;
2034 data[i++] = 0;
2036 break;
2038 case ALC_FREQUENCY:
2039 *data = device->Frequency;
2040 break;
2042 case ALC_REFRESH:
2043 if(device->IsLoopbackDevice)
2044 alcSetError(device, ALC_INVALID_DEVICE);
2045 else
2046 *data = device->Frequency / device->UpdateSize;
2047 break;
2049 case ALC_SYNC:
2050 if(device->IsLoopbackDevice)
2051 alcSetError(device, ALC_INVALID_DEVICE);
2052 else
2053 *data = ALC_FALSE;
2054 break;
2056 case ALC_FORMAT_CHANNELS_SOFT:
2057 if(!device->IsLoopbackDevice)
2058 alcSetError(device, ALC_INVALID_DEVICE);
2059 else
2060 *data = device->FmtChans;
2061 break;
2063 case ALC_FORMAT_TYPE_SOFT:
2064 if(!device->IsLoopbackDevice)
2065 alcSetError(device, ALC_INVALID_DEVICE);
2066 else
2067 *data = device->FmtType;
2068 break;
2070 case ALC_MONO_SOURCES:
2071 *data = device->NumMonoSources;
2072 break;
2074 case ALC_STEREO_SOURCES:
2075 *data = device->NumStereoSources;
2076 break;
2078 case ALC_MAX_AUXILIARY_SENDS:
2079 *data = device->NumAuxSends;
2080 break;
2082 case ALC_CONNECTED:
2083 *data = device->Connected;
2084 break;
2086 default:
2087 alcSetError(device, ALC_INVALID_ENUM);
2088 break;
2091 if(device)
2092 ALCdevice_DecRef(device);
2096 /* alcIsExtensionPresent
2098 * Determines if there is support for a particular extension
2100 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2102 ALCboolean bResult = ALC_FALSE;
2104 device = VerifyDevice(device);
2106 if(!extName)
2107 alcSetError(device, ALC_INVALID_VALUE);
2108 else
2110 size_t len = strlen(extName);
2111 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2112 while(ptr && *ptr)
2114 if(strncasecmp(ptr, extName, len) == 0 &&
2115 (ptr[len] == '\0' || isspace(ptr[len])))
2117 bResult = ALC_TRUE;
2118 break;
2120 if((ptr=strchr(ptr, ' ')) != NULL)
2122 do {
2123 ++ptr;
2124 } while(isspace(*ptr));
2128 if(device)
2129 ALCdevice_DecRef(device);
2130 return bResult;
2134 /* alcGetProcAddress
2136 * Retrieves the function address for a particular extension function
2138 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2140 ALCvoid *ptr = NULL;
2142 device = VerifyDevice(device);
2144 if(!funcName)
2145 alcSetError(device, ALC_INVALID_VALUE);
2146 else
2148 ALsizei i = 0;
2149 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2150 i++;
2151 ptr = alcFunctions[i].address;
2153 if(device)
2154 ALCdevice_DecRef(device);
2155 return ptr;
2159 /* alcGetEnumValue
2161 * Get the value for a particular ALC Enumerated Value
2163 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2165 ALCenum val = 0;
2167 device = VerifyDevice(device);
2169 if(!enumName)
2170 alcSetError(device, ALC_INVALID_VALUE);
2171 else
2173 ALsizei i = 0;
2174 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2175 i++;
2176 val = enumeration[i].value;
2178 if(device)
2179 ALCdevice_DecRef(device);
2180 return val;
2184 /* alcCreateContext
2186 * Create and attach a Context to a particular Device.
2188 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2190 ALCcontext *ALContext;
2192 LockLists();
2193 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2195 UnlockLists();
2196 alcSetError(device, ALC_INVALID_DEVICE);
2197 if(device) ALCdevice_DecRef(device);
2198 return NULL;
2201 /* Reset Context Last Error code */
2202 device->LastError = ALC_NO_ERROR;
2204 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2206 UnlockLists();
2207 alcSetError(device, ALC_INVALID_DEVICE);
2208 aluHandleDisconnect(device);
2209 ALCdevice_DecRef(device);
2210 return NULL;
2213 ALContext = calloc(1, sizeof(ALCcontext));
2214 if(ALContext)
2216 ALContext->ref = 1;
2218 ALContext->MaxActiveSources = 256;
2219 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2220 ALContext->MaxActiveSources);
2222 if(!ALContext || !ALContext->ActiveSources)
2224 if(!device->ContextList)
2226 ALCdevice_StopPlayback(device);
2227 device->Flags &= ~DEVICE_RUNNING;
2229 UnlockLists();
2231 free(ALContext);
2232 ALContext = NULL;
2234 alcSetError(device, ALC_OUT_OF_MEMORY);
2235 ALCdevice_DecRef(device);
2236 return NULL;
2239 ALContext->Device = device;
2240 ALCdevice_IncRef(device);
2241 InitContext(ALContext);
2243 do {
2244 ALContext->next = device->ContextList;
2245 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2246 UnlockLists();
2248 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2250 ALCdevice_DecRef(device);
2252 TRACE("Created context %p\n", ALContext);
2253 return ALContext;
2256 /* alcDestroyContext
2258 * Remove a Context
2260 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2262 ALCdevice *Device;
2264 LockLists();
2265 /* alcGetContextsDevice sets an error for invalid contexts */
2266 Device = alcGetContextsDevice(context);
2267 if(Device)
2269 ReleaseContext(context, Device);
2270 if(!Device->ContextList)
2272 ALCdevice_StopPlayback(Device);
2273 Device->Flags &= ~DEVICE_RUNNING;
2276 UnlockLists();
2280 /* alcGetCurrentContext
2282 * Returns the currently active Context
2284 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2286 ALCcontext *Context;
2288 Context = pthread_getspecific(LocalContext);
2289 if(!Context) Context = GlobalContext;
2291 return Context;
2294 /* alcGetThreadContext
2296 * Returns the currently active thread-local Context
2298 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2300 ALCcontext *Context;
2301 Context = pthread_getspecific(LocalContext);
2302 return Context;
2306 /* alcMakeContextCurrent
2308 * Makes the given Context the active Context
2310 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2312 /* context must be a valid Context or NULL */
2313 if(context && !(context=VerifyContext(context)))
2315 alcSetError(NULL, ALC_INVALID_CONTEXT);
2316 return ALC_FALSE;
2318 /* context's reference count is already incremented */
2319 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2320 if(context) ALCcontext_DecRef(context);
2322 if((context=pthread_getspecific(LocalContext)) != NULL)
2324 pthread_setspecific(LocalContext, NULL);
2325 ALCcontext_DecRef(context);
2328 return ALC_TRUE;
2331 /* alcSetThreadContext
2333 * Makes the given Context the active Context for the current thread
2335 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2337 ALCcontext *old;
2339 /* context must be a valid Context or NULL */
2340 if(context && !(context=VerifyContext(context)))
2342 alcSetError(NULL, ALC_INVALID_CONTEXT);
2343 return ALC_FALSE;
2345 /* context's reference count is already incremented */
2346 old = pthread_getspecific(LocalContext);
2347 pthread_setspecific(LocalContext, context);
2348 if(old) ALCcontext_DecRef(old);
2350 return ALC_TRUE;
2354 /* alcGetContextsDevice
2356 * Returns the Device that a particular Context is attached to
2358 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2360 ALCdevice *Device;
2362 if(!(Context=VerifyContext(Context)))
2364 alcSetError(NULL, ALC_INVALID_CONTEXT);
2365 return NULL;
2367 Device = Context->Device;
2368 ALCcontext_DecRef(Context);
2370 return Device;
2374 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2376 static const struct {
2377 const char name[32];
2378 enum DevFmtChannels channels;
2379 enum DevFmtType type;
2380 } formats[] = {
2381 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2382 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2383 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2384 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2385 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2386 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2388 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2389 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2390 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2391 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2392 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2393 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2395 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2396 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2397 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2398 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2399 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2400 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2402 size_t i;
2404 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2406 if(strcasecmp(str, formats[i].name) == 0)
2408 *chans = formats[i].channels;
2409 *type = formats[i].type;
2410 return;
2414 ERR("Unknown format: \"%s\"\n", str);
2415 *chans = DevFmtStereo;
2416 *type = DevFmtShort;
2419 /* alcOpenDevice
2421 * Open the Device specified.
2423 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2425 const ALCchar *fmt;
2426 ALCdevice *device;
2427 ALCenum err;
2428 ALCint i;
2430 DO_INITCONFIG();
2432 if(!PlaybackBackend.name)
2434 alcSetError(NULL, ALC_INVALID_VALUE);
2435 return NULL;
2438 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2439 deviceName = NULL;
2441 device = calloc(1, sizeof(ALCdevice)+sizeof(ALeffectslot));
2442 if(!device)
2444 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2445 return NULL;
2448 //Validate device
2449 device->Funcs = &PlaybackBackend.Funcs;
2450 device->ref = 1;
2451 device->Connected = ALC_TRUE;
2452 device->IsCaptureDevice = AL_FALSE;
2453 device->IsLoopbackDevice = AL_FALSE;
2454 InitializeCriticalSection(&device->Mutex);
2455 device->LastError = ALC_NO_ERROR;
2457 device->Flags = 0;
2458 device->Bs2b = NULL;
2459 device->Bs2bLevel = 0;
2460 device->szDeviceName = NULL;
2462 device->ContextList = NULL;
2464 device->MaxNoOfSources = 256;
2465 device->AuxiliaryEffectSlotMax = 4;
2466 device->NumAuxSends = MAX_SENDS;
2468 InitUIntMap(&device->BufferMap, ~0);
2469 InitUIntMap(&device->EffectMap, ~0);
2470 InitUIntMap(&device->FilterMap, ~0);
2472 //Set output format
2473 device->NumUpdates = 4;
2474 device->UpdateSize = 1024;
2476 device->Frequency = DEFAULT_OUTPUT_RATE;
2477 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2478 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2479 device->Frequency = maxu(device->Frequency, 8000);
2481 fmt = "AL_FORMAT_STEREO32";
2482 if(ConfigValueStr(NULL, "format", &fmt))
2483 device->Flags |= DEVICE_CHANNELS_REQUEST;
2484 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2486 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2487 if(device->NumUpdates < 2) device->NumUpdates = 4;
2489 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2490 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2492 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2493 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2495 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2496 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2498 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2499 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2501 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2503 device->NumStereoSources = 1;
2504 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2506 device->DefaultSlot = (ALeffectslot*)(device+1);
2507 device->DefaultSlot->EffectState = NoneCreate();
2508 device->DefaultSlot->Gain = 1.0;
2509 device->DefaultSlot->AuxSendAuto = AL_TRUE;
2510 device->DefaultSlot->NeedsUpdate = AL_FALSE;
2511 for(i = 0;i < BUFFERSIZE;i++)
2512 device->DefaultSlot->WetBuffer[i] = 0.0f;
2513 for(i = 0;i < 1;i++)
2515 device->DefaultSlot->ClickRemoval[i] = 0.0f;
2516 device->DefaultSlot->PendingClicks[i] = 0.0f;
2518 device->DefaultSlot->ref = 0;
2520 // Find a playback device to open
2521 LockLists();
2522 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2524 UnlockLists();
2525 DeleteCriticalSection(&device->Mutex);
2526 free(device);
2527 alcSetError(NULL, err);
2528 return NULL;
2530 UnlockLists();
2532 do {
2533 device->next = DeviceList;
2534 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2536 TRACE("Created device %p\n", device);
2537 return device;
2540 /* alcCloseDevice
2542 * Close the specified Device
2544 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2546 ALCdevice *volatile*list;
2547 ALCcontext *ctx;
2549 LockLists();
2550 list = &DeviceList;
2551 while(*list && *list != pDevice)
2552 list = &(*list)->next;
2554 if(!*list || (*list)->IsCaptureDevice)
2556 alcSetError(*list, ALC_INVALID_DEVICE);
2557 UnlockLists();
2558 return ALC_FALSE;
2561 *list = (*list)->next;
2562 UnlockLists();
2564 if((ctx=pDevice->ContextList) != NULL)
2566 do {
2567 WARN("Releasing context %p\n", ctx);
2568 ReleaseContext(ctx, pDevice);
2569 } while((ctx=pDevice->ContextList) != NULL);
2570 ALCdevice_StopPlayback(pDevice);
2571 pDevice->Flags &= ~DEVICE_RUNNING;
2573 ALCdevice_ClosePlayback(pDevice);
2575 ALCdevice_DecRef(pDevice);
2577 return ALC_TRUE;
2581 /* alcLoopbackOpenDeviceSOFT
2583 * Open a loopback device, for manual rendering.
2585 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2587 ALCdevice *device;
2589 DO_INITCONFIG();
2591 device = calloc(1, sizeof(ALCdevice));
2592 if(!device)
2594 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2595 return NULL;
2598 //Validate device
2599 device->Funcs = &BackendLoopback.Funcs;
2600 device->ref = 1;
2601 device->Connected = ALC_TRUE;
2602 device->IsCaptureDevice = AL_FALSE;
2603 device->IsLoopbackDevice = AL_TRUE;
2604 InitializeCriticalSection(&device->Mutex);
2605 device->LastError = ALC_NO_ERROR;
2607 device->Flags = 0;
2608 device->Bs2b = NULL;
2609 device->Bs2bLevel = 0;
2610 device->szDeviceName = NULL;
2612 device->ContextList = NULL;
2614 device->MaxNoOfSources = 256;
2615 device->AuxiliaryEffectSlotMax = 4;
2616 device->NumAuxSends = MAX_SENDS;
2618 InitUIntMap(&device->BufferMap, ~0);
2619 InitUIntMap(&device->EffectMap, ~0);
2620 InitUIntMap(&device->FilterMap, ~0);
2622 //Set output format
2623 device->NumUpdates = 0;
2624 device->UpdateSize = 0;
2626 device->Frequency = 44100;
2627 device->FmtChans = DevFmtStereo;
2628 device->FmtType = DevFmtShort;
2630 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2631 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2633 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2634 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2636 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2637 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2639 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2641 device->NumStereoSources = 1;
2642 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2644 // Open the "backend"
2645 ALCdevice_OpenPlayback(device, "Loopback");
2646 do {
2647 device->next = DeviceList;
2648 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2650 TRACE("Created device %p\n", device);
2651 return device;
2654 /* alcIsRenderFormatSupportedSOFT
2656 * Determines if the loopback device supports the given format for rendering.
2658 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2660 ALCboolean ret = ALC_FALSE;
2662 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2663 alcSetError(device, ALC_INVALID_DEVICE);
2664 else if(freq <= 0)
2665 alcSetError(device, ALC_INVALID_VALUE);
2666 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2667 alcSetError(device, ALC_INVALID_ENUM);
2668 else
2670 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2671 freq >= 8000)
2672 ret = ALC_TRUE;
2674 if(device) ALCdevice_DecRef(device);
2676 return ret;
2679 /* alcRenderSamplesSOFT
2681 * Renders some samples into a buffer, using the format last set by the
2682 * attributes given to alcCreateContext.
2684 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2686 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2687 alcSetError(device, ALC_INVALID_DEVICE);
2688 else if(samples < 0 || (samples > 0 && buffer == NULL))
2689 alcSetError(device, ALC_INVALID_VALUE);
2690 else
2691 aluMixData(device, buffer, samples);
2692 if(device) ALCdevice_DecRef(device);
2696 static void ReleaseALC(void)
2698 ALCdevice *dev;
2700 free(alcDeviceList); alcDeviceList = NULL;
2701 alcDeviceListSize = 0;
2702 free(alcAllDeviceList); alcAllDeviceList = NULL;
2703 alcAllDeviceListSize = 0;
2704 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2705 alcCaptureDeviceListSize = 0;
2707 free(alcDefaultDeviceSpecifier);
2708 alcDefaultDeviceSpecifier = NULL;
2709 free(alcDefaultAllDeviceSpecifier);
2710 alcDefaultAllDeviceSpecifier = NULL;
2711 free(alcCaptureDefaultDeviceSpecifier);
2712 alcCaptureDefaultDeviceSpecifier = NULL;
2714 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2716 ALCuint num = 0;
2717 do {
2718 num++;
2719 } while((dev=dev->next) != NULL);
2720 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2724 ///////////////////////////////////////////////////////