Use raise(SIGTRAP) instead of kill(getpid(),SIGTRAP)
[openal-soft/android.git] / Alc / ALc.c
blob0f7d48c30478de72d53fef842c2a5aaef757e658
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 *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_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 AL_EXT_IMA4 "
377 "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_SOFTX_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 ///////////////////////////////////////////////////////
405 ///////////////////////////////////////////////////////
406 // ALC Related helper functions
407 static void ReleaseALC(ALCboolean doclose);
408 static void ReleaseThreadCtx(void *ptr);
410 static void alc_initconfig(void);
411 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
413 #if defined(_WIN32)
414 static void alc_init(void);
415 static void alc_deinit(void);
416 static void alc_deinit_safe(void);
418 #ifndef AL_LIBTYPE_STATIC
419 UIntMap TlsDestructor;
421 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
423 ALsizei i;
424 (void)hModule;
426 // Perform actions based on the reason for calling.
427 switch(ul_reason_for_call)
429 case DLL_PROCESS_ATTACH:
430 InitUIntMap(&TlsDestructor, ~0);
431 alc_init();
432 break;
434 case DLL_THREAD_DETACH:
435 LockUIntMapRead(&TlsDestructor);
436 for(i = 0;i < TlsDestructor.size;i++)
438 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
439 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
440 if(ptr && callback)
441 callback(ptr);
443 UnlockUIntMapRead(&TlsDestructor);
444 break;
446 case DLL_PROCESS_DETACH:
447 if(!lpReserved)
448 alc_deinit();
449 else
450 alc_deinit_safe();
451 ResetUIntMap(&TlsDestructor);
452 break;
454 return TRUE;
456 #elif defined(_MSC_VER)
457 #pragma section(".CRT$XCU",read)
458 static void alc_constructor(void);
459 static void alc_destructor(void);
460 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
462 static void alc_constructor(void)
464 atexit(alc_destructor);
465 alc_init();
468 static void alc_destructor(void)
470 alc_deinit();
472 #elif defined(HAVE_GCC_DESTRUCTOR)
473 static void alc_init(void) __attribute__((constructor));
474 static void alc_deinit(void) __attribute__((destructor));
475 #else
476 #error "No static initialization available on this platform!"
477 #endif
478 #elif defined(HAVE_GCC_DESTRUCTOR)
479 static void alc_init(void) __attribute__((constructor));
480 static void alc_deinit(void) __attribute__((destructor));
481 #else
482 #error "No global initialization available on this platform!"
483 #endif
485 static void alc_init(void)
487 const char *str;
489 LogFile = stderr;
491 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
492 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
493 ConeScale = 1.0f;
495 str = getenv("__ALSOFT_REVERSE_Z");
496 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
497 ZScale = -1.0f;
499 str = getenv("__ALSOFT_TRAP_ERROR");
500 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
502 TrapALError = AL_TRUE;
503 TrapALCError = AL_TRUE;
505 else
507 str = getenv("__ALSOFT_TRAP_AL_ERROR");
508 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
509 TrapALError = AL_TRUE;
511 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
512 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
513 TrapALCError = ALC_TRUE;
516 pthread_key_create(&LocalContext, ReleaseThreadCtx);
517 InitializeCriticalSection(&ListLock);
518 ThunkInit();
521 static void alc_deinit_safe(void)
523 ReleaseALC(ALC_FALSE);
525 FreeHrtf();
526 FreeALConfig();
528 ThunkExit();
529 DeleteCriticalSection(&ListLock);
530 pthread_key_delete(LocalContext);
532 if(LogFile != stderr)
533 fclose(LogFile);
534 LogFile = NULL;
537 static void alc_deinit(void)
539 int i;
541 ReleaseALC(ALC_TRUE);
543 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
544 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
546 for(i = 0;BackendList[i].Deinit;i++)
547 BackendList[i].Deinit();
548 BackendLoopback.Deinit();
550 alc_deinit_safe();
553 static void alc_initconfig(void)
555 const char *devs, *str;
556 float valf;
557 int i, n;
559 str = getenv("ALSOFT_LOGLEVEL");
560 if(str)
562 long lvl = strtol(str, NULL, 0);
563 if(lvl >= NoLog && lvl <= LogRef)
564 LogLevel = lvl;
567 str = getenv("ALSOFT_LOGFILE");
568 if(str && str[0])
570 FILE *logfile = fopen(str, "wat");
571 if(logfile) LogFile = logfile;
572 else ERR("Failed to open log file '%s'\n", str);
575 ReadALConfig();
577 InitHrtf();
579 #ifdef _WIN32
580 RTPrioLevel = 1;
581 #else
582 RTPrioLevel = 0;
583 #endif
584 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
586 if(ConfigValueInt(NULL, "resampler", &n))
588 if(n < RESAMPLER_MAX && n > RESAMPLER_MIN)
589 DefaultResampler = n;
592 if(!TrapALCError)
593 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
595 if(!TrapALError)
596 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
598 if(ConfigValueFloat("reverb", "boost", &valf))
599 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
601 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
603 if(ConfigValueStr(NULL, "drivers", &devs))
605 int n;
606 size_t len;
607 const char *next = devs;
608 int endlist, delitem;
610 i = 0;
611 do {
612 devs = next;
613 next = strchr(devs, ',');
615 delitem = (devs[0] == '-');
616 if(devs[0] == '-') devs++;
618 if(!devs[0] || devs[0] == ',')
620 endlist = 0;
621 continue;
623 endlist = 1;
625 len = (next ? ((size_t)(next-devs)) : strlen(devs));
626 for(n = i;BackendList[n].Init;n++)
628 if(len == strlen(BackendList[n].name) &&
629 strncmp(BackendList[n].name, devs, len) == 0)
631 if(delitem)
633 do {
634 BackendList[n] = BackendList[n+1];
635 ++n;
636 } while(BackendList[n].Init);
638 else
640 struct BackendInfo Bkp = BackendList[n];
641 while(n > i)
643 BackendList[n] = BackendList[n-1];
644 --n;
646 BackendList[n] = Bkp;
648 i++;
650 break;
653 } while(next++);
655 if(endlist)
657 BackendList[i].name = NULL;
658 BackendList[i].Init = NULL;
659 BackendList[i].Deinit = NULL;
660 BackendList[i].Probe = NULL;
664 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
666 if(!BackendList[i].Init(&BackendList[i].Funcs))
668 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
669 continue;
672 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
673 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
675 PlaybackBackend = BackendList[i];
676 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
678 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
680 CaptureBackend = BackendList[i];
681 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
684 BackendLoopback.Init(&BackendLoopback.Funcs);
686 if(ConfigValueStr(NULL, "excludefx", &str))
688 size_t len;
689 const char *next = str;
691 do {
692 str = next;
693 next = strchr(str, ',');
695 if(!str[0] || next == str)
696 continue;
698 len = (next ? ((size_t)(next-str)) : strlen(str));
699 for(n = 0;EffectList[n].name;n++)
701 if(len == strlen(EffectList[n].name) &&
702 strncmp(EffectList[n].name, str, len) == 0)
703 DisabledEffects[EffectList[n].type] = AL_TRUE;
705 } while(next++);
710 static void LockLists(void)
712 EnterCriticalSection(&ListLock);
715 static void UnlockLists(void)
717 LeaveCriticalSection(&ListLock);
721 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
723 DO_INITCONFIG();
725 LockLists();
726 free(*list);
727 *list = NULL;
728 *listsize = 0;
730 if(type == CAPTURE_DEVICE_PROBE)
731 CaptureBackend.Probe(type);
732 else
733 PlaybackBackend.Probe(type);
734 UnlockLists();
737 static void ProbeDeviceList(void)
738 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
739 static void ProbeAllDeviceList(void)
740 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
741 static void ProbeCaptureDeviceList(void)
742 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
745 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
747 size_t len = strlen(name);
748 void *temp;
750 if(len == 0)
751 return;
753 temp = realloc(*List, (*ListSize) + len + 2);
754 if(!temp)
756 ERR("Realloc failed to add %s!\n", name);
757 return;
759 *List = temp;
761 memcpy((*List)+(*ListSize), name, len+1);
762 *ListSize += len+1;
763 (*List)[*ListSize] = 0;
766 #define DECL_APPEND_LIST_FUNC(type) \
767 void Append##type##List(const ALCchar *name) \
768 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
770 DECL_APPEND_LIST_FUNC(Device)
771 DECL_APPEND_LIST_FUNC(AllDevice)
772 DECL_APPEND_LIST_FUNC(CaptureDevice)
774 #undef DECL_APPEND_LIST_FUNC
777 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
778 void SetDefaultChannelOrder(ALCdevice *device)
780 switch(device->FmtChans)
782 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
783 device->DevChannels[1] = FRONT_RIGHT;
784 device->DevChannels[2] = BACK_LEFT;
785 device->DevChannels[3] = BACK_RIGHT;
786 device->DevChannels[4] = FRONT_CENTER;
787 device->DevChannels[5] = LFE;
788 return;
790 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
791 device->DevChannels[1] = FRONT_RIGHT;
792 device->DevChannels[2] = BACK_LEFT;
793 device->DevChannels[3] = BACK_RIGHT;
794 device->DevChannels[4] = FRONT_CENTER;
795 device->DevChannels[5] = LFE;
796 device->DevChannels[6] = SIDE_LEFT;
797 device->DevChannels[7] = SIDE_RIGHT;
798 return;
800 /* Same as WFX order */
801 case DevFmtMono:
802 case DevFmtStereo:
803 case DevFmtQuad:
804 case DevFmtX51Side:
805 case DevFmtX61:
806 break;
808 SetDefaultWFXChannelOrder(device);
810 /* Sets the default order used by WaveFormatEx */
811 void SetDefaultWFXChannelOrder(ALCdevice *device)
813 switch(device->FmtChans)
815 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
817 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
818 device->DevChannels[1] = FRONT_RIGHT; break;
820 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
821 device->DevChannels[1] = FRONT_RIGHT;
822 device->DevChannels[2] = BACK_LEFT;
823 device->DevChannels[3] = BACK_RIGHT; break;
825 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
826 device->DevChannels[1] = FRONT_RIGHT;
827 device->DevChannels[2] = FRONT_CENTER;
828 device->DevChannels[3] = LFE;
829 device->DevChannels[4] = BACK_LEFT;
830 device->DevChannels[5] = BACK_RIGHT; break;
832 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
833 device->DevChannels[1] = FRONT_RIGHT;
834 device->DevChannels[2] = FRONT_CENTER;
835 device->DevChannels[3] = LFE;
836 device->DevChannels[4] = SIDE_LEFT;
837 device->DevChannels[5] = SIDE_RIGHT; break;
839 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
840 device->DevChannels[1] = FRONT_RIGHT;
841 device->DevChannels[2] = FRONT_CENTER;
842 device->DevChannels[3] = LFE;
843 device->DevChannels[4] = BACK_CENTER;
844 device->DevChannels[5] = SIDE_LEFT;
845 device->DevChannels[6] = SIDE_RIGHT; break;
847 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
848 device->DevChannels[1] = FRONT_RIGHT;
849 device->DevChannels[2] = FRONT_CENTER;
850 device->DevChannels[3] = LFE;
851 device->DevChannels[4] = BACK_LEFT;
852 device->DevChannels[5] = BACK_RIGHT;
853 device->DevChannels[6] = SIDE_LEFT;
854 device->DevChannels[7] = SIDE_RIGHT; break;
859 const ALCchar *DevFmtTypeString(enum DevFmtType type)
861 switch(type)
863 case DevFmtByte: return "Signed Byte";
864 case DevFmtUByte: return "Unsigned Byte";
865 case DevFmtShort: return "Signed Short";
866 case DevFmtUShort: return "Unsigned Short";
867 case DevFmtFloat: return "Float";
869 return "(unknown type)";
871 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
873 switch(chans)
875 case DevFmtMono: return "Mono";
876 case DevFmtStereo: return "Stereo";
877 case DevFmtQuad: return "Quadraphonic";
878 case DevFmtX51: return "5.1 Surround";
879 case DevFmtX51Side: return "5.1 Side";
880 case DevFmtX61: return "6.1 Surround";
881 case DevFmtX71: return "7.1 Surround";
883 return "(unknown channels)";
886 ALuint BytesFromDevFmt(enum DevFmtType type)
888 switch(type)
890 case DevFmtByte: return sizeof(ALbyte);
891 case DevFmtUByte: return sizeof(ALubyte);
892 case DevFmtShort: return sizeof(ALshort);
893 case DevFmtUShort: return sizeof(ALushort);
894 case DevFmtFloat: return sizeof(ALfloat);
896 return 0;
898 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
900 switch(chans)
902 case DevFmtMono: return 1;
903 case DevFmtStereo: return 2;
904 case DevFmtQuad: return 4;
905 case DevFmtX51: return 6;
906 case DevFmtX51Side: return 6;
907 case DevFmtX61: return 7;
908 case DevFmtX71: return 8;
910 return 0;
912 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
913 enum DevFmtType *type)
915 static const struct {
916 ALenum format;
917 enum DevFmtChannels channels;
918 enum DevFmtType type;
919 } list[] = {
920 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
921 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
922 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
924 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
925 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
926 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
928 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
929 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
930 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
932 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
933 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
934 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
936 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
937 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
938 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
940 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
941 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
942 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
944 ALuint i;
946 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
948 if(list[i].format == format)
950 *chans = list[i].channels;
951 *type = list[i].type;
952 return AL_TRUE;
956 return AL_FALSE;
959 static ALCboolean IsValidALCType(ALCenum type)
961 switch(type)
963 case ALC_BYTE:
964 case ALC_UNSIGNED_BYTE:
965 case ALC_SHORT:
966 case ALC_UNSIGNED_SHORT:
967 case ALC_INT:
968 case ALC_UNSIGNED_INT:
969 case ALC_FLOAT:
970 return ALC_TRUE;
972 return ALC_FALSE;
975 static ALCboolean IsValidALCChannels(ALCenum channels)
977 switch(channels)
979 case ALC_MONO:
980 case ALC_STEREO:
981 case ALC_QUAD:
982 case ALC_5POINT1:
983 case ALC_6POINT1:
984 case ALC_7POINT1:
985 return ALC_TRUE;
987 return ALC_FALSE;
991 /* alcSetError
993 * Stores the latest ALC Error
995 static void alcSetError(ALCdevice *device, ALCenum errorCode)
997 if(TrapALCError)
999 #ifdef _WIN32
1000 /* DebugBreak() will cause an exception if there is no debugger */
1001 if(IsDebuggerPresent())
1002 DebugBreak();
1003 #elif defined(SIGTRAP)
1004 raise(SIGTRAP);
1005 #endif
1008 if(device)
1009 device->LastError = errorCode;
1010 else
1011 g_eLastNullDeviceError = errorCode;
1015 /* UpdateDeviceParams
1017 * Updates device parameters according to the attribute list (caller is
1018 * responsible for holding the list lock).
1020 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1022 ALCcontext *context;
1023 int oldMode;
1024 ALuint i;
1026 // Check for attributes
1027 if(attrList && attrList[0])
1029 ALCuint freq, numMono, numStereo, numSends;
1030 enum DevFmtChannels schans;
1031 enum DevFmtType stype;
1032 ALuint attrIdx;
1034 // If a context is already running on the device, stop playback so the
1035 // device attributes can be updated
1036 if((device->Flags&DEVICE_RUNNING))
1037 ALCdevice_StopPlayback(device);
1038 device->Flags &= ~DEVICE_RUNNING;
1040 freq = device->Frequency;
1041 schans = device->FmtChans;
1042 stype = device->FmtType;
1043 numMono = device->NumMonoSources;
1044 numStereo = device->NumStereoSources;
1045 numSends = device->NumAuxSends;
1047 attrIdx = 0;
1048 while(attrList[attrIdx])
1050 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1051 device->IsLoopbackDevice)
1053 ALCint val = attrList[attrIdx + 1];
1054 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1056 alcSetError(device, ALC_INVALID_VALUE);
1057 return ALC_FALSE;
1059 schans = val;
1062 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1063 device->IsLoopbackDevice)
1065 ALCint val = attrList[attrIdx + 1];
1066 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1068 alcSetError(device, ALC_INVALID_VALUE);
1069 return ALC_FALSE;
1071 stype = val;
1074 if(attrList[attrIdx] == ALC_FREQUENCY)
1076 if(device->IsLoopbackDevice)
1078 freq = attrList[attrIdx + 1];
1079 if(freq < 8000)
1081 alcSetError(device, ALC_INVALID_VALUE);
1082 return ALC_FALSE;
1085 else
1087 freq = attrList[attrIdx + 1];
1088 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1092 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1094 numStereo = attrList[attrIdx + 1];
1095 if(numStereo > device->MaxNoOfSources)
1096 numStereo = device->MaxNoOfSources;
1098 numMono = device->MaxNoOfSources - numStereo;
1101 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1102 numSends = attrList[attrIdx + 1];
1104 attrIdx += 2;
1107 if(!device->IsLoopbackDevice)
1109 ConfigValueUInt(NULL, "frequency", &freq);
1110 freq = maxu(freq, 8000);
1112 ConfigValueUInt(NULL, "sends", &numSends);
1113 numSends = minu(MAX_SENDS, numSends);
1115 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1116 device->Frequency;
1118 device->Frequency = freq;
1119 device->FmtChans = schans;
1120 device->FmtType = stype;
1121 device->NumMonoSources = numMono;
1122 device->NumStereoSources = numStereo;
1123 device->NumAuxSends = numSends;
1126 if((device->Flags&DEVICE_RUNNING))
1127 return ALC_TRUE;
1129 LockDevice(device);
1130 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1131 DevFmtChannelsString(device->FmtChans),
1132 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1133 DevFmtTypeString(device->FmtType), device->Frequency,
1134 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1135 device->UpdateSize, device->NumUpdates);
1136 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1138 UnlockDevice(device);
1139 return ALC_FALSE;
1141 device->Flags |= DEVICE_RUNNING;
1142 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1143 DevFmtChannelsString(device->FmtChans),
1144 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1145 DevFmtTypeString(device->FmtType), device->Frequency,
1146 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1147 device->UpdateSize, device->NumUpdates);
1149 aluInitPanning(device);
1151 for(i = 0;i < MAXCHANNELS;i++)
1153 device->ClickRemoval[i] = 0.0f;
1154 device->PendingClicks[i] = 0.0f;
1157 device->Hrtf = NULL;
1158 device->Flags &= ~DEVICE_USE_HRTF;
1159 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1160 device->Flags |= DEVICE_USE_HRTF;
1161 if((device->Flags&DEVICE_USE_HRTF) && !(device->Hrtf=GetHrtf(device)))
1162 device->Flags &= ~DEVICE_USE_HRTF;
1163 TRACE("HRTF %s\n", (device->Flags&DEVICE_USE_HRTF)?"enabled":"disabled");
1165 if(!(device->Flags&DEVICE_USE_HRTF) && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1167 if(!device->Bs2b)
1169 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1170 bs2b_clear(device->Bs2b);
1172 bs2b_set_srate(device->Bs2b, device->Frequency);
1173 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1174 TRACE("BS2B level %d\n", device->Bs2bLevel);
1176 else
1178 free(device->Bs2b);
1179 device->Bs2b = NULL;
1180 TRACE("BS2B disabled\n");
1183 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1184 switch(device->FmtChans)
1186 case DevFmtMono:
1187 case DevFmtStereo:
1188 break;
1189 case DevFmtQuad:
1190 case DevFmtX51:
1191 case DevFmtX51Side:
1192 case DevFmtX61:
1193 case DevFmtX71:
1194 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1195 device->Flags |= DEVICE_DUPLICATE_STEREO;
1196 break;
1198 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1200 oldMode = SetMixerFPUMode();
1201 context = device->ContextList;
1202 while(context)
1204 ALsizei pos;
1206 context->UpdateSources = AL_FALSE;
1207 LockUIntMapRead(&context->EffectSlotMap);
1208 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1210 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1212 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1214 UnlockUIntMapRead(&context->EffectSlotMap);
1215 UnlockDevice(device);
1216 ALCdevice_StopPlayback(device);
1217 device->Flags &= ~DEVICE_RUNNING;
1218 return ALC_FALSE;
1220 slot->NeedsUpdate = AL_FALSE;
1221 ALeffectState_Update(slot->EffectState, context, slot);
1223 UnlockUIntMapRead(&context->EffectSlotMap);
1225 LockUIntMapRead(&context->SourceMap);
1226 for(pos = 0;pos < context->SourceMap.size;pos++)
1228 ALsource *source = context->SourceMap.array[pos].value;
1229 ALuint s = device->NumAuxSends;
1230 while(s < MAX_SENDS)
1232 if(source->Send[s].Slot)
1233 DecrementRef(&source->Send[s].Slot->ref);
1234 source->Send[s].Slot = NULL;
1235 source->Send[s].WetGain = 1.0f;
1236 source->Send[s].WetGainHF = 1.0f;
1237 s++;
1239 source->NeedsUpdate = AL_FALSE;
1240 ALsource_Update(source, context);
1242 UnlockUIntMapRead(&context->SourceMap);
1244 context = context->next;
1246 RestoreFPUMode(oldMode);
1247 UnlockDevice(device);
1249 return ALC_TRUE;
1252 /* FreeDevice
1254 * Frees the device structure, and destroys any objects the app failed to
1255 * delete. Called once there's no more references on the device.
1257 static ALCvoid FreeDevice(ALCdevice *device)
1259 TRACE("%p\n", device);
1261 if(device->BufferMap.size > 0)
1263 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1264 ReleaseALBuffers(device);
1266 ResetUIntMap(&device->BufferMap);
1268 if(device->EffectMap.size > 0)
1270 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1271 ReleaseALEffects(device);
1273 ResetUIntMap(&device->EffectMap);
1275 if(device->FilterMap.size > 0)
1277 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1278 ReleaseALFilters(device);
1280 ResetUIntMap(&device->FilterMap);
1282 free(device->Bs2b);
1283 device->Bs2b = NULL;
1285 free(device->szDeviceName);
1286 device->szDeviceName = NULL;
1288 DeleteCriticalSection(&device->Mutex);
1290 free(device);
1294 void ALCdevice_IncRef(ALCdevice *device)
1296 RefCount ref;
1297 ref = IncrementRef(&device->ref);
1298 TRACEREF("%p increasing refcount to %u\n", device, ref);
1301 void ALCdevice_DecRef(ALCdevice *device)
1303 RefCount ref;
1304 ref = DecrementRef(&device->ref);
1305 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1306 if(ref == 0) FreeDevice(device);
1309 /* VerifyDevice
1311 * Checks if the device handle is valid, and increments its ref count if so.
1313 static ALCdevice *VerifyDevice(ALCdevice *device)
1315 ALCdevice *tmpDevice;
1317 if(!device)
1318 return NULL;
1320 LockLists();
1321 tmpDevice = DeviceList;
1322 while(tmpDevice && tmpDevice != device)
1323 tmpDevice = tmpDevice->next;
1325 if(tmpDevice)
1326 ALCdevice_IncRef(tmpDevice);
1327 UnlockLists();
1328 return tmpDevice;
1332 ALCvoid LockDevice(ALCdevice *device)
1334 EnterCriticalSection(&device->Mutex);
1337 ALCvoid UnlockDevice(ALCdevice *device)
1339 LeaveCriticalSection(&device->Mutex);
1343 /* InitContext
1345 * Initializes context variables
1347 static ALvoid InitContext(ALCcontext *pContext)
1349 //Initialise listener
1350 pContext->Listener.Gain = 1.0f;
1351 pContext->Listener.MetersPerUnit = 1.0f;
1352 pContext->Listener.Position[0] = 0.0f;
1353 pContext->Listener.Position[1] = 0.0f;
1354 pContext->Listener.Position[2] = 0.0f;
1355 pContext->Listener.Velocity[0] = 0.0f;
1356 pContext->Listener.Velocity[1] = 0.0f;
1357 pContext->Listener.Velocity[2] = 0.0f;
1358 pContext->Listener.Forward[0] = 0.0f;
1359 pContext->Listener.Forward[1] = 0.0f;
1360 pContext->Listener.Forward[2] = -1.0f;
1361 pContext->Listener.Up[0] = 0.0f;
1362 pContext->Listener.Up[1] = 1.0f;
1363 pContext->Listener.Up[2] = 0.0f;
1365 //Validate pContext
1366 pContext->LastError = AL_NO_ERROR;
1367 pContext->UpdateSources = AL_FALSE;
1368 pContext->ActiveSourceCount = 0;
1369 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1370 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1372 //Set globals
1373 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1374 pContext->SourceDistanceModel = AL_FALSE;
1375 pContext->DopplerFactor = 1.0f;
1376 pContext->DopplerVelocity = 1.0f;
1377 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1378 pContext->DeferUpdates = AL_FALSE;
1380 pContext->ExtensionList = alExtList;
1384 /* FreeContext
1386 * Cleans up the context, and destroys any remaining objects the app failed to
1387 * delete. Called once there's no more references on the context.
1389 static ALCvoid FreeContext(ALCcontext *context)
1391 TRACE("%p\n", context);
1393 if(context->SourceMap.size > 0)
1395 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1396 ReleaseALSources(context);
1398 ResetUIntMap(&context->SourceMap);
1400 if(context->EffectSlotMap.size > 0)
1402 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1403 ReleaseALAuxiliaryEffectSlots(context);
1405 ResetUIntMap(&context->EffectSlotMap);
1407 context->ActiveSourceCount = 0;
1408 free(context->ActiveSources);
1409 context->ActiveSources = NULL;
1410 context->MaxActiveSources = 0;
1412 context->ActiveEffectSlotCount = 0;
1413 free(context->ActiveEffectSlots);
1414 context->ActiveEffectSlots = NULL;
1415 context->MaxActiveEffectSlots = 0;
1417 ALCdevice_DecRef(context->Device);
1418 context->Device = NULL;
1420 //Invalidate context
1421 memset(context, 0, sizeof(ALCcontext));
1422 free(context);
1425 /* ReleaseContext
1427 * Removes the context reference from the given device and removes it from
1428 * being current on the running thread or globally.
1430 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1432 ALCcontext *volatile*tmp_ctx;
1434 if(pthread_getspecific(LocalContext) == context)
1436 WARN("%p released while current on thread\n", context);
1437 pthread_setspecific(LocalContext, NULL);
1438 ALCcontext_DecRef(context);
1441 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1443 WARN("%p released while current\n", context);
1444 ALCcontext_DecRef(context);
1447 tmp_ctx = &device->ContextList;
1448 while(*tmp_ctx)
1450 if(*tmp_ctx == context)
1452 *tmp_ctx = context->next;
1453 break;
1455 tmp_ctx = &(*tmp_ctx)->next;
1458 LockDevice(device);
1459 /* Lock the device to make sure the mixer is not using the contexts in the
1460 * list before we go about deleting this one. There should be a more
1461 * efficient way of doing this. */
1462 UnlockDevice(device);
1464 ALCcontext_DecRef(context);
1467 void ALCcontext_IncRef(ALCcontext *context)
1469 RefCount ref;
1470 ref = IncrementRef(&context->ref);
1471 TRACEREF("%p increasing refcount to %u\n", context, ref);
1474 void ALCcontext_DecRef(ALCcontext *context)
1476 RefCount ref;
1477 ref = DecrementRef(&context->ref);
1478 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1479 if(ref == 0) FreeContext(context);
1482 static void ReleaseThreadCtx(void *ptr)
1484 WARN("%p current for thread being destroyed\n", ptr);
1485 ALCcontext_DecRef(ptr);
1488 /* VerifyContext
1490 * Checks that the given context is valid, and increments its reference count.
1492 static ALCcontext *VerifyContext(ALCcontext *context)
1494 ALCdevice *dev;
1496 LockLists();
1497 dev = DeviceList;
1498 while(dev)
1500 ALCcontext *tmp_ctx = dev->ContextList;
1501 while(tmp_ctx)
1503 if(tmp_ctx == context)
1505 ALCcontext_IncRef(tmp_ctx);
1506 UnlockLists();
1507 return tmp_ctx;
1509 tmp_ctx = tmp_ctx->next;
1511 dev = dev->next;
1513 UnlockLists();
1515 return NULL;
1519 ALCvoid LockContext(ALCcontext *context)
1521 EnterCriticalSection(&context->Device->Mutex);
1524 ALCvoid UnlockContext(ALCcontext *context)
1526 LeaveCriticalSection(&context->Device->Mutex);
1529 /* GetContextRef
1531 * Returns the currently active context, and adds a reference without locking
1532 * it.
1534 ALCcontext *GetContextRef(void)
1536 ALCcontext *context;
1538 context = pthread_getspecific(LocalContext);
1539 if(context)
1540 ALCcontext_IncRef(context);
1541 else
1543 LockLists();
1544 context = GlobalContext;
1545 if(context)
1546 ALCcontext_IncRef(context);
1547 UnlockLists();
1550 return context;
1553 ///////////////////////////////////////////////////////
1556 ///////////////////////////////////////////////////////
1557 // ALC Functions calls
1560 // This should probably move to another c file but for now ...
1561 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1563 ALCdevice *device = NULL;
1564 ALCenum err;
1566 DO_INITCONFIG();
1568 if(!CaptureBackend.name)
1570 alcSetError(NULL, ALC_INVALID_VALUE);
1571 return NULL;
1574 if(SampleSize <= 0)
1576 alcSetError(NULL, ALC_INVALID_VALUE);
1577 return NULL;
1580 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1581 deviceName = NULL;
1583 device = calloc(1, sizeof(ALCdevice));
1584 if(!device)
1586 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1587 return NULL;
1590 //Validate device
1591 device->Funcs = &CaptureBackend.Funcs;
1592 device->ref = 1;
1593 device->Connected = ALC_TRUE;
1594 device->IsCaptureDevice = AL_TRUE;
1595 device->IsLoopbackDevice = AL_FALSE;
1596 InitializeCriticalSection(&device->Mutex);
1598 InitUIntMap(&device->BufferMap, ~0);
1599 InitUIntMap(&device->EffectMap, ~0);
1600 InitUIntMap(&device->FilterMap, ~0);
1602 device->szDeviceName = NULL;
1604 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1605 device->Frequency = frequency;
1607 device->Flags |= DEVICE_CHANNELS_REQUEST;
1608 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1610 DeleteCriticalSection(&device->Mutex);
1611 free(device);
1612 alcSetError(NULL, ALC_INVALID_ENUM);
1613 return NULL;
1616 device->UpdateSize = SampleSize;
1617 device->NumUpdates = 1;
1619 LockLists();
1620 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1622 UnlockLists();
1623 DeleteCriticalSection(&device->Mutex);
1624 free(device);
1625 alcSetError(NULL, err);
1626 return NULL;
1628 UnlockLists();
1630 do {
1631 device->next = DeviceList;
1632 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
1634 TRACE("Created device %p\n", device);
1635 return device;
1638 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1640 ALCdevice *volatile*list;
1642 LockLists();
1643 list = &DeviceList;
1644 while(*list && *list != pDevice)
1645 list = &(*list)->next;
1647 if(!*list || !(*list)->IsCaptureDevice)
1649 alcSetError(*list, ALC_INVALID_DEVICE);
1650 UnlockLists();
1651 return ALC_FALSE;
1654 *list = (*list)->next;
1655 UnlockLists();
1657 LockDevice(pDevice);
1658 ALCdevice_CloseCapture(pDevice);
1659 UnlockDevice(pDevice);
1661 ALCdevice_DecRef(pDevice);
1663 return ALC_TRUE;
1666 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1668 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1670 alcSetError(device, ALC_INVALID_DEVICE);
1671 if(device) ALCdevice_DecRef(device);
1672 return;
1674 LockDevice(device);
1675 if(device->Connected)
1676 ALCdevice_StartCapture(device);
1677 UnlockDevice(device);
1679 ALCdevice_DecRef(device);
1682 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1684 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1686 alcSetError(device, ALC_INVALID_DEVICE);
1687 if(device) ALCdevice_DecRef(device);
1688 return;
1690 LockDevice(device);
1691 if(device->Connected)
1692 ALCdevice_StopCapture(device);
1693 UnlockDevice(device);
1695 ALCdevice_DecRef(device);
1698 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1700 ALCenum err = ALC_INVALID_DEVICE;
1701 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1703 err = ALC_INVALID_VALUE;
1704 LockDevice(device);
1705 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1706 err = ALCdevice_CaptureSamples(device, buffer, samples);
1707 UnlockDevice(device);
1709 if(err != ALC_NO_ERROR)
1710 alcSetError(device, err);
1711 if(device) ALCdevice_DecRef(device);
1715 alcGetError
1717 Return last ALC generated error code
1719 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1721 ALCenum errorCode;
1723 if(VerifyDevice(device))
1725 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1726 ALCdevice_DecRef(device);
1728 else
1729 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1731 return errorCode;
1735 /* alcSuspendContext
1737 * Not functional
1739 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1741 (void)Context;
1744 /* alcProcessContext
1746 * Not functional
1748 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1750 (void)Context;
1754 /* alcGetString
1756 * Returns information about the Device, and error strings
1758 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1760 const ALCchar *value = NULL;
1762 switch(param)
1764 case ALC_NO_ERROR:
1765 value = alcNoError;
1766 break;
1768 case ALC_INVALID_ENUM:
1769 value = alcErrInvalidEnum;
1770 break;
1772 case ALC_INVALID_VALUE:
1773 value = alcErrInvalidValue;
1774 break;
1776 case ALC_INVALID_DEVICE:
1777 value = alcErrInvalidDevice;
1778 break;
1780 case ALC_INVALID_CONTEXT:
1781 value = alcErrInvalidContext;
1782 break;
1784 case ALC_OUT_OF_MEMORY:
1785 value = alcErrOutOfMemory;
1786 break;
1788 case ALC_DEVICE_SPECIFIER:
1789 if(VerifyDevice(pDevice))
1791 value = pDevice->szDeviceName;
1792 ALCdevice_DecRef(pDevice);
1794 else
1796 ProbeDeviceList();
1797 value = alcDeviceList;
1799 break;
1801 case ALC_ALL_DEVICES_SPECIFIER:
1802 ProbeAllDeviceList();
1803 value = alcAllDeviceList;
1804 break;
1806 case ALC_CAPTURE_DEVICE_SPECIFIER:
1807 if(VerifyDevice(pDevice))
1809 value = pDevice->szDeviceName;
1810 ALCdevice_DecRef(pDevice);
1812 else
1814 ProbeCaptureDeviceList();
1815 value = alcCaptureDeviceList;
1817 break;
1819 /* Default devices are always first in the list */
1820 case ALC_DEFAULT_DEVICE_SPECIFIER:
1821 if(!alcDeviceList)
1822 ProbeDeviceList();
1824 pDevice = VerifyDevice(pDevice);
1826 free(alcDefaultDeviceSpecifier);
1827 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1828 if(!alcDefaultDeviceSpecifier)
1829 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1831 value = alcDefaultDeviceSpecifier;
1832 if(pDevice) ALCdevice_DecRef(pDevice);
1833 break;
1835 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1836 if(!alcAllDeviceList)
1837 ProbeAllDeviceList();
1839 pDevice = VerifyDevice(pDevice);
1841 free(alcDefaultAllDeviceSpecifier);
1842 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1843 alcAllDeviceList : "");
1844 if(!alcDefaultAllDeviceSpecifier)
1845 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1847 value = alcDefaultAllDeviceSpecifier;
1848 if(pDevice) ALCdevice_DecRef(pDevice);
1849 break;
1851 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1852 if(!alcCaptureDeviceList)
1853 ProbeCaptureDeviceList();
1855 pDevice = VerifyDevice(pDevice);
1857 free(alcCaptureDefaultDeviceSpecifier);
1858 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1859 alcCaptureDeviceList : "");
1860 if(!alcCaptureDefaultDeviceSpecifier)
1861 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1863 value = alcCaptureDefaultDeviceSpecifier;
1864 if(pDevice) ALCdevice_DecRef(pDevice);
1865 break;
1867 case ALC_EXTENSIONS:
1868 if(!VerifyDevice(pDevice))
1869 value = alcNoDeviceExtList;
1870 else
1872 value = alcExtensionList;
1873 ALCdevice_DecRef(pDevice);
1875 break;
1877 default:
1878 pDevice = VerifyDevice(pDevice);
1879 alcSetError(pDevice, ALC_INVALID_ENUM);
1880 if(pDevice) ALCdevice_DecRef(pDevice);
1881 break;
1884 return value;
1888 /* alcGetIntegerv
1890 * Returns information about the Device and the version of Open AL
1892 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1894 device = VerifyDevice(device);
1896 if(size == 0 || data == NULL)
1898 alcSetError(device, ALC_INVALID_VALUE);
1899 if(device) ALCdevice_DecRef(device);
1900 return;
1903 if(!device)
1905 switch(param)
1907 case ALC_MAJOR_VERSION:
1908 *data = alcMajorVersion;
1909 break;
1910 case ALC_MINOR_VERSION:
1911 *data = alcMinorVersion;
1912 break;
1914 case ALC_ATTRIBUTES_SIZE:
1915 case ALC_ALL_ATTRIBUTES:
1916 case ALC_FREQUENCY:
1917 case ALC_REFRESH:
1918 case ALC_SYNC:
1919 case ALC_MONO_SOURCES:
1920 case ALC_STEREO_SOURCES:
1921 case ALC_CAPTURE_SAMPLES:
1922 case ALC_FORMAT_CHANNELS_SOFT:
1923 case ALC_FORMAT_TYPE_SOFT:
1924 alcSetError(NULL, ALC_INVALID_DEVICE);
1925 break;
1927 default:
1928 alcSetError(NULL, ALC_INVALID_ENUM);
1929 break;
1932 else if(device->IsCaptureDevice)
1934 switch(param)
1936 case ALC_CAPTURE_SAMPLES:
1937 LockDevice(device);
1938 *data = ALCdevice_AvailableSamples(device);
1939 UnlockDevice(device);
1940 break;
1942 case ALC_CONNECTED:
1943 *data = device->Connected;
1944 break;
1946 default:
1947 alcSetError(device, ALC_INVALID_ENUM);
1948 break;
1951 else /* render device */
1953 switch(param)
1955 case ALC_MAJOR_VERSION:
1956 *data = alcMajorVersion;
1957 break;
1959 case ALC_MINOR_VERSION:
1960 *data = alcMinorVersion;
1961 break;
1963 case ALC_EFX_MAJOR_VERSION:
1964 *data = alcEFXMajorVersion;
1965 break;
1967 case ALC_EFX_MINOR_VERSION:
1968 *data = alcEFXMinorVersion;
1969 break;
1971 case ALC_ATTRIBUTES_SIZE:
1972 *data = 13;
1973 break;
1975 case ALC_ALL_ATTRIBUTES:
1976 if(size < 13)
1977 alcSetError(device, ALC_INVALID_VALUE);
1978 else
1980 int i = 0;
1982 data[i++] = ALC_FREQUENCY;
1983 data[i++] = device->Frequency;
1985 if(!device->IsLoopbackDevice)
1987 data[i++] = ALC_REFRESH;
1988 data[i++] = device->Frequency / device->UpdateSize;
1990 data[i++] = ALC_SYNC;
1991 data[i++] = ALC_FALSE;
1993 else
1995 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
1996 data[i++] = device->FmtChans;
1998 data[i++] = ALC_FORMAT_TYPE_SOFT;
1999 data[i++] = device->FmtType;
2002 data[i++] = ALC_MONO_SOURCES;
2003 data[i++] = device->NumMonoSources;
2005 data[i++] = ALC_STEREO_SOURCES;
2006 data[i++] = device->NumStereoSources;
2008 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2009 data[i++] = device->NumAuxSends;
2011 data[i++] = 0;
2013 break;
2015 case ALC_FREQUENCY:
2016 *data = device->Frequency;
2017 break;
2019 case ALC_REFRESH:
2020 if(device->IsLoopbackDevice)
2021 alcSetError(device, ALC_INVALID_DEVICE);
2022 else
2023 *data = device->Frequency / device->UpdateSize;
2024 break;
2026 case ALC_SYNC:
2027 if(device->IsLoopbackDevice)
2028 alcSetError(device, ALC_INVALID_DEVICE);
2029 else
2030 *data = ALC_FALSE;
2031 break;
2033 case ALC_FORMAT_CHANNELS_SOFT:
2034 if(!device->IsLoopbackDevice)
2035 alcSetError(device, ALC_INVALID_DEVICE);
2036 else
2037 *data = device->FmtChans;
2038 break;
2040 case ALC_FORMAT_TYPE_SOFT:
2041 if(!device->IsLoopbackDevice)
2042 alcSetError(device, ALC_INVALID_DEVICE);
2043 else
2044 *data = device->FmtType;
2045 break;
2047 case ALC_MONO_SOURCES:
2048 *data = device->NumMonoSources;
2049 break;
2051 case ALC_STEREO_SOURCES:
2052 *data = device->NumStereoSources;
2053 break;
2055 case ALC_MAX_AUXILIARY_SENDS:
2056 *data = device->NumAuxSends;
2057 break;
2059 case ALC_CONNECTED:
2060 *data = device->Connected;
2061 break;
2063 default:
2064 alcSetError(device, ALC_INVALID_ENUM);
2065 break;
2068 if(device)
2069 ALCdevice_DecRef(device);
2073 /* alcIsExtensionPresent
2075 * Determines if there is support for a particular extension
2077 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2079 ALCboolean bResult = ALC_FALSE;
2081 device = VerifyDevice(device);
2083 if(!extName)
2084 alcSetError(device, ALC_INVALID_VALUE);
2085 else
2087 size_t len = strlen(extName);
2088 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2089 while(ptr && *ptr)
2091 if(strncasecmp(ptr, extName, len) == 0 &&
2092 (ptr[len] == '\0' || isspace(ptr[len])))
2094 bResult = ALC_TRUE;
2095 break;
2097 if((ptr=strchr(ptr, ' ')) != NULL)
2099 do {
2100 ++ptr;
2101 } while(isspace(*ptr));
2105 if(device)
2106 ALCdevice_DecRef(device);
2107 return bResult;
2111 /* alcGetProcAddress
2113 * Retrieves the function address for a particular extension function
2115 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2117 ALCvoid *ptr = NULL;
2119 device = VerifyDevice(device);
2121 if(!funcName)
2122 alcSetError(device, ALC_INVALID_VALUE);
2123 else
2125 ALsizei i = 0;
2126 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2127 i++;
2128 ptr = alcFunctions[i].address;
2130 if(device)
2131 ALCdevice_DecRef(device);
2132 return ptr;
2136 /* alcGetEnumValue
2138 * Get the value for a particular ALC Enumerated Value
2140 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2142 ALCenum val = 0;
2144 device = VerifyDevice(device);
2146 if(!enumName)
2147 alcSetError(device, ALC_INVALID_VALUE);
2148 else
2150 ALsizei i = 0;
2151 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2152 i++;
2153 val = enumeration[i].value;
2155 if(device)
2156 ALCdevice_DecRef(device);
2157 return val;
2161 /* alcCreateContext
2163 * Create and attach a Context to a particular Device.
2165 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2167 ALCcontext *ALContext;
2169 LockLists();
2170 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2172 UnlockLists();
2173 alcSetError(device, ALC_INVALID_DEVICE);
2174 if(device) ALCdevice_DecRef(device);
2175 return NULL;
2178 /* Reset Context Last Error code */
2179 device->LastError = ALC_NO_ERROR;
2181 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2183 UnlockLists();
2184 alcSetError(device, ALC_INVALID_DEVICE);
2185 aluHandleDisconnect(device);
2186 ALCdevice_DecRef(device);
2187 return NULL;
2190 ALContext = calloc(1, sizeof(ALCcontext));
2191 if(ALContext)
2193 ALContext->ref = 1;
2195 ALContext->MaxActiveSources = 256;
2196 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2197 ALContext->MaxActiveSources);
2199 if(!ALContext || !ALContext->ActiveSources)
2201 if(!device->ContextList)
2203 ALCdevice_StopPlayback(device);
2204 device->Flags &= ~DEVICE_RUNNING;
2206 UnlockLists();
2208 free(ALContext);
2209 ALContext = NULL;
2211 alcSetError(device, ALC_OUT_OF_MEMORY);
2212 ALCdevice_DecRef(device);
2213 return NULL;
2216 ALContext->Device = device;
2217 ALCdevice_IncRef(device);
2218 InitContext(ALContext);
2220 ALContext->next = device->ContextList;
2221 device->ContextList = ALContext;
2222 UnlockLists();
2224 ALCdevice_DecRef(device);
2226 TRACE("Created context %p\n", ALContext);
2227 return ALContext;
2230 /* alcDestroyContext
2232 * Remove a Context
2234 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2236 ALCdevice *Device;
2238 LockLists();
2239 /* alcGetContextsDevice sets an error for invalid contexts */
2240 Device = alcGetContextsDevice(context);
2241 if(Device)
2243 ReleaseContext(context, Device);
2244 if(!Device->ContextList)
2246 ALCdevice_StopPlayback(Device);
2247 Device->Flags &= ~DEVICE_RUNNING;
2250 UnlockLists();
2254 /* alcGetCurrentContext
2256 * Returns the currently active Context
2258 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2260 ALCcontext *Context;
2262 Context = pthread_getspecific(LocalContext);
2263 if(!Context) Context = GlobalContext;
2265 return Context;
2268 /* alcGetThreadContext
2270 * Returns the currently active thread-local Context
2272 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2274 ALCcontext *Context;
2275 Context = pthread_getspecific(LocalContext);
2276 return Context;
2280 /* alcMakeContextCurrent
2282 * Makes the given Context the active Context
2284 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2286 /* context must be a valid Context or NULL */
2287 if(context && !(context=VerifyContext(context)))
2289 alcSetError(NULL, ALC_INVALID_CONTEXT);
2290 return ALC_FALSE;
2292 /* context's reference count is already incremented */
2293 context = ExchangePtr((void**)&GlobalContext, context);
2294 if(context) ALCcontext_DecRef(context);
2296 if((context=pthread_getspecific(LocalContext)) != NULL)
2298 pthread_setspecific(LocalContext, NULL);
2299 ALCcontext_DecRef(context);
2302 return ALC_TRUE;
2305 /* alcSetThreadContext
2307 * Makes the given Context the active Context for the current thread
2309 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2311 ALCcontext *old;
2313 /* context must be a valid Context or NULL */
2314 if(context && !(context=VerifyContext(context)))
2316 alcSetError(NULL, ALC_INVALID_CONTEXT);
2317 return ALC_FALSE;
2319 /* context's reference count is already incremented */
2320 old = pthread_getspecific(LocalContext);
2321 pthread_setspecific(LocalContext, context);
2322 if(old) ALCcontext_DecRef(old);
2324 return ALC_TRUE;
2328 /* alcGetContextsDevice
2330 * Returns the Device that a particular Context is attached to
2332 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2334 ALCdevice *Device;
2336 if(!(Context=VerifyContext(Context)))
2338 alcSetError(NULL, ALC_INVALID_CONTEXT);
2339 return NULL;
2341 Device = Context->Device;
2342 ALCcontext_DecRef(Context);
2344 return Device;
2348 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2350 static const struct {
2351 const char name[32];
2352 enum DevFmtChannels channels;
2353 enum DevFmtType type;
2354 } formats[] = {
2355 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2356 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2357 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2358 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2359 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2360 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2362 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2363 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2364 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2365 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2366 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2367 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2369 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2370 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2371 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2372 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2373 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2374 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2376 size_t i;
2378 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2380 if(strcasecmp(str, formats[i].name) == 0)
2382 *chans = formats[i].channels;
2383 *type = formats[i].type;
2384 return;
2388 ERR("Unknown format: \"%s\"\n", str);
2389 *chans = DevFmtStereo;
2390 *type = DevFmtShort;
2393 /* alcOpenDevice
2395 * Open the Device specified.
2397 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2399 const ALCchar *fmt;
2400 ALCdevice *device;
2401 ALCenum err;
2403 DO_INITCONFIG();
2405 if(!PlaybackBackend.name)
2407 alcSetError(NULL, ALC_INVALID_VALUE);
2408 return NULL;
2411 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2412 deviceName = NULL;
2414 device = calloc(1, sizeof(ALCdevice));
2415 if(!device)
2417 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2418 return NULL;
2421 //Validate device
2422 device->Funcs = &PlaybackBackend.Funcs;
2423 device->ref = 1;
2424 device->Connected = ALC_TRUE;
2425 device->IsCaptureDevice = AL_FALSE;
2426 device->IsLoopbackDevice = AL_FALSE;
2427 InitializeCriticalSection(&device->Mutex);
2428 device->LastError = ALC_NO_ERROR;
2430 device->Flags = 0;
2431 device->Bs2b = NULL;
2432 device->Bs2bLevel = 0;
2433 device->szDeviceName = NULL;
2435 device->ContextList = NULL;
2437 device->MaxNoOfSources = 256;
2438 device->AuxiliaryEffectSlotMax = 4;
2439 device->NumAuxSends = MAX_SENDS;
2441 InitUIntMap(&device->BufferMap, ~0);
2442 InitUIntMap(&device->EffectMap, ~0);
2443 InitUIntMap(&device->FilterMap, ~0);
2445 //Set output format
2446 device->NumUpdates = 4;
2447 device->UpdateSize = 1024;
2449 device->Frequency = DEFAULT_OUTPUT_RATE;
2450 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2451 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2452 device->Frequency = maxu(device->Frequency, 8000);
2454 fmt = "AL_FORMAT_STEREO16";
2455 if(ConfigValueStr(NULL, "format", &fmt))
2456 device->Flags |= DEVICE_CHANNELS_REQUEST;
2457 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2459 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2460 if(device->NumUpdates < 2) device->NumUpdates = 4;
2462 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2463 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2465 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2466 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2468 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2469 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2471 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2472 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2474 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2476 device->NumStereoSources = 1;
2477 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2479 // Find a playback device to open
2480 LockLists();
2481 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2483 UnlockLists();
2484 DeleteCriticalSection(&device->Mutex);
2485 free(device);
2486 alcSetError(NULL, err);
2487 return NULL;
2489 UnlockLists();
2491 do {
2492 device->next = DeviceList;
2493 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2495 TRACE("Created device %p\n", device);
2496 return device;
2499 /* alcCloseDevice
2501 * Close the specified Device
2503 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2505 ALCdevice *volatile*list;
2506 ALCcontext *ctx;
2508 LockLists();
2509 list = &DeviceList;
2510 while(*list && *list != pDevice)
2511 list = &(*list)->next;
2513 if(!*list || (*list)->IsCaptureDevice)
2515 alcSetError(*list, ALC_INVALID_DEVICE);
2516 UnlockLists();
2517 return ALC_FALSE;
2520 *list = (*list)->next;
2521 UnlockLists();
2523 if((ctx=pDevice->ContextList) != NULL)
2525 do {
2526 WARN("Releasing context %p\n", ctx);
2527 ReleaseContext(ctx, pDevice);
2528 } while((ctx=pDevice->ContextList) != NULL);
2529 ALCdevice_StopPlayback(pDevice);
2530 pDevice->Flags &= ~DEVICE_RUNNING;
2532 ALCdevice_ClosePlayback(pDevice);
2534 ALCdevice_DecRef(pDevice);
2536 return ALC_TRUE;
2540 /* alcLoopbackOpenDeviceSOFT
2542 * Open a loopback device, for manual rendering.
2544 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2546 ALCdevice *device;
2548 DO_INITCONFIG();
2550 device = calloc(1, sizeof(ALCdevice));
2551 if(!device)
2553 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2554 return NULL;
2557 //Validate device
2558 device->Funcs = &BackendLoopback.Funcs;
2559 device->ref = 1;
2560 device->Connected = ALC_TRUE;
2561 device->IsCaptureDevice = AL_FALSE;
2562 device->IsLoopbackDevice = AL_TRUE;
2563 InitializeCriticalSection(&device->Mutex);
2564 device->LastError = ALC_NO_ERROR;
2566 device->Flags = 0;
2567 device->Bs2b = NULL;
2568 device->Bs2bLevel = 0;
2569 device->szDeviceName = NULL;
2571 device->ContextList = NULL;
2573 device->MaxNoOfSources = 256;
2574 device->AuxiliaryEffectSlotMax = 4;
2575 device->NumAuxSends = MAX_SENDS;
2577 InitUIntMap(&device->BufferMap, ~0);
2578 InitUIntMap(&device->EffectMap, ~0);
2579 InitUIntMap(&device->FilterMap, ~0);
2581 //Set output format
2582 device->NumUpdates = 0;
2583 device->UpdateSize = 0;
2585 device->Frequency = 44100;
2586 device->FmtChans = DevFmtStereo;
2587 device->FmtType = DevFmtShort;
2589 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2590 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2592 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2593 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2595 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2596 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2598 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2600 device->NumStereoSources = 1;
2601 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2603 // Open the "backend"
2604 ALCdevice_OpenPlayback(device, "Loopback");
2605 do {
2606 device->next = DeviceList;
2607 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2609 TRACE("Created device %p\n", device);
2610 return device;
2613 /* alcIsRenderFormatSupportedSOFT
2615 * Determines if the loopback device supports the given format for rendering.
2617 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2619 ALCboolean ret = ALC_FALSE;
2621 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2622 alcSetError(device, ALC_INVALID_DEVICE);
2623 else if(freq <= 0)
2624 alcSetError(device, ALC_INVALID_VALUE);
2625 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2626 alcSetError(device, ALC_INVALID_ENUM);
2627 else
2629 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2630 freq >= 8000)
2631 ret = ALC_TRUE;
2633 if(device) ALCdevice_DecRef(device);
2635 return ret;
2638 /* alcRenderSamplesSOFT
2640 * Renders some samples into a buffer, using the format last set by the
2641 * attributes given to alcCreateContext.
2643 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2645 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2646 alcSetError(device, ALC_INVALID_DEVICE);
2647 else if(samples < 0 || (samples > 0 && buffer == NULL))
2648 alcSetError(device, ALC_INVALID_VALUE);
2649 else
2650 aluMixData(device, buffer, samples);
2651 if(device) ALCdevice_DecRef(device);
2655 static void ReleaseALC(ALCboolean doclose)
2657 free(alcDeviceList); alcDeviceList = NULL;
2658 alcDeviceListSize = 0;
2659 free(alcAllDeviceList); alcAllDeviceList = NULL;
2660 alcAllDeviceListSize = 0;
2661 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2662 alcCaptureDeviceListSize = 0;
2664 free(alcDefaultDeviceSpecifier);
2665 alcDefaultDeviceSpecifier = NULL;
2666 free(alcDefaultAllDeviceSpecifier);
2667 alcDefaultAllDeviceSpecifier = NULL;
2668 free(alcCaptureDefaultDeviceSpecifier);
2669 alcCaptureDefaultDeviceSpecifier = NULL;
2671 if(doclose)
2673 ALCdevice *dev;
2674 while((dev=DeviceList) != NULL)
2676 WARN("Closing device %p\n", dev);
2677 if(!dev->IsCaptureDevice) alcCloseDevice(dev);
2678 else alcCaptureCloseDevice(dev);
2681 else
2683 ALCdevice *dev;
2684 if((dev=DeviceList) != NULL)
2686 ALCuint num = 0;
2687 do {
2688 num++;
2689 } while((dev=dev->next) != NULL);
2690 WARN("%u device%s not closed\n", num, (num>1)?"s":"");
2695 ///////////////////////////////////////////////////////