Fix a typo
[openal-soft/openal-hmr.git] / Alc / ALc.c
blobd3eacd8907a68de3417e9e77690720f74e5c559d
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <math.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <memory.h>
27 #include <ctype.h>
28 #include <signal.h>
30 #include "alMain.h"
31 #include "alSource.h"
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "alThunk.h"
35 #include "alSource.h"
36 #include "alBuffer.h"
37 #include "alAuxEffectSlot.h"
38 #include "alError.h"
39 #include "bs2b.h"
40 #include "alu.h"
43 #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
44 static struct BackendInfo BackendList[] = {
45 #ifdef HAVE_PULSEAUDIO
46 { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs },
47 #endif
48 #ifdef HAVE_ALSA
49 { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs },
50 #endif
51 #ifdef HAVE_COREAUDIO
52 { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs },
53 #endif
54 #ifdef HAVE_OSS
55 { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs },
56 #endif
57 #ifdef HAVE_SOLARIS
58 { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs },
59 #endif
60 #ifdef HAVE_SNDIO
61 { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs },
62 #endif
63 #ifdef HAVE_MMDEVAPI
64 { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs },
65 #endif
66 #ifdef HAVE_DSOUND
67 { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs },
68 #endif
69 #ifdef HAVE_WINMM
70 { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs },
71 #endif
72 #ifdef HAVE_PORTAUDIO
73 { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs },
74 #endif
75 #ifdef HAVE_OPENSL
76 { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs },
77 #endif
79 { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs },
80 #ifdef HAVE_WAVE
81 { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs },
82 #endif
84 { NULL, NULL, NULL, NULL, EmptyFuncs }
86 static struct BackendInfo BackendLoopback = {
87 "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs
89 #undef EmptyFuncs
91 static struct BackendInfo PlaybackBackend;
92 static struct BackendInfo CaptureBackend;
94 ///////////////////////////////////////////////////////
95 // STRING and EXTENSIONS
97 typedef struct ALCfunction {
98 const ALCchar *funcName;
99 ALCvoid *address;
100 } ALCfunction;
102 typedef struct ALCenums {
103 const ALCchar *enumName;
104 ALCenum value;
105 } ALCenums;
108 static const ALCfunction alcFunctions[] = {
109 { "alcCreateContext", (ALCvoid *) alcCreateContext },
110 { "alcMakeContextCurrent", (ALCvoid *) alcMakeContextCurrent },
111 { "alcProcessContext", (ALCvoid *) alcProcessContext },
112 { "alcSuspendContext", (ALCvoid *) alcSuspendContext },
113 { "alcDestroyContext", (ALCvoid *) alcDestroyContext },
114 { "alcGetCurrentContext", (ALCvoid *) alcGetCurrentContext },
115 { "alcGetContextsDevice", (ALCvoid *) alcGetContextsDevice },
116 { "alcOpenDevice", (ALCvoid *) alcOpenDevice },
117 { "alcCloseDevice", (ALCvoid *) alcCloseDevice },
118 { "alcGetError", (ALCvoid *) alcGetError },
119 { "alcIsExtensionPresent", (ALCvoid *) alcIsExtensionPresent },
120 { "alcGetProcAddress", (ALCvoid *) alcGetProcAddress },
121 { "alcGetEnumValue", (ALCvoid *) alcGetEnumValue },
122 { "alcGetString", (ALCvoid *) alcGetString },
123 { "alcGetIntegerv", (ALCvoid *) alcGetIntegerv },
124 { "alcCaptureOpenDevice", (ALCvoid *) alcCaptureOpenDevice },
125 { "alcCaptureCloseDevice", (ALCvoid *) alcCaptureCloseDevice },
126 { "alcCaptureStart", (ALCvoid *) alcCaptureStart },
127 { "alcCaptureStop", (ALCvoid *) alcCaptureStop },
128 { "alcCaptureSamples", (ALCvoid *) alcCaptureSamples },
130 { "alcSetThreadContext", (ALCvoid *) alcSetThreadContext },
131 { "alcGetThreadContext", (ALCvoid *) alcGetThreadContext },
133 { "alcLoopbackOpenDeviceSOFT", (ALCvoid *) alcLoopbackOpenDeviceSOFT},
134 { "alcIsRenderFormatSupportedSOFT",(ALCvoid *) alcIsRenderFormatSupportedSOFT},
135 { "alcRenderSamplesSOFT", (ALCvoid *) alcRenderSamplesSOFT },
137 { "alEnable", (ALCvoid *) alEnable },
138 { "alDisable", (ALCvoid *) alDisable },
139 { "alIsEnabled", (ALCvoid *) alIsEnabled },
140 { "alGetString", (ALCvoid *) alGetString },
141 { "alGetBooleanv", (ALCvoid *) alGetBooleanv },
142 { "alGetIntegerv", (ALCvoid *) alGetIntegerv },
143 { "alGetFloatv", (ALCvoid *) alGetFloatv },
144 { "alGetDoublev", (ALCvoid *) alGetDoublev },
145 { "alGetBoolean", (ALCvoid *) alGetBoolean },
146 { "alGetInteger", (ALCvoid *) alGetInteger },
147 { "alGetFloat", (ALCvoid *) alGetFloat },
148 { "alGetDouble", (ALCvoid *) alGetDouble },
149 { "alGetError", (ALCvoid *) alGetError },
150 { "alIsExtensionPresent", (ALCvoid *) alIsExtensionPresent },
151 { "alGetProcAddress", (ALCvoid *) alGetProcAddress },
152 { "alGetEnumValue", (ALCvoid *) alGetEnumValue },
153 { "alListenerf", (ALCvoid *) alListenerf },
154 { "alListener3f", (ALCvoid *) alListener3f },
155 { "alListenerfv", (ALCvoid *) alListenerfv },
156 { "alListeneri", (ALCvoid *) alListeneri },
157 { "alListener3i", (ALCvoid *) alListener3i },
158 { "alListeneriv", (ALCvoid *) alListeneriv },
159 { "alGetListenerf", (ALCvoid *) alGetListenerf },
160 { "alGetListener3f", (ALCvoid *) alGetListener3f },
161 { "alGetListenerfv", (ALCvoid *) alGetListenerfv },
162 { "alGetListeneri", (ALCvoid *) alGetListeneri },
163 { "alGetListener3i", (ALCvoid *) alGetListener3i },
164 { "alGetListeneriv", (ALCvoid *) alGetListeneriv },
165 { "alGenSources", (ALCvoid *) alGenSources },
166 { "alDeleteSources", (ALCvoid *) alDeleteSources },
167 { "alIsSource", (ALCvoid *) alIsSource },
168 { "alSourcef", (ALCvoid *) alSourcef },
169 { "alSource3f", (ALCvoid *) alSource3f },
170 { "alSourcefv", (ALCvoid *) alSourcefv },
171 { "alSourcei", (ALCvoid *) alSourcei },
172 { "alSource3i", (ALCvoid *) alSource3i },
173 { "alSourceiv", (ALCvoid *) alSourceiv },
174 { "alGetSourcef", (ALCvoid *) alGetSourcef },
175 { "alGetSource3f", (ALCvoid *) alGetSource3f },
176 { "alGetSourcefv", (ALCvoid *) alGetSourcefv },
177 { "alGetSourcei", (ALCvoid *) alGetSourcei },
178 { "alGetSource3i", (ALCvoid *) alGetSource3i },
179 { "alGetSourceiv", (ALCvoid *) alGetSourceiv },
180 { "alSourcePlayv", (ALCvoid *) alSourcePlayv },
181 { "alSourceStopv", (ALCvoid *) alSourceStopv },
182 { "alSourceRewindv", (ALCvoid *) alSourceRewindv },
183 { "alSourcePausev", (ALCvoid *) alSourcePausev },
184 { "alSourcePlay", (ALCvoid *) alSourcePlay },
185 { "alSourceStop", (ALCvoid *) alSourceStop },
186 { "alSourceRewind", (ALCvoid *) alSourceRewind },
187 { "alSourcePause", (ALCvoid *) alSourcePause },
188 { "alSourceQueueBuffers", (ALCvoid *) alSourceQueueBuffers },
189 { "alSourceUnqueueBuffers", (ALCvoid *) alSourceUnqueueBuffers },
190 { "alGenBuffers", (ALCvoid *) alGenBuffers },
191 { "alDeleteBuffers", (ALCvoid *) alDeleteBuffers },
192 { "alIsBuffer", (ALCvoid *) alIsBuffer },
193 { "alBufferData", (ALCvoid *) alBufferData },
194 { "alBufferf", (ALCvoid *) alBufferf },
195 { "alBuffer3f", (ALCvoid *) alBuffer3f },
196 { "alBufferfv", (ALCvoid *) alBufferfv },
197 { "alBufferi", (ALCvoid *) alBufferi },
198 { "alBuffer3i", (ALCvoid *) alBuffer3i },
199 { "alBufferiv", (ALCvoid *) alBufferiv },
200 { "alGetBufferf", (ALCvoid *) alGetBufferf },
201 { "alGetBuffer3f", (ALCvoid *) alGetBuffer3f },
202 { "alGetBufferfv", (ALCvoid *) alGetBufferfv },
203 { "alGetBufferi", (ALCvoid *) alGetBufferi },
204 { "alGetBuffer3i", (ALCvoid *) alGetBuffer3i },
205 { "alGetBufferiv", (ALCvoid *) alGetBufferiv },
206 { "alDopplerFactor", (ALCvoid *) alDopplerFactor },
207 { "alDopplerVelocity", (ALCvoid *) alDopplerVelocity },
208 { "alSpeedOfSound", (ALCvoid *) alSpeedOfSound },
209 { "alDistanceModel", (ALCvoid *) alDistanceModel },
211 { "alGenFilters", (ALCvoid *) alGenFilters },
212 { "alDeleteFilters", (ALCvoid *) alDeleteFilters },
213 { "alIsFilter", (ALCvoid *) alIsFilter },
214 { "alFilteri", (ALCvoid *) alFilteri },
215 { "alFilteriv", (ALCvoid *) alFilteriv },
216 { "alFilterf", (ALCvoid *) alFilterf },
217 { "alFilterfv", (ALCvoid *) alFilterfv },
218 { "alGetFilteri", (ALCvoid *) alGetFilteri },
219 { "alGetFilteriv", (ALCvoid *) alGetFilteriv },
220 { "alGetFilterf", (ALCvoid *) alGetFilterf },
221 { "alGetFilterfv", (ALCvoid *) alGetFilterfv },
222 { "alGenEffects", (ALCvoid *) alGenEffects },
223 { "alDeleteEffects", (ALCvoid *) alDeleteEffects },
224 { "alIsEffect", (ALCvoid *) alIsEffect },
225 { "alEffecti", (ALCvoid *) alEffecti },
226 { "alEffectiv", (ALCvoid *) alEffectiv },
227 { "alEffectf", (ALCvoid *) alEffectf },
228 { "alEffectfv", (ALCvoid *) alEffectfv },
229 { "alGetEffecti", (ALCvoid *) alGetEffecti },
230 { "alGetEffectiv", (ALCvoid *) alGetEffectiv },
231 { "alGetEffectf", (ALCvoid *) alGetEffectf },
232 { "alGetEffectfv", (ALCvoid *) alGetEffectfv },
233 { "alGenAuxiliaryEffectSlots", (ALCvoid *) alGenAuxiliaryEffectSlots},
234 { "alDeleteAuxiliaryEffectSlots",(ALCvoid *) alDeleteAuxiliaryEffectSlots},
235 { "alIsAuxiliaryEffectSlot", (ALCvoid *) alIsAuxiliaryEffectSlot },
236 { "alAuxiliaryEffectSloti", (ALCvoid *) alAuxiliaryEffectSloti },
237 { "alAuxiliaryEffectSlotiv", (ALCvoid *) alAuxiliaryEffectSlotiv },
238 { "alAuxiliaryEffectSlotf", (ALCvoid *) alAuxiliaryEffectSlotf },
239 { "alAuxiliaryEffectSlotfv", (ALCvoid *) alAuxiliaryEffectSlotfv },
240 { "alGetAuxiliaryEffectSloti", (ALCvoid *) alGetAuxiliaryEffectSloti},
241 { "alGetAuxiliaryEffectSlotiv", (ALCvoid *) alGetAuxiliaryEffectSlotiv},
242 { "alGetAuxiliaryEffectSlotf", (ALCvoid *) alGetAuxiliaryEffectSlotf},
243 { "alGetAuxiliaryEffectSlotfv", (ALCvoid *) alGetAuxiliaryEffectSlotfv},
245 { "alBufferSubDataSOFT", (ALCvoid *) alBufferSubDataSOFT },
247 { "alBufferSamplesSOFT", (ALCvoid *) alBufferSamplesSOFT },
248 { "alBufferSubSamplesSOFT", (ALCvoid *) alBufferSubSamplesSOFT },
249 { "alGetBufferSamplesSOFT", (ALCvoid *) alGetBufferSamplesSOFT },
250 { "alIsBufferFormatSupportedSOFT",(ALCvoid *) alIsBufferFormatSupportedSOFT},
252 { "alDeferUpdatesSOFT", (ALCvoid *) alDeferUpdatesSOFT },
253 { "alProcessUpdatesSOFT", (ALCvoid *) alProcessUpdatesSOFT },
255 { NULL, (ALCvoid *) NULL }
258 static const ALCenums enumeration[] = {
259 // Types
260 { "ALC_INVALID", ALC_INVALID },
261 { "ALC_FALSE", ALC_FALSE },
262 { "ALC_TRUE", ALC_TRUE },
264 // ALC Properties
265 { "ALC_MAJOR_VERSION", ALC_MAJOR_VERSION },
266 { "ALC_MINOR_VERSION", ALC_MINOR_VERSION },
267 { "ALC_ATTRIBUTES_SIZE", ALC_ATTRIBUTES_SIZE },
268 { "ALC_ALL_ATTRIBUTES", ALC_ALL_ATTRIBUTES },
269 { "ALC_DEFAULT_DEVICE_SPECIFIER", ALC_DEFAULT_DEVICE_SPECIFIER },
270 { "ALC_DEVICE_SPECIFIER", ALC_DEVICE_SPECIFIER },
271 { "ALC_ALL_DEVICES_SPECIFIER", ALC_ALL_DEVICES_SPECIFIER },
272 { "ALC_DEFAULT_ALL_DEVICES_SPECIFIER", ALC_DEFAULT_ALL_DEVICES_SPECIFIER },
273 { "ALC_EXTENSIONS", ALC_EXTENSIONS },
274 { "ALC_FREQUENCY", ALC_FREQUENCY },
275 { "ALC_REFRESH", ALC_REFRESH },
276 { "ALC_SYNC", ALC_SYNC },
277 { "ALC_MONO_SOURCES", ALC_MONO_SOURCES },
278 { "ALC_STEREO_SOURCES", ALC_STEREO_SOURCES },
279 { "ALC_CAPTURE_DEVICE_SPECIFIER", ALC_CAPTURE_DEVICE_SPECIFIER },
280 { "ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER", ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER},
281 { "ALC_CAPTURE_SAMPLES", ALC_CAPTURE_SAMPLES },
282 { "ALC_CONNECTED", ALC_CONNECTED },
284 // EFX Properties
285 { "ALC_EFX_MAJOR_VERSION", ALC_EFX_MAJOR_VERSION },
286 { "ALC_EFX_MINOR_VERSION", ALC_EFX_MINOR_VERSION },
287 { "ALC_MAX_AUXILIARY_SENDS", ALC_MAX_AUXILIARY_SENDS },
289 // Loopback device Properties
290 { "ALC_FORMAT_CHANNELS_SOFT", ALC_FORMAT_CHANNELS_SOFT },
291 { "ALC_FORMAT_TYPE_SOFT", ALC_FORMAT_TYPE_SOFT },
293 // Buffer Channel Configurations
294 { "ALC_MONO_SOFT", ALC_MONO_SOFT },
295 { "ALC_STEREO_SOFT", ALC_STEREO_SOFT },
296 { "ALC_QUAD_SOFT", ALC_QUAD_SOFT },
297 { "ALC_5POINT1_SOFT", ALC_5POINT1_SOFT },
298 { "ALC_6POINT1_SOFT", ALC_6POINT1_SOFT },
299 { "ALC_7POINT1_SOFT", ALC_7POINT1_SOFT },
301 // Buffer Sample Types
302 { "ALC_BYTE_SOFT", ALC_BYTE_SOFT },
303 { "ALC_UNSIGNED_BYTE_SOFT", ALC_UNSIGNED_BYTE_SOFT },
304 { "ALC_SHORT_SOFT", ALC_SHORT_SOFT },
305 { "ALC_UNSIGNED_SHORT_SOFT", ALC_UNSIGNED_SHORT_SOFT },
306 { "ALC_INT_SOFT", ALC_INT_SOFT },
307 { "ALC_UNSIGNED_INT_SOFT", ALC_UNSIGNED_INT_SOFT },
308 { "ALC_FLOAT_SOFT", ALC_FLOAT_SOFT },
310 // ALC Error Message
311 { "ALC_NO_ERROR", ALC_NO_ERROR },
312 { "ALC_INVALID_DEVICE", ALC_INVALID_DEVICE },
313 { "ALC_INVALID_CONTEXT", ALC_INVALID_CONTEXT },
314 { "ALC_INVALID_ENUM", ALC_INVALID_ENUM },
315 { "ALC_INVALID_VALUE", ALC_INVALID_VALUE },
316 { "ALC_OUT_OF_MEMORY", ALC_OUT_OF_MEMORY },
318 { NULL, (ALCenum)0 }
320 // Error strings
321 static const ALCchar alcNoError[] = "No Error";
322 static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
323 static const ALCchar alcErrInvalidContext[] = "Invalid Context";
324 static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
325 static const ALCchar alcErrInvalidValue[] = "Invalid Value";
326 static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
328 /* Device lists. Sizes only include the first ending null character, not the
329 * second */
330 static ALCchar *alcDeviceList;
331 static size_t alcDeviceListSize;
332 static ALCchar *alcAllDeviceList;
333 static size_t alcAllDeviceListSize;
334 static ALCchar *alcCaptureDeviceList;
335 static size_t alcCaptureDeviceListSize;
336 /* Default is always the first in the list */
337 static ALCchar *alcDefaultDeviceSpecifier;
338 static ALCchar *alcDefaultAllDeviceSpecifier;
339 static ALCchar *alcCaptureDefaultDeviceSpecifier;
342 static const ALCchar alcNoDeviceExtList[] =
343 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
344 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
345 static const ALCchar alcExtensionList[] =
346 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
347 "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
348 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
349 static const ALCint alcMajorVersion = 1;
350 static const ALCint alcMinorVersion = 1;
352 static const ALCint alcEFXMajorVersion = 1;
353 static const ALCint alcEFXMinorVersion = 0;
355 ///////////////////////////////////////////////////////
358 ///////////////////////////////////////////////////////
359 // Global Variables
361 static CRITICAL_SECTION ListLock;
363 /* Device List */
364 static ALCdevice *volatile DeviceList = NULL;
366 // Thread-local current context
367 static pthread_key_t LocalContext;
368 // Process-wide current context
369 static ALCcontext *GlobalContext;
371 /* Device Error */
372 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
374 // Default context extensions
375 static const ALchar alExtList[] =
376 "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 "
377 "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
378 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
379 "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data "
380 "AL_SOFTX_deferred_updates AL_SOFT_loop_points "
381 "AL_SOFTX_non_virtual_channels";
383 // Mixing Priority Level
384 ALint RTPrioLevel;
386 // Output Log File
387 FILE *LogFile;
389 // Output Log Level
390 #ifdef _DEBUG
391 enum LogLevel LogLevel = LogWarning;
392 #else
393 enum LogLevel LogLevel = LogError;
394 #endif
396 /* Flag to trap ALC device errors */
397 static ALCboolean TrapALCError = ALC_FALSE;
399 /* One-time configuration init control */
400 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
402 /* Forced effect that applies to sources that don't have an effect on send 0 */
403 static ALeffect ForcedEffect;
405 ///////////////////////////////////////////////////////
408 ///////////////////////////////////////////////////////
409 // ALC Related helper functions
410 static void ReleaseALC(void);
411 static void ReleaseThreadCtx(void *ptr);
413 static void alc_initconfig(void);
414 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
416 #if defined(_WIN32)
417 static void alc_init(void);
418 static void alc_deinit(void);
419 static void alc_deinit_safe(void);
421 UIntMap TlsDestructor;
423 #ifndef AL_LIBTYPE_STATIC
424 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
426 ALsizei i;
427 (void)hModule;
429 // Perform actions based on the reason for calling.
430 switch(ul_reason_for_call)
432 case DLL_PROCESS_ATTACH:
433 InitUIntMap(&TlsDestructor, ~0);
434 alc_init();
435 break;
437 case DLL_THREAD_DETACH:
438 LockUIntMapRead(&TlsDestructor);
439 for(i = 0;i < TlsDestructor.size;i++)
441 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
442 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
443 if(ptr && callback)
444 callback(ptr);
446 UnlockUIntMapRead(&TlsDestructor);
447 break;
449 case DLL_PROCESS_DETACH:
450 if(!lpReserved)
451 alc_deinit();
452 else
453 alc_deinit_safe();
454 ResetUIntMap(&TlsDestructor);
455 break;
457 return TRUE;
459 #elif defined(_MSC_VER)
460 #pragma section(".CRT$XCU",read)
461 static void alc_constructor(void);
462 static void alc_destructor(void);
463 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
465 static void alc_constructor(void)
467 atexit(alc_destructor);
468 alc_init();
471 static void alc_destructor(void)
473 alc_deinit();
475 #elif defined(HAVE_GCC_DESTRUCTOR)
476 static void alc_init(void) __attribute__((constructor));
477 static void alc_deinit(void) __attribute__((destructor));
478 #else
479 #error "No static initialization available on this platform!"
480 #endif
481 #elif defined(HAVE_GCC_DESTRUCTOR)
482 static void alc_init(void) __attribute__((constructor));
483 static void alc_deinit(void) __attribute__((destructor));
484 #else
485 #error "No global initialization available on this platform!"
486 #endif
488 static void alc_init(void)
490 const char *str;
492 LogFile = stderr;
494 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
495 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
496 ConeScale = 1.0f;
498 str = getenv("__ALSOFT_REVERSE_Z");
499 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
500 ZScale = -1.0f;
502 str = getenv("__ALSOFT_TRAP_ERROR");
503 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
505 TrapALError = AL_TRUE;
506 TrapALCError = AL_TRUE;
508 else
510 str = getenv("__ALSOFT_TRAP_AL_ERROR");
511 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
512 TrapALError = AL_TRUE;
514 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
515 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
516 TrapALCError = ALC_TRUE;
519 pthread_key_create(&LocalContext, ReleaseThreadCtx);
520 InitializeCriticalSection(&ListLock);
521 ThunkInit();
524 static void alc_deinit_safe(void)
526 ReleaseALC();
528 FreeHrtf();
529 FreeALConfig();
531 ThunkExit();
532 DeleteCriticalSection(&ListLock);
533 pthread_key_delete(LocalContext);
535 if(LogFile != stderr)
536 fclose(LogFile);
537 LogFile = NULL;
540 static void alc_deinit(void)
542 int i;
544 ReleaseALC();
546 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
547 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
549 for(i = 0;BackendList[i].Deinit;i++)
550 BackendList[i].Deinit();
551 BackendLoopback.Deinit();
553 alc_deinit_safe();
556 static void alc_initconfig(void)
558 const char *devs, *str;
559 float valf;
560 int i, n;
562 str = getenv("ALSOFT_LOGLEVEL");
563 if(str)
565 long lvl = strtol(str, NULL, 0);
566 if(lvl >= NoLog && lvl <= LogRef)
567 LogLevel = lvl;
570 str = getenv("ALSOFT_LOGFILE");
571 if(str && str[0])
573 FILE *logfile = fopen(str, "wat");
574 if(logfile) LogFile = logfile;
575 else ERR("Failed to open log file '%s'\n", str);
578 ReadALConfig();
580 InitHrtf();
582 #ifdef _WIN32
583 RTPrioLevel = 1;
584 #else
585 RTPrioLevel = 0;
586 #endif
587 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
589 if(ConfigValueStr(NULL, "resampler", &str))
591 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
592 DefaultResampler = POINT_RESAMPLER;
593 else if(strcasecmp(str, "linear") == 0)
594 DefaultResampler = LINEAR_RESAMPLER;
595 else if(strcasecmp(str, "cubic") == 0)
596 DefaultResampler = CUBIC_RESAMPLER;
597 else
599 char *end;
601 n = strtol(str, &end, 0);
602 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
603 DefaultResampler = n;
604 else
605 WARN("Invalid resampler: %s\n", str);
609 if(!TrapALCError)
610 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
612 if(!TrapALError)
613 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
615 if(ConfigValueFloat("reverb", "boost", &valf))
616 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
618 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
620 if(ConfigValueStr(NULL, "drivers", &devs))
622 int n;
623 size_t len;
624 const char *next = devs;
625 int endlist, delitem;
627 i = 0;
628 do {
629 devs = next;
630 next = strchr(devs, ',');
632 delitem = (devs[0] == '-');
633 if(devs[0] == '-') devs++;
635 if(!devs[0] || devs[0] == ',')
637 endlist = 0;
638 continue;
640 endlist = 1;
642 len = (next ? ((size_t)(next-devs)) : strlen(devs));
643 for(n = i;BackendList[n].Init;n++)
645 if(len == strlen(BackendList[n].name) &&
646 strncmp(BackendList[n].name, devs, len) == 0)
648 if(delitem)
650 do {
651 BackendList[n] = BackendList[n+1];
652 ++n;
653 } while(BackendList[n].Init);
655 else
657 struct BackendInfo Bkp = BackendList[n];
658 while(n > i)
660 BackendList[n] = BackendList[n-1];
661 --n;
663 BackendList[n] = Bkp;
665 i++;
667 break;
670 } while(next++);
672 if(endlist)
674 BackendList[i].name = NULL;
675 BackendList[i].Init = NULL;
676 BackendList[i].Deinit = NULL;
677 BackendList[i].Probe = NULL;
681 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
683 if(!BackendList[i].Init(&BackendList[i].Funcs))
685 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
686 continue;
689 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
690 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
692 PlaybackBackend = BackendList[i];
693 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
695 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
697 CaptureBackend = BackendList[i];
698 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
701 BackendLoopback.Init(&BackendLoopback.Funcs);
703 if(ConfigValueStr(NULL, "excludefx", &str))
705 size_t len;
706 const char *next = str;
708 do {
709 str = next;
710 next = strchr(str, ',');
712 if(!str[0] || next == str)
713 continue;
715 len = (next ? ((size_t)(next-str)) : strlen(str));
716 for(n = 0;EffectList[n].name;n++)
718 if(len == strlen(EffectList[n].name) &&
719 strncmp(EffectList[n].name, str, len) == 0)
720 DisabledEffects[EffectList[n].type] = AL_TRUE;
722 } while(next++);
725 InitEffect(&ForcedEffect);
726 str = getenv("__ALSOFT_DEFAULT_REVERB");
727 if(str && str[0])
728 GetReverbEffect(str, &ForcedEffect);
729 else if(ConfigValueStr(NULL, "default-reverb", &str))
730 GetReverbEffect(str, &ForcedEffect);
734 static void LockLists(void)
736 EnterCriticalSection(&ListLock);
739 static void UnlockLists(void)
741 LeaveCriticalSection(&ListLock);
745 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
747 DO_INITCONFIG();
749 LockLists();
750 free(*list);
751 *list = NULL;
752 *listsize = 0;
754 if(type == CAPTURE_DEVICE_PROBE)
755 CaptureBackend.Probe(type);
756 else
757 PlaybackBackend.Probe(type);
758 UnlockLists();
761 static void ProbeDeviceList(void)
762 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
763 static void ProbeAllDeviceList(void)
764 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
765 static void ProbeCaptureDeviceList(void)
766 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
769 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
771 size_t len = strlen(name);
772 void *temp;
774 if(len == 0)
775 return;
777 temp = realloc(*List, (*ListSize) + len + 2);
778 if(!temp)
780 ERR("Realloc failed to add %s!\n", name);
781 return;
783 *List = temp;
785 memcpy((*List)+(*ListSize), name, len+1);
786 *ListSize += len+1;
787 (*List)[*ListSize] = 0;
790 #define DECL_APPEND_LIST_FUNC(type) \
791 void Append##type##List(const ALCchar *name) \
792 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
794 DECL_APPEND_LIST_FUNC(Device)
795 DECL_APPEND_LIST_FUNC(AllDevice)
796 DECL_APPEND_LIST_FUNC(CaptureDevice)
798 #undef DECL_APPEND_LIST_FUNC
801 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
802 void SetDefaultChannelOrder(ALCdevice *device)
804 switch(device->FmtChans)
806 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
807 device->DevChannels[1] = FRONT_RIGHT;
808 device->DevChannels[2] = BACK_LEFT;
809 device->DevChannels[3] = BACK_RIGHT;
810 device->DevChannels[4] = FRONT_CENTER;
811 device->DevChannels[5] = LFE;
812 return;
814 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
815 device->DevChannels[1] = FRONT_RIGHT;
816 device->DevChannels[2] = BACK_LEFT;
817 device->DevChannels[3] = BACK_RIGHT;
818 device->DevChannels[4] = FRONT_CENTER;
819 device->DevChannels[5] = LFE;
820 device->DevChannels[6] = SIDE_LEFT;
821 device->DevChannels[7] = SIDE_RIGHT;
822 return;
824 /* Same as WFX order */
825 case DevFmtMono:
826 case DevFmtStereo:
827 case DevFmtQuad:
828 case DevFmtX51Side:
829 case DevFmtX61:
830 break;
832 SetDefaultWFXChannelOrder(device);
834 /* Sets the default order used by WaveFormatEx */
835 void SetDefaultWFXChannelOrder(ALCdevice *device)
837 switch(device->FmtChans)
839 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
841 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
842 device->DevChannels[1] = FRONT_RIGHT; break;
844 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
845 device->DevChannels[1] = FRONT_RIGHT;
846 device->DevChannels[2] = BACK_LEFT;
847 device->DevChannels[3] = BACK_RIGHT; break;
849 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
850 device->DevChannels[1] = FRONT_RIGHT;
851 device->DevChannels[2] = FRONT_CENTER;
852 device->DevChannels[3] = LFE;
853 device->DevChannels[4] = BACK_LEFT;
854 device->DevChannels[5] = BACK_RIGHT; break;
856 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
857 device->DevChannels[1] = FRONT_RIGHT;
858 device->DevChannels[2] = FRONT_CENTER;
859 device->DevChannels[3] = LFE;
860 device->DevChannels[4] = SIDE_LEFT;
861 device->DevChannels[5] = SIDE_RIGHT; break;
863 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
864 device->DevChannels[1] = FRONT_RIGHT;
865 device->DevChannels[2] = FRONT_CENTER;
866 device->DevChannels[3] = LFE;
867 device->DevChannels[4] = BACK_CENTER;
868 device->DevChannels[5] = SIDE_LEFT;
869 device->DevChannels[6] = SIDE_RIGHT; break;
871 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
872 device->DevChannels[1] = FRONT_RIGHT;
873 device->DevChannels[2] = FRONT_CENTER;
874 device->DevChannels[3] = LFE;
875 device->DevChannels[4] = BACK_LEFT;
876 device->DevChannels[5] = BACK_RIGHT;
877 device->DevChannels[6] = SIDE_LEFT;
878 device->DevChannels[7] = SIDE_RIGHT; break;
883 const ALCchar *DevFmtTypeString(enum DevFmtType type)
885 switch(type)
887 case DevFmtByte: return "Signed Byte";
888 case DevFmtUByte: return "Unsigned Byte";
889 case DevFmtShort: return "Signed Short";
890 case DevFmtUShort: return "Unsigned Short";
891 case DevFmtFloat: return "Float";
893 return "(unknown type)";
895 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
897 switch(chans)
899 case DevFmtMono: return "Mono";
900 case DevFmtStereo: return "Stereo";
901 case DevFmtQuad: return "Quadraphonic";
902 case DevFmtX51: return "5.1 Surround";
903 case DevFmtX51Side: return "5.1 Side";
904 case DevFmtX61: return "6.1 Surround";
905 case DevFmtX71: return "7.1 Surround";
907 return "(unknown channels)";
910 ALuint BytesFromDevFmt(enum DevFmtType type)
912 switch(type)
914 case DevFmtByte: return sizeof(ALbyte);
915 case DevFmtUByte: return sizeof(ALubyte);
916 case DevFmtShort: return sizeof(ALshort);
917 case DevFmtUShort: return sizeof(ALushort);
918 case DevFmtFloat: return sizeof(ALfloat);
920 return 0;
922 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
924 switch(chans)
926 case DevFmtMono: return 1;
927 case DevFmtStereo: return 2;
928 case DevFmtQuad: return 4;
929 case DevFmtX51: return 6;
930 case DevFmtX51Side: return 6;
931 case DevFmtX61: return 7;
932 case DevFmtX71: return 8;
934 return 0;
936 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
937 enum DevFmtType *type)
939 static const struct {
940 ALenum format;
941 enum DevFmtChannels channels;
942 enum DevFmtType type;
943 } list[] = {
944 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
945 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
946 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
948 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
949 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
950 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
952 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
953 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
954 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
956 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
957 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
958 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
960 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
961 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
962 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
964 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
965 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
966 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
968 ALuint i;
970 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
972 if(list[i].format == format)
974 *chans = list[i].channels;
975 *type = list[i].type;
976 return AL_TRUE;
980 return AL_FALSE;
983 static ALCboolean IsValidALCType(ALCenum type)
985 switch(type)
987 case ALC_BYTE_SOFT:
988 case ALC_UNSIGNED_BYTE_SOFT:
989 case ALC_SHORT_SOFT:
990 case ALC_UNSIGNED_SHORT_SOFT:
991 case ALC_INT_SOFT:
992 case ALC_UNSIGNED_INT_SOFT:
993 case ALC_FLOAT_SOFT:
994 return ALC_TRUE;
996 return ALC_FALSE;
999 static ALCboolean IsValidALCChannels(ALCenum channels)
1001 switch(channels)
1003 case ALC_MONO_SOFT:
1004 case ALC_STEREO_SOFT:
1005 case ALC_QUAD_SOFT:
1006 case ALC_5POINT1_SOFT:
1007 case ALC_6POINT1_SOFT:
1008 case ALC_7POINT1_SOFT:
1009 return ALC_TRUE;
1011 return ALC_FALSE;
1015 /* alcSetError
1017 * Stores the latest ALC Error
1019 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1021 if(TrapALCError)
1023 #ifdef _WIN32
1024 /* DebugBreak() will cause an exception if there is no debugger */
1025 if(IsDebuggerPresent())
1026 DebugBreak();
1027 #elif defined(SIGTRAP)
1028 raise(SIGTRAP);
1029 #endif
1032 if(device)
1033 device->LastError = errorCode;
1034 else
1035 g_eLastNullDeviceError = errorCode;
1039 /* UpdateDeviceParams
1041 * Updates device parameters according to the attribute list (caller is
1042 * responsible for holding the list lock).
1044 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1046 ALCcontext *context;
1047 enum DevFmtChannels oldChans;
1048 enum DevFmtType oldType;
1049 ALCuint oldFreq;
1050 int oldMode;
1051 ALuint i;
1053 // Check for attributes
1054 if(attrList && attrList[0])
1056 ALCuint freq, numMono, numStereo, numSends;
1057 enum DevFmtChannels schans;
1058 enum DevFmtType stype;
1059 ALuint attrIdx;
1061 // If a context is already running on the device, stop playback so the
1062 // device attributes can be updated
1063 if((device->Flags&DEVICE_RUNNING))
1064 ALCdevice_StopPlayback(device);
1065 device->Flags &= ~DEVICE_RUNNING;
1067 freq = device->Frequency;
1068 schans = device->FmtChans;
1069 stype = device->FmtType;
1070 numMono = device->NumMonoSources;
1071 numStereo = device->NumStereoSources;
1072 numSends = device->NumAuxSends;
1074 attrIdx = 0;
1075 while(attrList[attrIdx])
1077 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1078 device->IsLoopbackDevice)
1080 ALCint val = attrList[attrIdx + 1];
1081 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1083 alcSetError(device, ALC_INVALID_VALUE);
1084 return ALC_FALSE;
1086 schans = val;
1089 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1090 device->IsLoopbackDevice)
1092 ALCint val = attrList[attrIdx + 1];
1093 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1095 alcSetError(device, ALC_INVALID_VALUE);
1096 return ALC_FALSE;
1098 stype = val;
1101 if(attrList[attrIdx] == ALC_FREQUENCY)
1103 if(device->IsLoopbackDevice)
1105 freq = attrList[attrIdx + 1];
1106 if(freq < 8000)
1108 alcSetError(device, ALC_INVALID_VALUE);
1109 return ALC_FALSE;
1112 else
1114 freq = attrList[attrIdx + 1];
1115 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1119 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1121 numStereo = attrList[attrIdx + 1];
1122 if(numStereo > device->MaxNoOfSources)
1123 numStereo = device->MaxNoOfSources;
1125 numMono = device->MaxNoOfSources - numStereo;
1128 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1129 numSends = attrList[attrIdx + 1];
1131 attrIdx += 2;
1134 if(!device->IsLoopbackDevice)
1136 ConfigValueUInt(NULL, "frequency", &freq);
1137 freq = maxu(freq, 8000);
1139 ConfigValueUInt(NULL, "sends", &numSends);
1140 numSends = minu(MAX_SENDS, numSends);
1142 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1143 device->Frequency;
1145 device->Frequency = freq;
1146 device->FmtChans = schans;
1147 device->FmtType = stype;
1148 device->NumMonoSources = numMono;
1149 device->NumStereoSources = numStereo;
1150 device->NumAuxSends = numSends;
1153 if((device->Flags&DEVICE_RUNNING))
1154 return ALC_TRUE;
1156 LockDevice(device);
1158 oldFreq = device->Frequency;
1159 oldChans = device->FmtChans;
1160 oldType = device->FmtType;
1162 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1163 DevFmtChannelsString(device->FmtChans),
1164 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1165 DevFmtTypeString(device->FmtType), device->Frequency,
1166 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1167 device->UpdateSize, device->NumUpdates);
1168 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1170 UnlockDevice(device);
1171 return ALC_FALSE;
1173 device->Flags |= DEVICE_RUNNING;
1175 if(device->FmtChans != oldChans)
1177 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1178 ERR("Failed to set %s, got %s instead\n",
1179 DevFmtChannelsString(oldChans),
1180 DevFmtChannelsString(device->FmtChans));
1181 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1183 if(device->Frequency != oldFreq)
1185 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1186 ERR("Failed to set %uhz, got %uhz instead\n",
1187 oldFreq, device->Frequency);
1188 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1191 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1192 DevFmtChannelsString(device->FmtChans),
1193 DevFmtTypeString(device->FmtType), device->Frequency,
1194 device->UpdateSize, device->NumUpdates);
1196 aluInitPanning(device);
1198 for(i = 0;i < MAXCHANNELS;i++)
1200 device->ClickRemoval[i] = 0.0f;
1201 device->PendingClicks[i] = 0.0f;
1204 device->Hrtf = NULL;
1205 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1206 device->Hrtf = GetHrtf(device);
1207 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1209 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1211 if(!device->Bs2b)
1213 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1214 bs2b_clear(device->Bs2b);
1216 bs2b_set_srate(device->Bs2b, device->Frequency);
1217 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1218 TRACE("BS2B level %d\n", device->Bs2bLevel);
1220 else
1222 free(device->Bs2b);
1223 device->Bs2b = NULL;
1224 TRACE("BS2B disabled\n");
1227 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1228 switch(device->FmtChans)
1230 case DevFmtMono:
1231 case DevFmtStereo:
1232 break;
1233 case DevFmtQuad:
1234 case DevFmtX51:
1235 case DevFmtX51Side:
1236 case DevFmtX61:
1237 case DevFmtX71:
1238 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1239 device->Flags |= DEVICE_DUPLICATE_STEREO;
1240 break;
1242 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1244 oldMode = SetMixerFPUMode();
1245 context = device->ContextList;
1246 while(context)
1248 ALsizei pos;
1250 context->UpdateSources = AL_FALSE;
1251 LockUIntMapRead(&context->EffectSlotMap);
1252 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1254 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1256 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1258 UnlockUIntMapRead(&context->EffectSlotMap);
1259 RestoreFPUMode(oldMode);
1260 UnlockDevice(device);
1261 ALCdevice_StopPlayback(device);
1262 device->Flags &= ~DEVICE_RUNNING;
1263 return ALC_FALSE;
1265 slot->NeedsUpdate = AL_FALSE;
1266 ALeffectState_Update(slot->EffectState, context, slot);
1268 UnlockUIntMapRead(&context->EffectSlotMap);
1270 LockUIntMapRead(&context->SourceMap);
1271 for(pos = 0;pos < context->SourceMap.size;pos++)
1273 ALsource *source = context->SourceMap.array[pos].value;
1274 ALuint s = device->NumAuxSends;
1275 while(s < MAX_SENDS)
1277 if(source->Send[s].Slot)
1278 DecrementRef(&source->Send[s].Slot->ref);
1279 source->Send[s].Slot = NULL;
1280 source->Send[s].WetGain = 1.0f;
1281 source->Send[s].WetGainHF = 1.0f;
1282 s++;
1284 source->NeedsUpdate = AL_FALSE;
1285 ALsource_Update(source, context);
1287 UnlockUIntMapRead(&context->SourceMap);
1289 context = context->next;
1291 RestoreFPUMode(oldMode);
1292 UnlockDevice(device);
1294 return ALC_TRUE;
1297 /* FreeDevice
1299 * Frees the device structure, and destroys any objects the app failed to
1300 * delete. Called once there's no more references on the device.
1302 static ALCvoid FreeDevice(ALCdevice *device)
1304 TRACE("%p\n", device);
1306 if(device->DefaultSlot)
1308 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1309 device->DefaultSlot->EffectState = NULL;
1312 if(device->BufferMap.size > 0)
1314 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1315 ReleaseALBuffers(device);
1317 ResetUIntMap(&device->BufferMap);
1319 if(device->EffectMap.size > 0)
1321 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1322 ReleaseALEffects(device);
1324 ResetUIntMap(&device->EffectMap);
1326 if(device->FilterMap.size > 0)
1328 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1329 ReleaseALFilters(device);
1331 ResetUIntMap(&device->FilterMap);
1333 free(device->Bs2b);
1334 device->Bs2b = NULL;
1336 free(device->szDeviceName);
1337 device->szDeviceName = NULL;
1339 DeleteCriticalSection(&device->Mutex);
1341 free(device);
1345 void ALCdevice_IncRef(ALCdevice *device)
1347 RefCount ref;
1348 ref = IncrementRef(&device->ref);
1349 TRACEREF("%p increasing refcount to %u\n", device, ref);
1352 void ALCdevice_DecRef(ALCdevice *device)
1354 RefCount ref;
1355 ref = DecrementRef(&device->ref);
1356 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1357 if(ref == 0) FreeDevice(device);
1360 /* VerifyDevice
1362 * Checks if the device handle is valid, and increments its ref count if so.
1364 static ALCdevice *VerifyDevice(ALCdevice *device)
1366 ALCdevice *tmpDevice;
1368 if(!device)
1369 return NULL;
1371 LockLists();
1372 tmpDevice = DeviceList;
1373 while(tmpDevice && tmpDevice != device)
1374 tmpDevice = tmpDevice->next;
1376 if(tmpDevice)
1377 ALCdevice_IncRef(tmpDevice);
1378 UnlockLists();
1379 return tmpDevice;
1383 /* InitContext
1385 * Initializes context variables
1387 static ALvoid InitContext(ALCcontext *pContext)
1389 ALint i, j;
1391 //Initialise listener
1392 pContext->Listener.Gain = 1.0f;
1393 pContext->Listener.MetersPerUnit = 1.0f;
1394 pContext->Listener.Position[0] = 0.0f;
1395 pContext->Listener.Position[1] = 0.0f;
1396 pContext->Listener.Position[2] = 0.0f;
1397 pContext->Listener.Velocity[0] = 0.0f;
1398 pContext->Listener.Velocity[1] = 0.0f;
1399 pContext->Listener.Velocity[2] = 0.0f;
1400 pContext->Listener.Forward[0] = 0.0f;
1401 pContext->Listener.Forward[1] = 0.0f;
1402 pContext->Listener.Forward[2] = -1.0f;
1403 pContext->Listener.Up[0] = 0.0f;
1404 pContext->Listener.Up[1] = 1.0f;
1405 pContext->Listener.Up[2] = 0.0f;
1406 for(i = 0;i < 4;i++)
1408 for(j = 0;j < 4;j++)
1409 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1412 //Validate pContext
1413 pContext->LastError = AL_NO_ERROR;
1414 pContext->UpdateSources = AL_FALSE;
1415 pContext->ActiveSourceCount = 0;
1416 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1417 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1419 //Set globals
1420 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1421 pContext->SourceDistanceModel = AL_FALSE;
1422 pContext->DopplerFactor = 1.0f;
1423 pContext->DopplerVelocity = 1.0f;
1424 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1425 pContext->DeferUpdates = AL_FALSE;
1427 pContext->ExtensionList = alExtList;
1431 /* FreeContext
1433 * Cleans up the context, and destroys any remaining objects the app failed to
1434 * delete. Called once there's no more references on the context.
1436 static ALCvoid FreeContext(ALCcontext *context)
1438 TRACE("%p\n", context);
1440 if(context->SourceMap.size > 0)
1442 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1443 ReleaseALSources(context);
1445 ResetUIntMap(&context->SourceMap);
1447 if(context->EffectSlotMap.size > 0)
1449 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1450 ReleaseALAuxiliaryEffectSlots(context);
1452 ResetUIntMap(&context->EffectSlotMap);
1454 context->ActiveSourceCount = 0;
1455 free(context->ActiveSources);
1456 context->ActiveSources = NULL;
1457 context->MaxActiveSources = 0;
1459 context->ActiveEffectSlotCount = 0;
1460 free(context->ActiveEffectSlots);
1461 context->ActiveEffectSlots = NULL;
1462 context->MaxActiveEffectSlots = 0;
1464 ALCdevice_DecRef(context->Device);
1465 context->Device = NULL;
1467 //Invalidate context
1468 memset(context, 0, sizeof(ALCcontext));
1469 free(context);
1472 /* ReleaseContext
1474 * Removes the context reference from the given device and removes it from
1475 * being current on the running thread or globally.
1477 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1479 ALCcontext *volatile*tmp_ctx;
1481 if(pthread_getspecific(LocalContext) == context)
1483 WARN("%p released while current on thread\n", context);
1484 pthread_setspecific(LocalContext, NULL);
1485 ALCcontext_DecRef(context);
1488 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1489 ALCcontext_DecRef(context);
1491 LockDevice(device);
1492 tmp_ctx = &device->ContextList;
1493 while(*tmp_ctx)
1495 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1496 break;
1497 tmp_ctx = &(*tmp_ctx)->next;
1499 UnlockDevice(device);
1501 ALCcontext_DecRef(context);
1504 void ALCcontext_IncRef(ALCcontext *context)
1506 RefCount ref;
1507 ref = IncrementRef(&context->ref);
1508 TRACEREF("%p increasing refcount to %u\n", context, ref);
1511 void ALCcontext_DecRef(ALCcontext *context)
1513 RefCount ref;
1514 ref = DecrementRef(&context->ref);
1515 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1516 if(ref == 0) FreeContext(context);
1519 static void ReleaseThreadCtx(void *ptr)
1521 WARN("%p current for thread being destroyed\n", ptr);
1522 ALCcontext_DecRef(ptr);
1525 /* VerifyContext
1527 * Checks that the given context is valid, and increments its reference count.
1529 static ALCcontext *VerifyContext(ALCcontext *context)
1531 ALCdevice *dev;
1533 LockLists();
1534 dev = DeviceList;
1535 while(dev)
1537 ALCcontext *tmp_ctx = dev->ContextList;
1538 while(tmp_ctx)
1540 if(tmp_ctx == context)
1542 ALCcontext_IncRef(tmp_ctx);
1543 UnlockLists();
1544 return tmp_ctx;
1546 tmp_ctx = tmp_ctx->next;
1548 dev = dev->next;
1550 UnlockLists();
1552 return NULL;
1556 /* GetContextRef
1558 * Returns the currently active context, and adds a reference without locking
1559 * it.
1561 ALCcontext *GetContextRef(void)
1563 ALCcontext *context;
1565 context = pthread_getspecific(LocalContext);
1566 if(context)
1567 ALCcontext_IncRef(context);
1568 else
1570 LockLists();
1571 context = GlobalContext;
1572 if(context)
1573 ALCcontext_IncRef(context);
1574 UnlockLists();
1577 return context;
1580 ///////////////////////////////////////////////////////
1583 ///////////////////////////////////////////////////////
1584 // ALC Functions calls
1587 // This should probably move to another c file but for now ...
1588 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1590 ALCdevice *device = NULL;
1591 ALCenum err;
1593 DO_INITCONFIG();
1595 if(!CaptureBackend.name)
1597 alcSetError(NULL, ALC_INVALID_VALUE);
1598 return NULL;
1601 if(SampleSize <= 0)
1603 alcSetError(NULL, ALC_INVALID_VALUE);
1604 return NULL;
1607 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1608 deviceName = NULL;
1610 device = calloc(1, sizeof(ALCdevice));
1611 if(!device)
1613 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1614 return NULL;
1617 //Validate device
1618 device->Funcs = &CaptureBackend.Funcs;
1619 device->ref = 1;
1620 device->Connected = ALC_TRUE;
1621 device->IsCaptureDevice = AL_TRUE;
1622 device->IsLoopbackDevice = AL_FALSE;
1623 InitializeCriticalSection(&device->Mutex);
1625 InitUIntMap(&device->BufferMap, ~0);
1626 InitUIntMap(&device->EffectMap, ~0);
1627 InitUIntMap(&device->FilterMap, ~0);
1629 device->szDeviceName = NULL;
1631 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1632 device->Frequency = frequency;
1634 device->Flags |= DEVICE_CHANNELS_REQUEST;
1635 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1637 DeleteCriticalSection(&device->Mutex);
1638 free(device);
1639 alcSetError(NULL, ALC_INVALID_ENUM);
1640 return NULL;
1643 device->UpdateSize = SampleSize;
1644 device->NumUpdates = 1;
1646 LockLists();
1647 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1649 UnlockLists();
1650 DeleteCriticalSection(&device->Mutex);
1651 free(device);
1652 alcSetError(NULL, err);
1653 return NULL;
1655 UnlockLists();
1657 do {
1658 device->next = DeviceList;
1659 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1661 TRACE("Created device %p\n", device);
1662 return device;
1665 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1667 ALCdevice *volatile*list;
1669 LockLists();
1670 list = &DeviceList;
1671 while(*list && *list != pDevice)
1672 list = &(*list)->next;
1674 if(!*list || !(*list)->IsCaptureDevice)
1676 alcSetError(*list, ALC_INVALID_DEVICE);
1677 UnlockLists();
1678 return ALC_FALSE;
1681 *list = (*list)->next;
1682 UnlockLists();
1684 LockDevice(pDevice);
1685 ALCdevice_CloseCapture(pDevice);
1686 UnlockDevice(pDevice);
1688 ALCdevice_DecRef(pDevice);
1690 return ALC_TRUE;
1693 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1695 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1697 alcSetError(device, ALC_INVALID_DEVICE);
1698 if(device) ALCdevice_DecRef(device);
1699 return;
1701 LockDevice(device);
1702 if(device->Connected)
1703 ALCdevice_StartCapture(device);
1704 UnlockDevice(device);
1706 ALCdevice_DecRef(device);
1709 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1711 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1713 alcSetError(device, ALC_INVALID_DEVICE);
1714 if(device) ALCdevice_DecRef(device);
1715 return;
1717 LockDevice(device);
1718 if(device->Connected)
1719 ALCdevice_StopCapture(device);
1720 UnlockDevice(device);
1722 ALCdevice_DecRef(device);
1725 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1727 ALCenum err = ALC_INVALID_DEVICE;
1728 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1730 err = ALC_INVALID_VALUE;
1731 LockDevice(device);
1732 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1733 err = ALCdevice_CaptureSamples(device, buffer, samples);
1734 UnlockDevice(device);
1736 if(err != ALC_NO_ERROR)
1737 alcSetError(device, err);
1738 if(device) ALCdevice_DecRef(device);
1742 alcGetError
1744 Return last ALC generated error code
1746 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1748 ALCenum errorCode;
1750 if(VerifyDevice(device))
1752 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1753 ALCdevice_DecRef(device);
1755 else
1756 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1758 return errorCode;
1762 /* alcSuspendContext
1764 * Not functional
1766 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1768 (void)Context;
1771 /* alcProcessContext
1773 * Not functional
1775 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1777 (void)Context;
1781 /* alcGetString
1783 * Returns information about the Device, and error strings
1785 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1787 const ALCchar *value = NULL;
1789 switch(param)
1791 case ALC_NO_ERROR:
1792 value = alcNoError;
1793 break;
1795 case ALC_INVALID_ENUM:
1796 value = alcErrInvalidEnum;
1797 break;
1799 case ALC_INVALID_VALUE:
1800 value = alcErrInvalidValue;
1801 break;
1803 case ALC_INVALID_DEVICE:
1804 value = alcErrInvalidDevice;
1805 break;
1807 case ALC_INVALID_CONTEXT:
1808 value = alcErrInvalidContext;
1809 break;
1811 case ALC_OUT_OF_MEMORY:
1812 value = alcErrOutOfMemory;
1813 break;
1815 case ALC_DEVICE_SPECIFIER:
1816 if(VerifyDevice(pDevice))
1818 value = pDevice->szDeviceName;
1819 ALCdevice_DecRef(pDevice);
1821 else
1823 ProbeDeviceList();
1824 value = alcDeviceList;
1826 break;
1828 case ALC_ALL_DEVICES_SPECIFIER:
1829 ProbeAllDeviceList();
1830 value = alcAllDeviceList;
1831 break;
1833 case ALC_CAPTURE_DEVICE_SPECIFIER:
1834 if(VerifyDevice(pDevice))
1836 value = pDevice->szDeviceName;
1837 ALCdevice_DecRef(pDevice);
1839 else
1841 ProbeCaptureDeviceList();
1842 value = alcCaptureDeviceList;
1844 break;
1846 /* Default devices are always first in the list */
1847 case ALC_DEFAULT_DEVICE_SPECIFIER:
1848 if(!alcDeviceList)
1849 ProbeDeviceList();
1851 pDevice = VerifyDevice(pDevice);
1853 free(alcDefaultDeviceSpecifier);
1854 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1855 if(!alcDefaultDeviceSpecifier)
1856 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1858 value = alcDefaultDeviceSpecifier;
1859 if(pDevice) ALCdevice_DecRef(pDevice);
1860 break;
1862 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1863 if(!alcAllDeviceList)
1864 ProbeAllDeviceList();
1866 pDevice = VerifyDevice(pDevice);
1868 free(alcDefaultAllDeviceSpecifier);
1869 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1870 alcAllDeviceList : "");
1871 if(!alcDefaultAllDeviceSpecifier)
1872 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1874 value = alcDefaultAllDeviceSpecifier;
1875 if(pDevice) ALCdevice_DecRef(pDevice);
1876 break;
1878 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1879 if(!alcCaptureDeviceList)
1880 ProbeCaptureDeviceList();
1882 pDevice = VerifyDevice(pDevice);
1884 free(alcCaptureDefaultDeviceSpecifier);
1885 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1886 alcCaptureDeviceList : "");
1887 if(!alcCaptureDefaultDeviceSpecifier)
1888 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1890 value = alcCaptureDefaultDeviceSpecifier;
1891 if(pDevice) ALCdevice_DecRef(pDevice);
1892 break;
1894 case ALC_EXTENSIONS:
1895 if(!VerifyDevice(pDevice))
1896 value = alcNoDeviceExtList;
1897 else
1899 value = alcExtensionList;
1900 ALCdevice_DecRef(pDevice);
1902 break;
1904 default:
1905 pDevice = VerifyDevice(pDevice);
1906 alcSetError(pDevice, ALC_INVALID_ENUM);
1907 if(pDevice) ALCdevice_DecRef(pDevice);
1908 break;
1911 return value;
1915 /* alcGetIntegerv
1917 * Returns information about the Device and the version of Open AL
1919 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1921 device = VerifyDevice(device);
1923 if(size == 0 || data == NULL)
1925 alcSetError(device, ALC_INVALID_VALUE);
1926 if(device) ALCdevice_DecRef(device);
1927 return;
1930 if(!device)
1932 switch(param)
1934 case ALC_MAJOR_VERSION:
1935 *data = alcMajorVersion;
1936 break;
1937 case ALC_MINOR_VERSION:
1938 *data = alcMinorVersion;
1939 break;
1941 case ALC_ATTRIBUTES_SIZE:
1942 case ALC_ALL_ATTRIBUTES:
1943 case ALC_FREQUENCY:
1944 case ALC_REFRESH:
1945 case ALC_SYNC:
1946 case ALC_MONO_SOURCES:
1947 case ALC_STEREO_SOURCES:
1948 case ALC_CAPTURE_SAMPLES:
1949 case ALC_FORMAT_CHANNELS_SOFT:
1950 case ALC_FORMAT_TYPE_SOFT:
1951 alcSetError(NULL, ALC_INVALID_DEVICE);
1952 break;
1954 default:
1955 alcSetError(NULL, ALC_INVALID_ENUM);
1956 break;
1959 else if(device->IsCaptureDevice)
1961 switch(param)
1963 case ALC_CAPTURE_SAMPLES:
1964 LockDevice(device);
1965 *data = ALCdevice_AvailableSamples(device);
1966 UnlockDevice(device);
1967 break;
1969 case ALC_CONNECTED:
1970 *data = device->Connected;
1971 break;
1973 default:
1974 alcSetError(device, ALC_INVALID_ENUM);
1975 break;
1978 else /* render device */
1980 switch(param)
1982 case ALC_MAJOR_VERSION:
1983 *data = alcMajorVersion;
1984 break;
1986 case ALC_MINOR_VERSION:
1987 *data = alcMinorVersion;
1988 break;
1990 case ALC_EFX_MAJOR_VERSION:
1991 *data = alcEFXMajorVersion;
1992 break;
1994 case ALC_EFX_MINOR_VERSION:
1995 *data = alcEFXMinorVersion;
1996 break;
1998 case ALC_ATTRIBUTES_SIZE:
1999 *data = 13;
2000 break;
2002 case ALC_ALL_ATTRIBUTES:
2003 if(size < 13)
2004 alcSetError(device, ALC_INVALID_VALUE);
2005 else
2007 int i = 0;
2009 data[i++] = ALC_FREQUENCY;
2010 data[i++] = device->Frequency;
2012 if(!device->IsLoopbackDevice)
2014 data[i++] = ALC_REFRESH;
2015 data[i++] = device->Frequency / device->UpdateSize;
2017 data[i++] = ALC_SYNC;
2018 data[i++] = ALC_FALSE;
2020 else
2022 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2023 data[i++] = device->FmtChans;
2025 data[i++] = ALC_FORMAT_TYPE_SOFT;
2026 data[i++] = device->FmtType;
2029 data[i++] = ALC_MONO_SOURCES;
2030 data[i++] = device->NumMonoSources;
2032 data[i++] = ALC_STEREO_SOURCES;
2033 data[i++] = device->NumStereoSources;
2035 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2036 data[i++] = device->NumAuxSends;
2038 data[i++] = 0;
2040 break;
2042 case ALC_FREQUENCY:
2043 *data = device->Frequency;
2044 break;
2046 case ALC_REFRESH:
2047 if(device->IsLoopbackDevice)
2048 alcSetError(device, ALC_INVALID_DEVICE);
2049 else
2050 *data = device->Frequency / device->UpdateSize;
2051 break;
2053 case ALC_SYNC:
2054 if(device->IsLoopbackDevice)
2055 alcSetError(device, ALC_INVALID_DEVICE);
2056 else
2057 *data = ALC_FALSE;
2058 break;
2060 case ALC_FORMAT_CHANNELS_SOFT:
2061 if(!device->IsLoopbackDevice)
2062 alcSetError(device, ALC_INVALID_DEVICE);
2063 else
2064 *data = device->FmtChans;
2065 break;
2067 case ALC_FORMAT_TYPE_SOFT:
2068 if(!device->IsLoopbackDevice)
2069 alcSetError(device, ALC_INVALID_DEVICE);
2070 else
2071 *data = device->FmtType;
2072 break;
2074 case ALC_MONO_SOURCES:
2075 *data = device->NumMonoSources;
2076 break;
2078 case ALC_STEREO_SOURCES:
2079 *data = device->NumStereoSources;
2080 break;
2082 case ALC_MAX_AUXILIARY_SENDS:
2083 *data = device->NumAuxSends;
2084 break;
2086 case ALC_CONNECTED:
2087 *data = device->Connected;
2088 break;
2090 default:
2091 alcSetError(device, ALC_INVALID_ENUM);
2092 break;
2095 if(device)
2096 ALCdevice_DecRef(device);
2100 /* alcIsExtensionPresent
2102 * Determines if there is support for a particular extension
2104 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2106 ALCboolean bResult = ALC_FALSE;
2108 device = VerifyDevice(device);
2110 if(!extName)
2111 alcSetError(device, ALC_INVALID_VALUE);
2112 else
2114 size_t len = strlen(extName);
2115 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2116 while(ptr && *ptr)
2118 if(strncasecmp(ptr, extName, len) == 0 &&
2119 (ptr[len] == '\0' || isspace(ptr[len])))
2121 bResult = ALC_TRUE;
2122 break;
2124 if((ptr=strchr(ptr, ' ')) != NULL)
2126 do {
2127 ++ptr;
2128 } while(isspace(*ptr));
2132 if(device)
2133 ALCdevice_DecRef(device);
2134 return bResult;
2138 /* alcGetProcAddress
2140 * Retrieves the function address for a particular extension function
2142 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2144 ALCvoid *ptr = NULL;
2146 device = VerifyDevice(device);
2148 if(!funcName)
2149 alcSetError(device, ALC_INVALID_VALUE);
2150 else
2152 ALsizei i = 0;
2153 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2154 i++;
2155 ptr = alcFunctions[i].address;
2157 if(device)
2158 ALCdevice_DecRef(device);
2159 return ptr;
2163 /* alcGetEnumValue
2165 * Get the value for a particular ALC Enumerated Value
2167 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2169 ALCenum val = 0;
2171 device = VerifyDevice(device);
2173 if(!enumName)
2174 alcSetError(device, ALC_INVALID_VALUE);
2175 else
2177 ALsizei i = 0;
2178 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2179 i++;
2180 val = enumeration[i].value;
2182 if(device)
2183 ALCdevice_DecRef(device);
2184 return val;
2188 /* alcCreateContext
2190 * Create and attach a Context to a particular Device.
2192 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2194 ALCcontext *ALContext;
2196 LockLists();
2197 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2199 UnlockLists();
2200 alcSetError(device, ALC_INVALID_DEVICE);
2201 if(device) ALCdevice_DecRef(device);
2202 return NULL;
2205 /* Reset Context Last Error code */
2206 device->LastError = ALC_NO_ERROR;
2208 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2210 UnlockLists();
2211 alcSetError(device, ALC_INVALID_DEVICE);
2212 aluHandleDisconnect(device);
2213 ALCdevice_DecRef(device);
2214 return NULL;
2217 ALContext = calloc(1, sizeof(ALCcontext));
2218 if(ALContext)
2220 ALContext->ref = 1;
2222 ALContext->MaxActiveSources = 256;
2223 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2224 ALContext->MaxActiveSources);
2226 if(!ALContext || !ALContext->ActiveSources)
2228 if(!device->ContextList)
2230 ALCdevice_StopPlayback(device);
2231 device->Flags &= ~DEVICE_RUNNING;
2233 UnlockLists();
2235 free(ALContext);
2236 ALContext = NULL;
2238 alcSetError(device, ALC_OUT_OF_MEMORY);
2239 ALCdevice_DecRef(device);
2240 return NULL;
2243 ALContext->Device = device;
2244 ALCdevice_IncRef(device);
2245 InitContext(ALContext);
2247 do {
2248 ALContext->next = device->ContextList;
2249 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2250 UnlockLists();
2252 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2254 ALCdevice_DecRef(device);
2256 TRACE("Created context %p\n", ALContext);
2257 return ALContext;
2260 /* alcDestroyContext
2262 * Remove a Context
2264 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2266 ALCdevice *Device;
2268 LockLists();
2269 /* alcGetContextsDevice sets an error for invalid contexts */
2270 Device = alcGetContextsDevice(context);
2271 if(Device)
2273 ReleaseContext(context, Device);
2274 if(!Device->ContextList)
2276 ALCdevice_StopPlayback(Device);
2277 Device->Flags &= ~DEVICE_RUNNING;
2280 UnlockLists();
2284 /* alcGetCurrentContext
2286 * Returns the currently active Context
2288 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2290 ALCcontext *Context;
2292 Context = pthread_getspecific(LocalContext);
2293 if(!Context) Context = GlobalContext;
2295 return Context;
2298 /* alcGetThreadContext
2300 * Returns the currently active thread-local Context
2302 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2304 ALCcontext *Context;
2305 Context = pthread_getspecific(LocalContext);
2306 return Context;
2310 /* alcMakeContextCurrent
2312 * Makes the given Context the active Context
2314 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2316 /* context must be a valid Context or NULL */
2317 if(context && !(context=VerifyContext(context)))
2319 alcSetError(NULL, ALC_INVALID_CONTEXT);
2320 return ALC_FALSE;
2322 /* context's reference count is already incremented */
2323 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2324 if(context) ALCcontext_DecRef(context);
2326 if((context=pthread_getspecific(LocalContext)) != NULL)
2328 pthread_setspecific(LocalContext, NULL);
2329 ALCcontext_DecRef(context);
2332 return ALC_TRUE;
2335 /* alcSetThreadContext
2337 * Makes the given Context the active Context for the current thread
2339 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2341 ALCcontext *old;
2343 /* context must be a valid Context or NULL */
2344 if(context && !(context=VerifyContext(context)))
2346 alcSetError(NULL, ALC_INVALID_CONTEXT);
2347 return ALC_FALSE;
2349 /* context's reference count is already incremented */
2350 old = pthread_getspecific(LocalContext);
2351 pthread_setspecific(LocalContext, context);
2352 if(old) ALCcontext_DecRef(old);
2354 return ALC_TRUE;
2358 /* alcGetContextsDevice
2360 * Returns the Device that a particular Context is attached to
2362 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2364 ALCdevice *Device;
2366 if(!(Context=VerifyContext(Context)))
2368 alcSetError(NULL, ALC_INVALID_CONTEXT);
2369 return NULL;
2371 Device = Context->Device;
2372 ALCcontext_DecRef(Context);
2374 return Device;
2378 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2380 static const struct {
2381 const char name[32];
2382 enum DevFmtChannels channels;
2383 enum DevFmtType type;
2384 } formats[] = {
2385 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2386 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2387 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2388 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2389 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2390 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2392 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2393 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2394 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2395 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2396 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2397 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2399 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2400 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2401 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2402 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2403 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2404 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2406 size_t i;
2408 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2410 if(strcasecmp(str, formats[i].name) == 0)
2412 *chans = formats[i].channels;
2413 *type = formats[i].type;
2414 return;
2418 ERR("Unknown format: \"%s\"\n", str);
2419 *chans = DevFmtStereo;
2420 *type = DevFmtShort;
2423 /* alcOpenDevice
2425 * Open the Device specified.
2427 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2429 const ALCchar *fmt;
2430 ALCdevice *device;
2431 ALCenum err;
2433 DO_INITCONFIG();
2435 if(!PlaybackBackend.name)
2437 alcSetError(NULL, ALC_INVALID_VALUE);
2438 return NULL;
2441 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2442 deviceName = NULL;
2444 device = calloc(1, sizeof(ALCdevice)+sizeof(ALeffectslot));
2445 if(!device)
2447 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2448 return NULL;
2451 //Validate device
2452 device->Funcs = &PlaybackBackend.Funcs;
2453 device->ref = 1;
2454 device->Connected = ALC_TRUE;
2455 device->IsCaptureDevice = AL_FALSE;
2456 device->IsLoopbackDevice = AL_FALSE;
2457 InitializeCriticalSection(&device->Mutex);
2458 device->LastError = ALC_NO_ERROR;
2460 device->Flags = 0;
2461 device->Bs2b = NULL;
2462 device->Bs2bLevel = 0;
2463 device->szDeviceName = NULL;
2465 device->ContextList = NULL;
2467 device->MaxNoOfSources = 256;
2468 device->AuxiliaryEffectSlotMax = 4;
2469 device->NumAuxSends = MAX_SENDS;
2471 InitUIntMap(&device->BufferMap, ~0);
2472 InitUIntMap(&device->EffectMap, ~0);
2473 InitUIntMap(&device->FilterMap, ~0);
2475 //Set output format
2476 device->NumUpdates = 4;
2477 device->UpdateSize = 1024;
2479 device->Frequency = DEFAULT_OUTPUT_RATE;
2480 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2481 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2482 device->Frequency = maxu(device->Frequency, 8000);
2484 fmt = "AL_FORMAT_STEREO32";
2485 if(ConfigValueStr(NULL, "format", &fmt))
2486 device->Flags |= DEVICE_CHANNELS_REQUEST;
2487 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2489 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2490 if(device->NumUpdates < 2) device->NumUpdates = 4;
2492 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2493 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2495 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2496 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2498 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2499 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2501 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2502 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2504 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2506 device->NumStereoSources = 1;
2507 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2509 device->DefaultSlot = (ALeffectslot*)(device+1);
2510 if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR)
2511 device->DefaultSlot = NULL;
2513 // Find a playback device to open
2514 LockLists();
2515 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2517 UnlockLists();
2518 DeleteCriticalSection(&device->Mutex);
2519 free(device);
2520 alcSetError(NULL, err);
2521 return NULL;
2523 UnlockLists();
2525 do {
2526 device->next = DeviceList;
2527 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2529 TRACE("Created device %p\n", device);
2530 return device;
2533 /* alcCloseDevice
2535 * Close the specified Device
2537 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2539 ALCdevice *volatile*list;
2540 ALCcontext *ctx;
2542 LockLists();
2543 list = &DeviceList;
2544 while(*list && *list != pDevice)
2545 list = &(*list)->next;
2547 if(!*list || (*list)->IsCaptureDevice)
2549 alcSetError(*list, ALC_INVALID_DEVICE);
2550 UnlockLists();
2551 return ALC_FALSE;
2554 *list = (*list)->next;
2555 UnlockLists();
2557 if((ctx=pDevice->ContextList) != NULL)
2559 do {
2560 WARN("Releasing context %p\n", ctx);
2561 ReleaseContext(ctx, pDevice);
2562 } while((ctx=pDevice->ContextList) != NULL);
2563 ALCdevice_StopPlayback(pDevice);
2564 pDevice->Flags &= ~DEVICE_RUNNING;
2566 ALCdevice_ClosePlayback(pDevice);
2568 ALCdevice_DecRef(pDevice);
2570 return ALC_TRUE;
2574 /* alcLoopbackOpenDeviceSOFT
2576 * Open a loopback device, for manual rendering.
2578 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2580 ALCdevice *device;
2582 DO_INITCONFIG();
2584 device = calloc(1, sizeof(ALCdevice));
2585 if(!device)
2587 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2588 return NULL;
2591 //Validate device
2592 device->Funcs = &BackendLoopback.Funcs;
2593 device->ref = 1;
2594 device->Connected = ALC_TRUE;
2595 device->IsCaptureDevice = AL_FALSE;
2596 device->IsLoopbackDevice = AL_TRUE;
2597 InitializeCriticalSection(&device->Mutex);
2598 device->LastError = ALC_NO_ERROR;
2600 device->Flags = 0;
2601 device->Bs2b = NULL;
2602 device->Bs2bLevel = 0;
2603 device->szDeviceName = NULL;
2605 device->ContextList = NULL;
2607 device->MaxNoOfSources = 256;
2608 device->AuxiliaryEffectSlotMax = 4;
2609 device->NumAuxSends = MAX_SENDS;
2611 InitUIntMap(&device->BufferMap, ~0);
2612 InitUIntMap(&device->EffectMap, ~0);
2613 InitUIntMap(&device->FilterMap, ~0);
2615 //Set output format
2616 device->NumUpdates = 0;
2617 device->UpdateSize = 0;
2619 device->Frequency = 44100;
2620 device->FmtChans = DevFmtStereo;
2621 device->FmtType = DevFmtShort;
2623 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2624 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2626 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2627 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2629 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2630 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2632 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2634 device->NumStereoSources = 1;
2635 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2637 // Open the "backend"
2638 ALCdevice_OpenPlayback(device, "Loopback");
2639 do {
2640 device->next = DeviceList;
2641 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2643 TRACE("Created device %p\n", device);
2644 return device;
2647 /* alcIsRenderFormatSupportedSOFT
2649 * Determines if the loopback device supports the given format for rendering.
2651 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2653 ALCboolean ret = ALC_FALSE;
2655 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2656 alcSetError(device, ALC_INVALID_DEVICE);
2657 else if(freq <= 0)
2658 alcSetError(device, ALC_INVALID_VALUE);
2659 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2660 alcSetError(device, ALC_INVALID_ENUM);
2661 else
2663 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2664 freq >= 8000)
2665 ret = ALC_TRUE;
2667 if(device) ALCdevice_DecRef(device);
2669 return ret;
2672 /* alcRenderSamplesSOFT
2674 * Renders some samples into a buffer, using the format last set by the
2675 * attributes given to alcCreateContext.
2677 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2679 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2680 alcSetError(device, ALC_INVALID_DEVICE);
2681 else if(samples < 0 || (samples > 0 && buffer == NULL))
2682 alcSetError(device, ALC_INVALID_VALUE);
2683 else
2684 aluMixData(device, buffer, samples);
2685 if(device) ALCdevice_DecRef(device);
2689 static void ReleaseALC(void)
2691 ALCdevice *dev;
2693 free(alcDeviceList); alcDeviceList = NULL;
2694 alcDeviceListSize = 0;
2695 free(alcAllDeviceList); alcAllDeviceList = NULL;
2696 alcAllDeviceListSize = 0;
2697 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2698 alcCaptureDeviceListSize = 0;
2700 free(alcDefaultDeviceSpecifier);
2701 alcDefaultDeviceSpecifier = NULL;
2702 free(alcDefaultAllDeviceSpecifier);
2703 alcDefaultAllDeviceSpecifier = NULL;
2704 free(alcCaptureDefaultDeviceSpecifier);
2705 alcCaptureDefaultDeviceSpecifier = NULL;
2707 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2709 ALCuint num = 0;
2710 do {
2711 num++;
2712 } while((dev=dev->next) != NULL);
2713 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2717 ///////////////////////////////////////////////////////