Don't increment the context reference count when locked
[openal-soft/android.git] / Alc / ALc.c
blobcbbacaa208b3e24fe882a49b334b6e391087398b
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", ALC_MONO },
295 { "ALC_STEREO", ALC_STEREO },
296 { "ALC_QUAD", ALC_QUAD },
297 { "ALC_5POINT1", ALC_5POINT1 },
298 { "ALC_6POINT1", ALC_6POINT1 },
299 { "ALC_7POINT1", ALC_7POINT1 },
301 // Buffer Sample Types
302 { "ALC_BYTE", ALC_BYTE },
303 { "ALC_UNSIGNED_BYTE", ALC_UNSIGNED_BYTE },
304 { "ALC_SHORT", ALC_SHORT },
305 { "ALC_UNSIGNED_SHORT", ALC_UNSIGNED_SHORT },
306 { "ALC_INT", ALC_INT },
307 { "ALC_UNSIGNED_INT", ALC_UNSIGNED_INT },
308 { "ALC_FLOAT", ALC_FLOAT },
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 *g_pDeviceList = NULL;
365 static ALCuint g_ulDeviceCount = 0;
367 // Thread-local current context
368 static pthread_key_t LocalContext;
369 // Process-wide current context
370 static ALCcontext *GlobalContext;
372 /* Device Error */
373 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
375 // Default context extensions
376 static const ALchar alExtList[] =
377 "AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 AL_EXT_IMA4 "
378 "AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
379 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
380 "AL_LOKI_quadriphonic AL_SOFTX_buffer_samples AL_SOFT_buffer_sub_data "
381 "AL_SOFTX_deferred_updates AL_SOFT_loop_points "
382 "AL_SOFTX_non_virtual_channels";
384 // Mixing Priority Level
385 ALint RTPrioLevel;
387 // Output Log File
388 FILE *LogFile;
390 // Output Log Level
391 #ifdef _DEBUG
392 enum LogLevel LogLevel = LogWarning;
393 #else
394 enum LogLevel LogLevel = LogError;
395 #endif
397 // Cone scalar
398 ALdouble ConeScale = 0.5;
400 // Localized Z scalar for mono sources
401 ALdouble ZScale = 1.0;
403 /* Flag to trap ALC device errors */
404 static ALCboolean TrapALCError = ALC_FALSE;
406 /* One-time configuration init control */
407 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
409 ///////////////////////////////////////////////////////
412 ///////////////////////////////////////////////////////
413 // ALC Related helper functions
414 static void ReleaseALC(ALCboolean doclose);
415 static void ReleaseThreadCtx(void *ptr);
417 static void alc_initconfig(void);
418 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
420 #if defined(_WIN32)
421 static void alc_init(void);
422 static void alc_deinit(void);
423 static void alc_deinit_safe(void);
425 #ifndef AL_LIBTYPE_STATIC
426 UIntMap TlsDestructor;
428 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
430 ALsizei i;
431 (void)hModule;
433 // Perform actions based on the reason for calling.
434 switch(ul_reason_for_call)
436 case DLL_PROCESS_ATTACH:
437 InitUIntMap(&TlsDestructor, ~0);
438 alc_init();
439 break;
441 case DLL_THREAD_DETACH:
442 LockUIntMapRead(&TlsDestructor);
443 for(i = 0;i < TlsDestructor.size;i++)
445 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
446 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
447 if(ptr && callback)
448 callback(ptr);
450 UnlockUIntMapRead(&TlsDestructor);
451 break;
453 case DLL_PROCESS_DETACH:
454 if(!lpReserved)
455 alc_deinit();
456 else
457 alc_deinit_safe();
458 ResetUIntMap(&TlsDestructor);
459 break;
461 return TRUE;
463 #elif defined(_MSC_VER)
464 #pragma section(".CRT$XCU",read)
465 static void alc_constructor(void);
466 static void alc_destructor(void);
467 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
469 static void alc_constructor(void)
471 atexit(alc_destructor);
472 alc_init();
475 static void alc_destructor(void)
477 alc_deinit();
479 #elif defined(HAVE_GCC_DESTRUCTOR)
480 static void alc_init(void) __attribute__((constructor));
481 static void alc_deinit(void) __attribute__((destructor));
482 #else
483 #error "No static initialization available on this platform!"
484 #endif
485 #elif defined(HAVE_GCC_DESTRUCTOR)
486 static void alc_init(void) __attribute__((constructor));
487 static void alc_deinit(void) __attribute__((destructor));
488 #else
489 #error "No global initialization available on this platform!"
490 #endif
492 static void alc_init(void)
494 const char *str;
496 LogFile = stderr;
498 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
499 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
500 ConeScale = 1.0;
502 str = getenv("__ALSOFT_REVERSE_Z");
503 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
504 ZScale = -1.0;
506 str = getenv("__ALSOFT_TRAP_AL_ERROR");
507 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
508 TrapALError = AL_TRUE;
510 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
511 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
512 TrapALCError = ALC_TRUE;
514 pthread_key_create(&LocalContext, ReleaseThreadCtx);
515 InitializeCriticalSection(&ListLock);
516 ThunkInit();
519 static void alc_deinit_safe(void)
521 ReleaseALC(ALC_FALSE);
523 FreeALConfig();
525 ThunkExit();
526 DeleteCriticalSection(&ListLock);
527 pthread_key_delete(LocalContext);
529 if(LogFile != stderr)
530 fclose(LogFile);
531 LogFile = NULL;
534 static void alc_deinit(void)
536 int i;
538 ReleaseALC(ALC_TRUE);
540 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
541 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
543 for(i = 0;BackendList[i].Deinit;i++)
544 BackendList[i].Deinit();
545 BackendLoopback.Deinit();
547 alc_deinit_safe();
550 static void alc_initconfig(void)
552 const char *devs, *str;
553 int i, n;
555 str = getenv("ALSOFT_LOGLEVEL");
556 if(str)
558 long lvl = strtol(str, NULL, 0);
559 if(lvl >= NoLog && lvl <= LogTrace)
560 LogLevel = lvl;
563 str = getenv("ALSOFT_LOGFILE");
564 if(str && str[0])
566 FILE *logfile = fopen(str, "wat");
567 if(logfile) LogFile = logfile;
568 else ERR("Failed to open log file '%s'\n", str);
571 ReadALConfig();
573 InitHrtf();
575 #ifdef _WIN32
576 RTPrioLevel = GetConfigValueInt(NULL, "rt-prio", 1);
577 #else
578 RTPrioLevel = GetConfigValueInt(NULL, "rt-prio", 0);
579 #endif
581 DefaultResampler = GetConfigValueInt(NULL, "resampler", RESAMPLER_DEFAULT);
582 if(DefaultResampler >= RESAMPLER_MAX || DefaultResampler <= RESAMPLER_MIN)
583 DefaultResampler = RESAMPLER_DEFAULT;
585 if(!TrapALCError)
586 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
588 if(!TrapALError)
589 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
591 ReverbBoost *= aluPow(10.0f, GetConfigValueFloat("reverb", "boost", 0.0f) /
592 20.0f);
593 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
595 devs = GetConfigValue(NULL, "drivers", "");
596 if(devs[0])
598 int n;
599 size_t len;
600 const char *next = devs;
601 int endlist, delitem;
603 i = 0;
604 do {
605 devs = next;
606 next = strchr(devs, ',');
608 delitem = (devs[0] == '-');
609 if(devs[0] == '-') devs++;
611 if(!devs[0] || devs[0] == ',')
613 endlist = 0;
614 continue;
616 endlist = 1;
618 len = (next ? ((size_t)(next-devs)) : strlen(devs));
619 for(n = i;BackendList[n].Init;n++)
621 if(len == strlen(BackendList[n].name) &&
622 strncmp(BackendList[n].name, devs, len) == 0)
624 if(delitem)
626 do {
627 BackendList[n] = BackendList[n+1];
628 ++n;
629 } while(BackendList[n].Init);
631 else
633 struct BackendInfo Bkp = BackendList[n];
634 while(n > i)
636 BackendList[n] = BackendList[n-1];
637 --n;
639 BackendList[n] = Bkp;
641 i++;
643 break;
646 } while(next++);
648 if(endlist)
650 BackendList[i].name = NULL;
651 BackendList[i].Init = NULL;
652 BackendList[i].Deinit = NULL;
653 BackendList[i].Probe = NULL;
657 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
659 if(!BackendList[i].Init(&BackendList[i].Funcs))
661 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
662 continue;
665 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
666 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
668 PlaybackBackend = BackendList[i];
669 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
671 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
673 CaptureBackend = BackendList[i];
674 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
677 BackendLoopback.Init(&BackendLoopback.Funcs);
679 str = GetConfigValue(NULL, "excludefx", "");
680 if(str[0])
682 size_t len;
683 const char *next = str;
685 do {
686 str = next;
687 next = strchr(str, ',');
689 if(!str[0] || next == str)
690 continue;
692 len = (next ? ((size_t)(next-str)) : strlen(str));
693 for(n = 0;EffectList[n].name;n++)
695 if(len == strlen(EffectList[n].name) &&
696 strncmp(EffectList[n].name, str, len) == 0)
697 DisabledEffects[EffectList[n].type] = AL_TRUE;
699 } while(next++);
704 static void LockLists(void)
706 EnterCriticalSection(&ListLock);
709 static void UnlockLists(void)
711 LeaveCriticalSection(&ListLock);
715 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
717 DO_INITCONFIG();
719 LockLists();
720 free(*list);
721 *list = NULL;
722 *listsize = 0;
724 if(type == CAPTURE_DEVICE_PROBE)
725 CaptureBackend.Probe(type);
726 else
727 PlaybackBackend.Probe(type);
728 UnlockLists();
731 static void ProbeDeviceList(void)
732 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
733 static void ProbeAllDeviceList(void)
734 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
735 static void ProbeCaptureDeviceList(void)
736 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
739 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
741 size_t len = strlen(name);
742 void *temp;
744 if(len == 0)
745 return;
747 temp = realloc(*List, (*ListSize) + len + 2);
748 if(!temp)
750 ERR("Realloc failed to add %s!\n", name);
751 return;
753 *List = temp;
755 memcpy((*List)+(*ListSize), name, len+1);
756 *ListSize += len+1;
757 (*List)[*ListSize] = 0;
760 #define DECL_APPEND_LIST_FUNC(type) \
761 void Append##type##List(const ALCchar *name) \
762 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
764 DECL_APPEND_LIST_FUNC(Device)
765 DECL_APPEND_LIST_FUNC(AllDevice)
766 DECL_APPEND_LIST_FUNC(CaptureDevice)
768 #undef DECL_APPEND_LIST_FUNC
771 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
772 void SetDefaultChannelOrder(ALCdevice *device)
774 switch(device->FmtChans)
776 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
777 device->DevChannels[1] = FRONT_RIGHT;
778 device->DevChannels[2] = BACK_LEFT;
779 device->DevChannels[3] = BACK_RIGHT;
780 device->DevChannels[4] = FRONT_CENTER;
781 device->DevChannels[5] = LFE;
782 return;
784 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
785 device->DevChannels[1] = FRONT_RIGHT;
786 device->DevChannels[2] = BACK_LEFT;
787 device->DevChannels[3] = BACK_RIGHT;
788 device->DevChannels[4] = FRONT_CENTER;
789 device->DevChannels[5] = LFE;
790 device->DevChannels[6] = SIDE_LEFT;
791 device->DevChannels[7] = SIDE_RIGHT;
792 return;
794 /* Same as WFX order */
795 case DevFmtMono:
796 case DevFmtStereo:
797 case DevFmtQuad:
798 case DevFmtX51Side:
799 case DevFmtX61:
800 break;
802 SetDefaultWFXChannelOrder(device);
804 /* Sets the default order used by WaveFormatEx */
805 void SetDefaultWFXChannelOrder(ALCdevice *device)
807 switch(device->FmtChans)
809 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
811 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
812 device->DevChannels[1] = FRONT_RIGHT; break;
814 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
815 device->DevChannels[1] = FRONT_RIGHT;
816 device->DevChannels[2] = BACK_LEFT;
817 device->DevChannels[3] = BACK_RIGHT; break;
819 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
820 device->DevChannels[1] = FRONT_RIGHT;
821 device->DevChannels[2] = FRONT_CENTER;
822 device->DevChannels[3] = LFE;
823 device->DevChannels[4] = BACK_LEFT;
824 device->DevChannels[5] = BACK_RIGHT; break;
826 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
827 device->DevChannels[1] = FRONT_RIGHT;
828 device->DevChannels[2] = FRONT_CENTER;
829 device->DevChannels[3] = LFE;
830 device->DevChannels[4] = SIDE_LEFT;
831 device->DevChannels[5] = SIDE_RIGHT; break;
833 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
834 device->DevChannels[1] = FRONT_RIGHT;
835 device->DevChannels[2] = FRONT_CENTER;
836 device->DevChannels[3] = LFE;
837 device->DevChannels[4] = BACK_CENTER;
838 device->DevChannels[5] = SIDE_LEFT;
839 device->DevChannels[6] = SIDE_RIGHT; break;
841 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
842 device->DevChannels[1] = FRONT_RIGHT;
843 device->DevChannels[2] = FRONT_CENTER;
844 device->DevChannels[3] = LFE;
845 device->DevChannels[4] = BACK_LEFT;
846 device->DevChannels[5] = BACK_RIGHT;
847 device->DevChannels[6] = SIDE_LEFT;
848 device->DevChannels[7] = SIDE_RIGHT; break;
853 const ALCchar *DevFmtTypeString(enum DevFmtType type)
855 switch(type)
857 case DevFmtByte: return "Signed Byte";
858 case DevFmtUByte: return "Unsigned Byte";
859 case DevFmtShort: return "Signed Short";
860 case DevFmtUShort: return "Unsigned Short";
861 case DevFmtFloat: return "Float";
863 return "(unknown type)";
865 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
867 switch(chans)
869 case DevFmtMono: return "Mono";
870 case DevFmtStereo: return "Stereo";
871 case DevFmtQuad: return "Quadraphonic";
872 case DevFmtX51: return "5.1 Surround";
873 case DevFmtX51Side: return "5.1 Side";
874 case DevFmtX61: return "6.1 Surround";
875 case DevFmtX71: return "7.1 Surround";
877 return "(unknown channels)";
880 ALuint BytesFromDevFmt(enum DevFmtType type)
882 switch(type)
884 case DevFmtByte: return sizeof(ALbyte);
885 case DevFmtUByte: return sizeof(ALubyte);
886 case DevFmtShort: return sizeof(ALshort);
887 case DevFmtUShort: return sizeof(ALushort);
888 case DevFmtFloat: return sizeof(ALfloat);
890 return 0;
892 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
894 switch(chans)
896 case DevFmtMono: return 1;
897 case DevFmtStereo: return 2;
898 case DevFmtQuad: return 4;
899 case DevFmtX51: return 6;
900 case DevFmtX51Side: return 6;
901 case DevFmtX61: return 7;
902 case DevFmtX71: return 8;
904 return 0;
906 ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
907 enum DevFmtType *type)
909 switch(format)
911 case AL_FORMAT_MONO8:
912 *chans = DevFmtMono;
913 *type = DevFmtUByte;
914 return AL_TRUE;
915 case AL_FORMAT_MONO16:
916 *chans = DevFmtMono;
917 *type = DevFmtShort;
918 return AL_TRUE;
919 case AL_FORMAT_MONO_FLOAT32:
920 *chans = DevFmtMono;
921 *type = DevFmtFloat;
922 return AL_TRUE;
923 case AL_FORMAT_STEREO8:
924 *chans = DevFmtStereo;
925 *type = DevFmtUByte;
926 return AL_TRUE;
927 case AL_FORMAT_STEREO16:
928 *chans = DevFmtStereo;
929 *type = DevFmtShort;
930 return AL_TRUE;
931 case AL_FORMAT_STEREO_FLOAT32:
932 *chans = DevFmtStereo;
933 *type = DevFmtFloat;
934 return AL_TRUE;
935 case AL_FORMAT_QUAD8:
936 *chans = DevFmtQuad;
937 *type = DevFmtUByte;
938 return AL_TRUE;
939 case AL_FORMAT_QUAD16:
940 *chans = DevFmtQuad;
941 *type = DevFmtShort;
942 return AL_TRUE;
943 case AL_FORMAT_QUAD32:
944 *chans = DevFmtQuad;
945 *type = DevFmtFloat;
946 return AL_TRUE;
947 case AL_FORMAT_51CHN8:
948 *chans = DevFmtX51;
949 *type = DevFmtUByte;
950 return AL_TRUE;
951 case AL_FORMAT_51CHN16:
952 *chans = DevFmtX51;
953 *type = DevFmtShort;
954 return AL_TRUE;
955 case AL_FORMAT_51CHN32:
956 *chans = DevFmtX51;
957 *type = DevFmtFloat;
958 return AL_TRUE;
959 case AL_FORMAT_61CHN8:
960 *chans = DevFmtX61;
961 *type = DevFmtUByte;
962 return AL_TRUE;
963 case AL_FORMAT_61CHN16:
964 *chans = DevFmtX61;
965 *type = DevFmtShort;
966 return AL_TRUE;
967 case AL_FORMAT_61CHN32:
968 *chans = DevFmtX61;
969 *type = DevFmtFloat;
970 return AL_TRUE;
971 case AL_FORMAT_71CHN8:
972 *chans = DevFmtX71;
973 *type = DevFmtUByte;
974 return AL_TRUE;
975 case AL_FORMAT_71CHN16:
976 *chans = DevFmtX71;
977 *type = DevFmtShort;
978 return AL_TRUE;
979 case AL_FORMAT_71CHN32:
980 *chans = DevFmtX71;
981 *type = DevFmtFloat;
982 return AL_TRUE;
984 return AL_FALSE;
987 static ALCboolean IsValidALCType(ALCenum type)
989 switch(type)
991 case ALC_BYTE:
992 case ALC_UNSIGNED_BYTE:
993 case ALC_SHORT:
994 case ALC_UNSIGNED_SHORT:
995 case ALC_INT:
996 case ALC_UNSIGNED_INT:
997 case ALC_FLOAT:
998 return ALC_TRUE;
1000 return ALC_FALSE;
1003 static ALCboolean IsValidALCChannels(ALCenum channels)
1005 switch(channels)
1007 case ALC_MONO:
1008 case ALC_STEREO:
1009 case ALC_QUAD:
1010 case ALC_5POINT1:
1011 case ALC_6POINT1:
1012 case ALC_7POINT1:
1013 return ALC_TRUE;
1015 return ALC_FALSE;
1018 /* IsDevice
1020 * Check if the device pointer is valid (caller is responsible for holding the
1021 * list lock).
1023 static ALCboolean IsDevice(ALCdevice *pDevice)
1025 ALCdevice *pTempDevice;
1027 pTempDevice = g_pDeviceList;
1028 while(pTempDevice && pTempDevice != pDevice)
1029 pTempDevice = pTempDevice->next;
1031 return (pTempDevice ? ALC_TRUE : ALC_FALSE);
1034 /* IsContext
1036 * Check if the context pointer is valid (caller is responsible for holding the
1037 * list lock).
1039 static ALCboolean IsContext(ALCcontext *context)
1041 ALCdevice *tmp_dev;
1043 tmp_dev = g_pDeviceList;
1044 while(tmp_dev)
1046 ALCcontext *tmp_ctx = tmp_dev->ContextList;
1047 while(tmp_ctx)
1049 if(tmp_ctx == context)
1050 return ALC_TRUE;
1051 tmp_ctx = tmp_ctx->next;
1053 tmp_dev = tmp_dev->next;
1056 return ALC_FALSE;
1060 /* UpdateDeviceParams
1062 * Updates device parameters according to the attribute list (caller is
1063 * responsible for holding the list lock).
1065 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1067 ALCcontext *context;
1068 ALuint i;
1070 // Check for attributes
1071 if(attrList && attrList[0])
1073 ALCuint freq, numMono, numStereo, numSends;
1074 enum DevFmtChannels schans;
1075 enum DevFmtType stype;
1076 ALuint attrIdx;
1078 // If a context is already running on the device, stop playback so the
1079 // device attributes can be updated
1080 if((device->Flags&DEVICE_RUNNING))
1081 ALCdevice_StopPlayback(device);
1082 device->Flags &= ~DEVICE_RUNNING;
1084 freq = device->Frequency;
1085 schans = device->FmtChans;
1086 stype = device->FmtType;
1087 numMono = device->NumMonoSources;
1088 numStereo = device->NumStereoSources;
1089 numSends = device->NumAuxSends;
1091 freq = GetConfigValueInt(NULL, "frequency", freq);
1092 if(freq < 8000) freq = 8000;
1094 attrIdx = 0;
1095 while(attrList[attrIdx])
1097 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1098 device->IsLoopbackDevice)
1100 ALCint val = attrList[attrIdx + 1];
1101 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1103 alcSetError(device, ALC_INVALID_VALUE);
1104 return ALC_FALSE;
1106 schans = val;
1109 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1110 device->IsLoopbackDevice)
1112 ALCint val = attrList[attrIdx + 1];
1113 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1115 alcSetError(device, ALC_INVALID_VALUE);
1116 return ALC_FALSE;
1118 stype = val;
1121 if(attrList[attrIdx] == ALC_FREQUENCY)
1123 if(device->IsLoopbackDevice)
1125 freq = attrList[attrIdx + 1];
1126 if(freq < 8000)
1128 alcSetError(device, ALC_INVALID_VALUE);
1129 return ALC_FALSE;
1132 else if(!ConfigValueExists(NULL, "frequency"))
1134 freq = attrList[attrIdx + 1];
1135 if(freq < 8000) freq = 8000;
1136 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1140 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1142 numStereo = attrList[attrIdx + 1];
1143 if(numStereo > device->MaxNoOfSources)
1144 numStereo = device->MaxNoOfSources;
1146 numMono = device->MaxNoOfSources - numStereo;
1149 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS &&
1150 !ConfigValueExists(NULL, "sends"))
1152 numSends = attrList[attrIdx + 1];
1153 if(numSends > MAX_SENDS)
1154 numSends = MAX_SENDS;
1157 attrIdx += 2;
1160 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1161 device->Frequency;
1163 device->Frequency = freq;
1164 device->FmtChans = schans;
1165 device->FmtType = stype;
1166 device->NumMonoSources = numMono;
1167 device->NumStereoSources = numStereo;
1168 device->NumAuxSends = numSends;
1171 if((device->Flags&DEVICE_RUNNING))
1172 return ALC_TRUE;
1174 LockDevice(device);
1175 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1176 DevFmtChannelsString(device->FmtChans),
1177 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1178 DevFmtTypeString(device->FmtType), device->Frequency,
1179 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1180 device->UpdateSize, device->NumUpdates);
1181 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1183 UnlockDevice(device);
1184 return ALC_FALSE;
1186 device->Flags |= DEVICE_RUNNING;
1187 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1188 DevFmtChannelsString(device->FmtChans),
1189 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1190 DevFmtTypeString(device->FmtType), device->Frequency,
1191 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1192 device->UpdateSize, device->NumUpdates);
1194 aluInitPanning(device);
1196 for(i = 0;i < MAXCHANNELS;i++)
1198 device->ClickRemoval[i] = 0.0f;
1199 device->PendingClicks[i] = 0.0f;
1202 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1203 device->Flags |= DEVICE_USE_HRTF;
1204 if((device->Flags&DEVICE_USE_HRTF) && !IsHrtfCompatible(device))
1205 device->Flags &= ~DEVICE_USE_HRTF;
1206 TRACE("HRTF %s\n", (device->Flags&DEVICE_USE_HRTF)?"enabled":"disabled");
1208 if(!(device->Flags&DEVICE_USE_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 context = device->ContextList;
1244 while(context)
1246 ALsizei pos;
1248 context->UpdateSources = AL_FALSE;
1249 LockUIntMapRead(&context->EffectSlotMap);
1250 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1252 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1254 if(ALEffect_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1256 UnlockUIntMapRead(&context->EffectSlotMap);
1257 UnlockDevice(device);
1258 ALCdevice_StopPlayback(device);
1259 device->Flags &= ~DEVICE_RUNNING;
1260 return ALC_FALSE;
1262 slot->NeedsUpdate = AL_FALSE;
1263 ALEffect_Update(slot->EffectState, context, slot);
1265 UnlockUIntMapRead(&context->EffectSlotMap);
1267 LockUIntMapRead(&context->SourceMap);
1268 for(pos = 0;pos < context->SourceMap.size;pos++)
1270 ALsource *source = context->SourceMap.array[pos].value;
1271 ALuint s = device->NumAuxSends;
1272 while(s < MAX_SENDS)
1274 if(source->Send[s].Slot)
1275 DecrementRef(&source->Send[s].Slot->ref);
1276 source->Send[s].Slot = NULL;
1277 source->Send[s].WetGain = 1.0f;
1278 source->Send[s].WetGainHF = 1.0f;
1279 s++;
1281 source->NeedsUpdate = AL_FALSE;
1282 ALsource_Update(source, context);
1284 UnlockUIntMapRead(&context->SourceMap);
1286 context = context->next;
1288 UnlockDevice(device);
1290 return ALC_TRUE;
1293 /* FreeDevice
1295 * Frees the device structure, and destroys any objects the app failed to
1296 * delete. Called once there's no more references on the device.
1298 static ALCvoid FreeDevice(ALCdevice *device)
1300 TRACE("%p\n", device);
1302 if(device->BufferMap.size > 0)
1304 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1305 ReleaseALBuffers(device);
1307 ResetUIntMap(&device->BufferMap);
1309 if(device->EffectMap.size > 0)
1311 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1312 ReleaseALEffects(device);
1314 ResetUIntMap(&device->EffectMap);
1316 if(device->FilterMap.size > 0)
1318 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1319 ReleaseALFilters(device);
1321 ResetUIntMap(&device->FilterMap);
1323 free(device->Bs2b);
1324 device->Bs2b = NULL;
1326 free(device->szDeviceName);
1327 device->szDeviceName = NULL;
1329 DeleteCriticalSection(&device->Mutex);
1331 free(device);
1335 void ALCdevice_IncRef(ALCdevice *device)
1337 RefCount ref;
1338 ref = IncrementRef(&device->ref);
1339 TRACE("%p increasing refcount to %u\n", device, ref);
1342 void ALCdevice_DecRef(ALCdevice *device)
1344 RefCount ref;
1345 ref = DecrementRef(&device->ref);
1346 TRACE("%p decreasing refcount to %u\n", device, ref);
1347 if(ref == 0) FreeDevice(device);
1350 /* VerifyDevice
1352 * Checks if the device handle is valid, and increments its ref count if so.
1354 static ALCdevice *VerifyDevice(ALCdevice *device)
1356 ALCdevice *tmpDevice;
1358 if(!device)
1359 return NULL;
1361 LockLists();
1362 tmpDevice = g_pDeviceList;
1363 while(tmpDevice && tmpDevice != device)
1364 tmpDevice = tmpDevice->next;
1366 if(tmpDevice)
1367 ALCdevice_IncRef(tmpDevice);
1368 UnlockLists();
1369 return tmpDevice;
1373 /* alcSetError
1375 * Stores the latest ALC Error
1377 ALCvoid alcSetError(ALCdevice *device, ALCenum errorCode)
1379 if(TrapALCError)
1381 #ifdef _WIN32
1382 /* Safely catch a breakpoint exception that wasn't caught by a debugger */
1383 __try {
1384 DebugBreak();
1385 } __except((GetExceptionCode()==EXCEPTION_BREAKPOINT) ?
1386 EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
1388 #elif defined(SIGTRAP)
1389 kill(getpid(), SIGTRAP);
1390 #endif
1393 if(device)
1394 device->LastError = errorCode;
1395 else
1396 g_eLastNullDeviceError = errorCode;
1400 ALCvoid LockDevice(ALCdevice *device)
1402 EnterCriticalSection(&device->Mutex);
1405 ALCvoid UnlockDevice(ALCdevice *device)
1407 LeaveCriticalSection(&device->Mutex);
1411 /* InitContext
1413 * Initializes context variables
1415 static ALvoid InitContext(ALCcontext *pContext)
1417 //Initialise listener
1418 pContext->Listener.Gain = 1.0f;
1419 pContext->Listener.MetersPerUnit = 1.0f;
1420 pContext->Listener.Position[0] = 0.0f;
1421 pContext->Listener.Position[1] = 0.0f;
1422 pContext->Listener.Position[2] = 0.0f;
1423 pContext->Listener.Velocity[0] = 0.0f;
1424 pContext->Listener.Velocity[1] = 0.0f;
1425 pContext->Listener.Velocity[2] = 0.0f;
1426 pContext->Listener.Forward[0] = 0.0f;
1427 pContext->Listener.Forward[1] = 0.0f;
1428 pContext->Listener.Forward[2] = -1.0f;
1429 pContext->Listener.Up[0] = 0.0f;
1430 pContext->Listener.Up[1] = 1.0f;
1431 pContext->Listener.Up[2] = 0.0f;
1433 //Validate pContext
1434 pContext->LastError = AL_NO_ERROR;
1435 pContext->UpdateSources = AL_FALSE;
1436 pContext->ActiveSourceCount = 0;
1437 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1438 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1440 //Set globals
1441 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1442 pContext->SourceDistanceModel = AL_FALSE;
1443 pContext->DopplerFactor = 1.0f;
1444 pContext->DopplerVelocity = 1.0f;
1445 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1446 pContext->DeferUpdates = AL_FALSE;
1448 pContext->ExtensionList = alExtList;
1452 /* FreeContext
1454 * Cleans up the context, and destroys any remaining objects the app failed to
1455 * delete. Called once there's no more references on the context.
1457 static ALCvoid FreeContext(ALCcontext *context)
1459 TRACE("%p\n", context);
1461 if(context->SourceMap.size > 0)
1463 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1464 ReleaseALSources(context);
1466 ResetUIntMap(&context->SourceMap);
1468 if(context->EffectSlotMap.size > 0)
1470 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1471 ReleaseALAuxiliaryEffectSlots(context);
1473 ResetUIntMap(&context->EffectSlotMap);
1475 context->ActiveSourceCount = 0;
1476 free(context->ActiveSources);
1477 context->ActiveSources = NULL;
1478 context->MaxActiveSources = 0;
1480 context->ActiveEffectSlotCount = 0;
1481 free(context->ActiveEffectSlots);
1482 context->ActiveEffectSlots = NULL;
1483 context->MaxActiveEffectSlots = 0;
1485 ALCdevice_DecRef(context->Device);
1486 context->Device = NULL;
1488 //Invalidate context
1489 memset(context, 0, sizeof(ALCcontext));
1490 free(context);
1493 /* ReleaseContext
1495 * Removes the context reference from the given device and removes it from
1496 * being current on the running thread or globally.
1498 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1500 ALCcontext *volatile*tmp_ctx;
1502 tmp_ctx = &device->ContextList;
1503 while(*tmp_ctx)
1505 if(*tmp_ctx == context)
1507 *tmp_ctx = context->next;
1508 break;
1510 tmp_ctx = &(*tmp_ctx)->next;
1513 LockDevice(device);
1514 /* Lock the device to make sure the mixer is not using the contexts in the
1515 * list before we go about deleting this one. There should be a more
1516 * efficient way of doing this. */
1517 UnlockDevice(device);
1519 if(pthread_getspecific(LocalContext) == context)
1521 WARN("Context %p released while current on thread\n", context);
1522 pthread_setspecific(LocalContext, NULL);
1523 ALCcontext_DecRef(context);
1526 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1528 WARN("Context %p released while current\n", context);
1529 ALCcontext_DecRef(context);
1532 ALCcontext_DecRef(context);
1535 void ALCcontext_IncRef(ALCcontext *context)
1537 RefCount ref;
1538 ref = IncrementRef(&context->ref);
1539 TRACE("%p increasing refcount to %u\n", context, ref);
1542 void ALCcontext_DecRef(ALCcontext *context)
1544 RefCount ref;
1545 ref = DecrementRef(&context->ref);
1546 TRACE("%p decreasing refcount to %u\n", context, ref);
1547 if(ref == 0) FreeContext(context);
1550 static void ReleaseThreadCtx(void *ptr)
1552 WARN("Context %p current for thread being destroyed\n", ptr);
1553 ALCcontext_DecRef(ptr);
1557 ALCvoid LockContext(ALCcontext *context)
1559 EnterCriticalSection(&context->Device->Mutex);
1562 ALCvoid UnlockContext(ALCcontext *context)
1564 LeaveCriticalSection(&context->Device->Mutex);
1567 /* GetContextRef
1569 * Returns the currently active context, and adds a reference without locking
1570 * it.
1572 ALCcontext *GetContextRef(void)
1574 ALCcontext *context;
1576 context = pthread_getspecific(LocalContext);
1577 if(context)
1578 ALCcontext_IncRef(context);
1579 else
1581 LockLists();
1582 context = GlobalContext;
1583 if(context)
1584 ALCcontext_IncRef(context);
1585 UnlockLists();
1588 return context;
1591 ///////////////////////////////////////////////////////
1594 ///////////////////////////////////////////////////////
1595 // ALC Functions calls
1598 // This should probably move to another c file but for now ...
1599 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1601 ALCdevice *device = NULL;
1602 ALCenum err;
1604 DO_INITCONFIG();
1606 if(!CaptureBackend.name)
1608 alcSetError(NULL, ALC_INVALID_VALUE);
1609 return NULL;
1612 if(SampleSize <= 0)
1614 alcSetError(NULL, ALC_INVALID_VALUE);
1615 return NULL;
1618 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1619 deviceName = NULL;
1621 device = calloc(1, sizeof(ALCdevice));
1622 if(!device)
1624 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1625 return NULL;
1628 //Validate device
1629 device->Funcs = &CaptureBackend.Funcs;
1630 device->ref = 1;
1631 device->Connected = ALC_TRUE;
1632 device->IsCaptureDevice = AL_TRUE;
1633 device->IsLoopbackDevice = AL_FALSE;
1634 InitializeCriticalSection(&device->Mutex);
1636 InitUIntMap(&device->BufferMap, ~0);
1637 InitUIntMap(&device->EffectMap, ~0);
1638 InitUIntMap(&device->FilterMap, ~0);
1640 device->szDeviceName = NULL;
1642 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1643 device->Frequency = frequency;
1645 device->Flags |= DEVICE_CHANNELS_REQUEST;
1646 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1648 free(device);
1649 alcSetError(NULL, ALC_INVALID_ENUM);
1650 return NULL;
1653 device->UpdateSize = SampleSize;
1654 device->NumUpdates = 1;
1656 LockLists();
1657 if((err=ALCdevice_OpenCapture(device, deviceName)) == ALC_NO_ERROR)
1659 device->next = g_pDeviceList;
1660 g_pDeviceList = device;
1661 g_ulDeviceCount++;
1663 else
1665 DeleteCriticalSection(&device->Mutex);
1666 free(device);
1667 device = NULL;
1668 alcSetError(NULL, err);
1670 UnlockLists();
1672 return device;
1675 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1677 ALCdevice **list;
1679 LockLists();
1680 list = &g_pDeviceList;
1681 while(*list && *list != pDevice)
1682 list = &(*list)->next;
1684 if(!*list || !(*list)->IsCaptureDevice)
1686 alcSetError(*list, ALC_INVALID_DEVICE);
1687 UnlockLists();
1688 return ALC_FALSE;
1691 *list = (*list)->next;
1692 g_ulDeviceCount--;
1694 UnlockLists();
1696 LockDevice(pDevice);
1697 ALCdevice_CloseCapture(pDevice);
1698 UnlockDevice(pDevice);
1700 ALCdevice_DecRef(pDevice);
1702 return ALC_TRUE;
1705 ALC_API void ALC_APIENTRY alcCaptureStart(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_StartCapture(device);
1716 UnlockDevice(device);
1718 ALCdevice_DecRef(device);
1721 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1723 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1725 alcSetError(device, ALC_INVALID_DEVICE);
1726 if(device) ALCdevice_DecRef(device);
1727 return;
1729 LockDevice(device);
1730 if(device->Connected)
1731 ALCdevice_StopCapture(device);
1732 UnlockDevice(device);
1734 ALCdevice_DecRef(device);
1737 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1739 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1741 alcSetError(device, ALC_INVALID_DEVICE);
1742 if(device) ALCdevice_DecRef(device);
1743 return;
1745 LockDevice(device);
1746 ALCdevice_CaptureSamples(device, buffer, samples);
1747 UnlockDevice(device);
1749 ALCdevice_DecRef(device);
1753 alcGetError
1755 Return last ALC generated error code
1757 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1759 ALCenum errorCode;
1761 if(VerifyDevice(device))
1763 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1764 ALCdevice_DecRef(device);
1766 else
1767 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1769 return errorCode;
1773 /* alcSuspendContext
1775 * Not functional
1777 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1779 (void)Context;
1782 /* alcProcessContext
1784 * Not functional
1786 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1788 (void)Context;
1792 /* alcGetString
1794 * Returns information about the Device, and error strings
1796 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1798 const ALCchar *value = NULL;
1800 switch(param)
1802 case ALC_NO_ERROR:
1803 value = alcNoError;
1804 break;
1806 case ALC_INVALID_ENUM:
1807 value = alcErrInvalidEnum;
1808 break;
1810 case ALC_INVALID_VALUE:
1811 value = alcErrInvalidValue;
1812 break;
1814 case ALC_INVALID_DEVICE:
1815 value = alcErrInvalidDevice;
1816 break;
1818 case ALC_INVALID_CONTEXT:
1819 value = alcErrInvalidContext;
1820 break;
1822 case ALC_OUT_OF_MEMORY:
1823 value = alcErrOutOfMemory;
1824 break;
1826 case ALC_DEVICE_SPECIFIER:
1827 if(VerifyDevice(pDevice))
1829 value = pDevice->szDeviceName;
1830 ALCdevice_DecRef(pDevice);
1832 else
1834 ProbeDeviceList();
1835 value = alcDeviceList;
1837 break;
1839 case ALC_ALL_DEVICES_SPECIFIER:
1840 ProbeAllDeviceList();
1841 value = alcAllDeviceList;
1842 break;
1844 case ALC_CAPTURE_DEVICE_SPECIFIER:
1845 if(VerifyDevice(pDevice))
1847 value = pDevice->szDeviceName;
1848 ALCdevice_DecRef(pDevice);
1850 else
1852 ProbeCaptureDeviceList();
1853 value = alcCaptureDeviceList;
1855 break;
1857 /* Default devices are always first in the list */
1858 case ALC_DEFAULT_DEVICE_SPECIFIER:
1859 if(!alcDeviceList)
1860 ProbeDeviceList();
1862 pDevice = VerifyDevice(pDevice);
1864 free(alcDefaultDeviceSpecifier);
1865 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1866 if(!alcDefaultDeviceSpecifier)
1867 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1869 value = alcDefaultDeviceSpecifier;
1870 if(pDevice) ALCdevice_DecRef(pDevice);
1871 break;
1873 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1874 if(!alcAllDeviceList)
1875 ProbeAllDeviceList();
1877 pDevice = VerifyDevice(pDevice);
1879 free(alcDefaultAllDeviceSpecifier);
1880 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1881 alcAllDeviceList : "");
1882 if(!alcDefaultAllDeviceSpecifier)
1883 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1885 value = alcDefaultAllDeviceSpecifier;
1886 if(pDevice) ALCdevice_DecRef(pDevice);
1887 break;
1889 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1890 if(!alcCaptureDeviceList)
1891 ProbeCaptureDeviceList();
1893 pDevice = VerifyDevice(pDevice);
1895 free(alcCaptureDefaultDeviceSpecifier);
1896 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1897 alcCaptureDeviceList : "");
1898 if(!alcCaptureDefaultDeviceSpecifier)
1899 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1901 value = alcCaptureDefaultDeviceSpecifier;
1902 if(pDevice) ALCdevice_DecRef(pDevice);
1903 break;
1905 case ALC_EXTENSIONS:
1906 if(!VerifyDevice(pDevice))
1907 value = alcNoDeviceExtList;
1908 else
1910 value = alcExtensionList;
1911 ALCdevice_DecRef(pDevice);
1913 break;
1915 default:
1916 pDevice = VerifyDevice(pDevice);
1917 alcSetError(pDevice, ALC_INVALID_ENUM);
1918 if(pDevice) ALCdevice_DecRef(pDevice);
1919 break;
1922 return value;
1926 /* alcGetIntegerv
1928 * Returns information about the Device and the version of Open AL
1930 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1932 device = VerifyDevice(device);
1934 if(size == 0 || data == NULL)
1936 alcSetError(device, ALC_INVALID_VALUE);
1937 if(device) ALCdevice_DecRef(device);
1938 return;
1941 if(!device)
1943 switch(param)
1945 case ALC_MAJOR_VERSION:
1946 *data = alcMajorVersion;
1947 break;
1948 case ALC_MINOR_VERSION:
1949 *data = alcMinorVersion;
1950 break;
1952 case ALC_ATTRIBUTES_SIZE:
1953 case ALC_ALL_ATTRIBUTES:
1954 case ALC_FREQUENCY:
1955 case ALC_REFRESH:
1956 case ALC_SYNC:
1957 case ALC_MONO_SOURCES:
1958 case ALC_STEREO_SOURCES:
1959 case ALC_CAPTURE_SAMPLES:
1960 case ALC_FORMAT_CHANNELS_SOFT:
1961 case ALC_FORMAT_TYPE_SOFT:
1962 alcSetError(NULL, ALC_INVALID_DEVICE);
1963 break;
1965 default:
1966 alcSetError(NULL, ALC_INVALID_ENUM);
1967 break;
1970 else if(device->IsCaptureDevice)
1972 switch(param)
1974 case ALC_CAPTURE_SAMPLES:
1975 LockDevice(device);
1976 *data = ALCdevice_AvailableSamples(device);
1977 UnlockDevice(device);
1978 break;
1980 case ALC_CONNECTED:
1981 *data = device->Connected;
1982 break;
1984 default:
1985 alcSetError(device, ALC_INVALID_ENUM);
1986 break;
1989 else /* render device */
1991 switch(param)
1993 case ALC_MAJOR_VERSION:
1994 *data = alcMajorVersion;
1995 break;
1997 case ALC_MINOR_VERSION:
1998 *data = alcMinorVersion;
1999 break;
2001 case ALC_EFX_MAJOR_VERSION:
2002 *data = alcEFXMajorVersion;
2003 break;
2005 case ALC_EFX_MINOR_VERSION:
2006 *data = alcEFXMinorVersion;
2007 break;
2009 case ALC_ATTRIBUTES_SIZE:
2010 *data = 13;
2011 break;
2013 case ALC_ALL_ATTRIBUTES:
2014 if(size < 13)
2015 alcSetError(device, ALC_INVALID_VALUE);
2016 else
2018 int i = 0;
2020 data[i++] = ALC_FREQUENCY;
2021 data[i++] = device->Frequency;
2023 if(!device->IsLoopbackDevice)
2025 data[i++] = ALC_REFRESH;
2026 data[i++] = device->Frequency / device->UpdateSize;
2028 data[i++] = ALC_SYNC;
2029 data[i++] = ALC_FALSE;
2031 else
2033 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2034 data[i++] = device->FmtChans;
2036 data[i++] = ALC_FORMAT_TYPE_SOFT;
2037 data[i++] = device->FmtType;
2040 data[i++] = ALC_MONO_SOURCES;
2041 data[i++] = device->NumMonoSources;
2043 data[i++] = ALC_STEREO_SOURCES;
2044 data[i++] = device->NumStereoSources;
2046 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2047 data[i++] = device->NumAuxSends;
2049 data[i++] = 0;
2051 break;
2053 case ALC_FREQUENCY:
2054 *data = device->Frequency;
2055 break;
2057 case ALC_REFRESH:
2058 if(device->IsLoopbackDevice)
2059 alcSetError(device, ALC_INVALID_DEVICE);
2060 else
2061 *data = device->Frequency / device->UpdateSize;
2062 break;
2064 case ALC_SYNC:
2065 if(device->IsLoopbackDevice)
2066 alcSetError(device, ALC_INVALID_DEVICE);
2067 else
2068 *data = ALC_FALSE;
2069 break;
2071 case ALC_FORMAT_CHANNELS_SOFT:
2072 if(!device->IsLoopbackDevice)
2073 alcSetError(device, ALC_INVALID_DEVICE);
2074 else
2075 *data = device->FmtChans;
2076 break;
2078 case ALC_FORMAT_TYPE_SOFT:
2079 if(!device->IsLoopbackDevice)
2080 alcSetError(device, ALC_INVALID_DEVICE);
2081 else
2082 *data = device->FmtType;
2083 break;
2085 case ALC_MONO_SOURCES:
2086 *data = device->NumMonoSources;
2087 break;
2089 case ALC_STEREO_SOURCES:
2090 *data = device->NumStereoSources;
2091 break;
2093 case ALC_MAX_AUXILIARY_SENDS:
2094 *data = device->NumAuxSends;
2095 break;
2097 case ALC_CONNECTED:
2098 *data = device->Connected;
2099 break;
2101 default:
2102 alcSetError(device, ALC_INVALID_ENUM);
2103 break;
2106 if(device)
2107 ALCdevice_DecRef(device);
2111 /* alcIsExtensionPresent
2113 * Determines if there is support for a particular extension
2115 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2117 ALCboolean bResult = ALC_FALSE;
2119 device = VerifyDevice(device);
2121 if(!extName)
2122 alcSetError(device, ALC_INVALID_VALUE);
2123 else
2125 size_t len = strlen(extName);
2126 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2127 while(ptr && *ptr)
2129 if(strncasecmp(ptr, extName, len) == 0 &&
2130 (ptr[len] == '\0' || isspace(ptr[len])))
2132 bResult = ALC_TRUE;
2133 break;
2135 if((ptr=strchr(ptr, ' ')) != NULL)
2137 do {
2138 ++ptr;
2139 } while(isspace(*ptr));
2143 if(device)
2144 ALCdevice_DecRef(device);
2145 return bResult;
2149 /* alcGetProcAddress
2151 * Retrieves the function address for a particular extension function
2153 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2155 ALCvoid *ptr = NULL;
2157 device = VerifyDevice(device);
2159 if(!funcName)
2160 alcSetError(device, ALC_INVALID_VALUE);
2161 else
2163 ALsizei i = 0;
2164 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2165 i++;
2166 ptr = alcFunctions[i].address;
2168 if(device)
2169 ALCdevice_DecRef(device);
2170 return ptr;
2174 /* alcGetEnumValue
2176 * Get the value for a particular ALC Enumerated Value
2178 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2180 ALCenum val = 0;
2182 device = VerifyDevice(device);
2184 if(!enumName)
2185 alcSetError(device, ALC_INVALID_VALUE);
2186 else
2188 ALsizei i = 0;
2189 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2190 i++;
2191 val = enumeration[i].value;
2193 if(device)
2194 ALCdevice_DecRef(device);
2195 return val;
2199 /* alcCreateContext
2201 * Create and attach a Context to a particular Device.
2203 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2205 ALCcontext *ALContext;
2207 LockLists();
2208 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2210 UnlockLists();
2211 alcSetError(device, ALC_INVALID_DEVICE);
2212 if(device) ALCdevice_DecRef(device);
2213 return NULL;
2216 /* Reset Context Last Error code */
2217 device->LastError = ALC_NO_ERROR;
2219 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2221 UnlockLists();
2222 alcSetError(device, ALC_INVALID_DEVICE);
2223 aluHandleDisconnect(device);
2224 ALCdevice_DecRef(device);
2225 return NULL;
2228 ALContext = calloc(1, sizeof(ALCcontext));
2229 if(ALContext)
2231 ALContext->ref = 1;
2233 ALContext->MaxActiveSources = 256;
2234 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2235 ALContext->MaxActiveSources);
2237 if(!ALContext || !ALContext->ActiveSources)
2239 if(!device->ContextList)
2241 ALCdevice_StopPlayback(device);
2242 device->Flags &= ~DEVICE_RUNNING;
2244 UnlockLists();
2246 free(ALContext);
2247 ALContext = NULL;
2249 alcSetError(device, ALC_OUT_OF_MEMORY);
2250 ALCdevice_DecRef(device);
2251 return NULL;
2254 ALContext->Device = device;
2255 ALCdevice_IncRef(device);
2256 InitContext(ALContext);
2258 ALContext->next = device->ContextList;
2259 device->ContextList = ALContext;
2260 UnlockLists();
2262 ALCdevice_DecRef(device);
2263 return ALContext;
2266 /* alcDestroyContext
2268 * Remove a Context
2270 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2272 ALCdevice *Device;
2274 LockLists();
2275 /* alcGetContextsDevice sets an error for invalid contexts */
2276 Device = alcGetContextsDevice(context);
2277 if(Device)
2279 ReleaseContext(context, Device);
2280 if(!Device->ContextList)
2282 ALCdevice_StopPlayback(Device);
2283 Device->Flags &= ~DEVICE_RUNNING;
2286 UnlockLists();
2290 /* alcGetCurrentContext
2292 * Returns the currently active Context
2294 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2296 ALCcontext *Context;
2298 Context = pthread_getspecific(LocalContext);
2299 if(!Context) Context = GlobalContext;
2301 return Context;
2304 /* alcGetThreadContext
2306 * Returns the currently active thread-local Context
2308 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2310 ALCcontext *Context;
2311 Context = pthread_getspecific(LocalContext);
2312 return Context;
2316 /* alcMakeContextCurrent
2318 * Makes the given Context the active Context
2320 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2322 ALboolean bReturn = AL_TRUE;
2324 LockLists();
2326 // context must be a valid Context or NULL
2327 if(context == NULL || IsContext(context))
2329 ALCcontext *old;
2331 if(context) ALCcontext_IncRef(context);
2332 old = ExchangePtr((void**)&GlobalContext, context);
2333 if(old) ALCcontext_DecRef(old);
2335 if((old=pthread_getspecific(LocalContext)) != NULL)
2337 pthread_setspecific(LocalContext, NULL);
2338 ALCcontext_DecRef(old);
2341 else
2343 alcSetError(NULL, ALC_INVALID_CONTEXT);
2344 bReturn = AL_FALSE;
2347 UnlockLists();
2349 return bReturn;
2352 /* alcSetThreadContext
2354 * Makes the given Context the active Context for the current thread
2356 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2358 ALboolean bReturn = AL_TRUE;
2359 ALCcontext *old;
2361 // context must be a valid Context or NULL
2362 old = pthread_getspecific(LocalContext);
2363 if(old != context)
2365 LockLists();
2366 if(context == NULL || IsContext(context))
2368 if(context) ALCcontext_IncRef(context);
2369 pthread_setspecific(LocalContext, context);
2370 if(old) ALCcontext_DecRef(old);
2372 else
2374 alcSetError(NULL, ALC_INVALID_CONTEXT);
2375 bReturn = AL_FALSE;
2377 UnlockLists();
2380 return bReturn;
2384 /* alcGetContextsDevice
2386 * Returns the Device that a particular Context is attached to
2388 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *pContext)
2390 ALCdevice *pDevice = NULL;
2392 LockLists();
2393 if(IsContext(pContext))
2394 pDevice = pContext->Device;
2395 else
2396 alcSetError(NULL, ALC_INVALID_CONTEXT);
2397 UnlockLists();
2399 return pDevice;
2403 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2405 static const struct {
2406 const char name[32];
2407 enum DevFmtChannels channels;
2408 enum DevFmtType type;
2409 } formats[] = {
2410 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2411 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2412 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2413 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2414 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2415 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2417 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2418 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2419 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2420 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2421 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2422 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2424 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2425 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2426 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2427 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2428 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2429 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2431 size_t i;
2433 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2435 if(strcasecmp(str, formats[i].name) == 0)
2437 *chans = formats[i].channels;
2438 *type = formats[i].type;
2439 return;
2443 ERR("Unknown format: \"%s\"\n", str);
2444 *chans = DevFmtStereo;
2445 *type = DevFmtShort;
2448 /* alcOpenDevice
2450 * Open the Device specified.
2452 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2454 const ALCchar *fmt;
2455 ALCdevice *device;
2456 ALCenum err;
2458 DO_INITCONFIG();
2460 if(!PlaybackBackend.name)
2462 alcSetError(NULL, ALC_INVALID_VALUE);
2463 return NULL;
2466 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2467 deviceName = NULL;
2469 device = calloc(1, sizeof(ALCdevice));
2470 if(!device)
2472 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2473 return NULL;
2476 //Validate device
2477 device->Funcs = &PlaybackBackend.Funcs;
2478 device->ref = 1;
2479 device->Connected = ALC_TRUE;
2480 device->IsCaptureDevice = AL_FALSE;
2481 device->IsLoopbackDevice = AL_FALSE;
2482 InitializeCriticalSection(&device->Mutex);
2483 device->LastError = ALC_NO_ERROR;
2485 device->Flags = 0;
2486 device->Bs2b = NULL;
2487 device->szDeviceName = NULL;
2489 device->ContextList = NULL;
2491 InitUIntMap(&device->BufferMap, ~0);
2492 InitUIntMap(&device->EffectMap, ~0);
2493 InitUIntMap(&device->FilterMap, ~0);
2495 //Set output format
2496 if(ConfigValueExists(NULL, "frequency"))
2497 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2498 device->Frequency = GetConfigValueInt(NULL, "frequency", DEFAULT_OUTPUT_RATE);
2499 if(device->Frequency < 8000)
2500 device->Frequency = 8000;
2502 if(ConfigValueExists(NULL, "format"))
2503 device->Flags |= DEVICE_CHANNELS_REQUEST;
2504 fmt = GetConfigValue(NULL, "format", "AL_FORMAT_STEREO16");
2505 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2507 device->NumUpdates = GetConfigValueInt(NULL, "periods", 4);
2508 if(device->NumUpdates < 2)
2509 device->NumUpdates = 4;
2511 device->UpdateSize = GetConfigValueInt(NULL, "period_size", 1024);
2512 if(device->UpdateSize <= 0)
2513 device->UpdateSize = 1024;
2515 device->MaxNoOfSources = GetConfigValueInt(NULL, "sources", 256);
2516 if(device->MaxNoOfSources <= 0)
2517 device->MaxNoOfSources = 256;
2519 device->AuxiliaryEffectSlotMax = GetConfigValueInt(NULL, "slots", 4);
2520 if(device->AuxiliaryEffectSlotMax <= 0)
2521 device->AuxiliaryEffectSlotMax = 4;
2523 device->NumStereoSources = 1;
2524 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2526 device->NumAuxSends = GetConfigValueInt(NULL, "sends", MAX_SENDS);
2527 if(device->NumAuxSends > MAX_SENDS)
2528 device->NumAuxSends = MAX_SENDS;
2530 device->Bs2bLevel = GetConfigValueInt(NULL, "cf_level", 0);
2532 // Find a playback device to open
2533 LockLists();
2534 if((err=ALCdevice_OpenPlayback(device, deviceName)) == ALC_NO_ERROR)
2536 device->next = g_pDeviceList;
2537 g_pDeviceList = device;
2538 g_ulDeviceCount++;
2540 else
2542 // No suitable output device found
2543 DeleteCriticalSection(&device->Mutex);
2544 free(device);
2545 device = NULL;
2546 alcSetError(NULL, err);
2548 UnlockLists();
2550 return device;
2553 /* alcCloseDevice
2555 * Close the specified Device
2557 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2559 ALCdevice **list;
2560 ALCcontext *ctx;
2562 LockLists();
2563 list = &g_pDeviceList;
2564 while(*list && *list != pDevice)
2565 list = &(*list)->next;
2567 if(!*list || (*list)->IsCaptureDevice)
2569 alcSetError(*list, ALC_INVALID_DEVICE);
2570 UnlockLists();
2571 return ALC_FALSE;
2574 *list = (*list)->next;
2575 g_ulDeviceCount--;
2576 UnlockLists();
2578 if((ctx=pDevice->ContextList) != NULL)
2580 do {
2581 WARN("Destroying context %p\n", ctx);
2582 ReleaseContext(ctx, pDevice);
2583 } while((ctx=pDevice->ContextList) != NULL);
2584 ALCdevice_StopPlayback(pDevice);
2585 pDevice->Flags &= ~DEVICE_RUNNING;
2587 ALCdevice_ClosePlayback(pDevice);
2589 ALCdevice_DecRef(pDevice);
2591 return ALC_TRUE;
2595 /* alcLoopbackOpenDeviceSOFT
2597 * Open a loopback device, for manual rendering.
2599 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2601 ALCdevice *device;
2603 DO_INITCONFIG();
2605 device = calloc(1, sizeof(ALCdevice));
2606 if(!device)
2608 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2609 return NULL;
2612 //Validate device
2613 device->Funcs = &BackendLoopback.Funcs;
2614 device->ref = 1;
2615 device->Connected = ALC_TRUE;
2616 device->IsCaptureDevice = AL_FALSE;
2617 device->IsLoopbackDevice = AL_TRUE;
2618 InitializeCriticalSection(&device->Mutex);
2619 device->LastError = ALC_NO_ERROR;
2621 device->Flags = 0;
2622 device->Bs2b = NULL;
2623 device->szDeviceName = NULL;
2625 device->ContextList = NULL;
2627 InitUIntMap(&device->BufferMap, ~0);
2628 InitUIntMap(&device->EffectMap, ~0);
2629 InitUIntMap(&device->FilterMap, ~0);
2631 //Set output format
2632 device->Frequency = 44100;
2633 device->FmtChans = DevFmtStereo;
2634 device->FmtType = DevFmtShort;
2636 device->NumUpdates = 0;
2637 device->UpdateSize = 0;
2639 device->MaxNoOfSources = GetConfigValueInt(NULL, "sources", 256);
2640 if(device->MaxNoOfSources <= 0)
2641 device->MaxNoOfSources = 256;
2643 device->AuxiliaryEffectSlotMax = GetConfigValueInt(NULL, "slots", 4);
2644 if(device->AuxiliaryEffectSlotMax <= 0)
2645 device->AuxiliaryEffectSlotMax = 4;
2647 device->NumStereoSources = 1;
2648 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2650 device->NumAuxSends = GetConfigValueInt(NULL, "sends", MAX_SENDS);
2651 if(device->NumAuxSends > MAX_SENDS)
2652 device->NumAuxSends = MAX_SENDS;
2654 device->Bs2bLevel = GetConfigValueInt(NULL, "cf_level", 0);
2656 // Open the "backend"
2657 LockLists();
2658 ALCdevice_OpenPlayback(device, "Loopback");
2660 device->next = g_pDeviceList;
2661 g_pDeviceList = device;
2662 g_ulDeviceCount++;
2663 UnlockLists();
2665 return device;
2668 /* alcIsRenderFormatSupportedSOFT
2670 * Determines if the loopback device supports the given format for rendering.
2672 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2674 ALCboolean ret = ALC_FALSE;
2676 LockLists();
2677 if(!IsDevice(device))
2678 alcSetError(NULL, ALC_INVALID_DEVICE);
2679 else if(!device->IsLoopbackDevice)
2680 alcSetError(device, ALC_INVALID_DEVICE);
2681 else if(freq <= 0)
2682 alcSetError(device, ALC_INVALID_VALUE);
2683 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2684 alcSetError(device, ALC_INVALID_ENUM);
2685 else
2687 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2688 freq >= 8000)
2689 ret = ALC_TRUE;
2691 UnlockLists();
2693 return ret;
2696 /* alcRenderSamplesSOFT
2698 * Renders some samples into a buffer, using the format last set by the
2699 * attributes given to alcCreateContext.
2701 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2703 LockLists();
2704 if(!IsDevice(device))
2705 alcSetError(NULL, ALC_INVALID_DEVICE);
2706 else if(!device->IsLoopbackDevice)
2707 alcSetError(device, ALC_INVALID_DEVICE);
2708 else if(samples < 0 || (samples > 0 && buffer == NULL))
2709 alcSetError(device, ALC_INVALID_VALUE);
2710 else
2711 aluMixData(device, buffer, samples);
2712 UnlockLists();
2716 static void ReleaseALC(ALCboolean doclose)
2718 free(alcDeviceList); alcDeviceList = NULL;
2719 alcDeviceListSize = 0;
2720 free(alcAllDeviceList); alcAllDeviceList = NULL;
2721 alcAllDeviceListSize = 0;
2722 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2723 alcCaptureDeviceListSize = 0;
2725 free(alcDefaultDeviceSpecifier);
2726 alcDefaultDeviceSpecifier = NULL;
2727 free(alcDefaultAllDeviceSpecifier);
2728 alcDefaultAllDeviceSpecifier = NULL;
2729 free(alcCaptureDefaultDeviceSpecifier);
2730 alcCaptureDefaultDeviceSpecifier = NULL;
2732 if(doclose)
2734 if(g_ulDeviceCount > 0)
2735 WARN("Closing %u device%s\n", g_ulDeviceCount, (g_ulDeviceCount>1)?"s":"");
2737 while(g_pDeviceList)
2739 if(g_pDeviceList->IsCaptureDevice)
2740 alcCaptureCloseDevice(g_pDeviceList);
2741 else
2742 alcCloseDevice(g_pDeviceList);
2745 else
2747 if(g_ulDeviceCount > 0)
2748 WARN("%u device%s not closed\n", g_ulDeviceCount, (g_ulDeviceCount>1)?"s":"");
2752 ///////////////////////////////////////////////////////