Use more proper enum names for the resampler
[openal-soft.git] / Alc / ALc.c
blob1c7869192feb518b4e7e860c93f2ca322a3a0344
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_SOFTX_direct_channels AL_SOFT_loop_points";
382 // Mixing Priority Level
383 ALint RTPrioLevel;
385 // Output Log File
386 FILE *LogFile;
388 // Output Log Level
389 #ifdef _DEBUG
390 enum LogLevel LogLevel = LogWarning;
391 #else
392 enum LogLevel LogLevel = LogError;
393 #endif
395 /* Flag to trap ALC device errors */
396 static ALCboolean TrapALCError = ALC_FALSE;
398 /* One-time configuration init control */
399 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
401 /* Forced effect that applies to sources that don't have an effect on send 0 */
402 static ALeffect ForcedEffect;
404 ///////////////////////////////////////////////////////
407 ///////////////////////////////////////////////////////
408 // ALC Related helper functions
409 static void ReleaseALC(void);
410 static void ReleaseThreadCtx(void *ptr);
412 static void alc_initconfig(void);
413 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
415 #if defined(_WIN32)
416 static void alc_init(void);
417 static void alc_deinit(void);
418 static void alc_deinit_safe(void);
420 UIntMap TlsDestructor;
422 #ifndef AL_LIBTYPE_STATIC
423 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
425 ALsizei i;
426 (void)hModule;
428 // Perform actions based on the reason for calling.
429 switch(ul_reason_for_call)
431 case DLL_PROCESS_ATTACH:
432 InitUIntMap(&TlsDestructor, ~0);
433 alc_init();
434 break;
436 case DLL_THREAD_DETACH:
437 LockUIntMapRead(&TlsDestructor);
438 for(i = 0;i < TlsDestructor.size;i++)
440 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
441 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
442 if(ptr && callback)
443 callback(ptr);
445 UnlockUIntMapRead(&TlsDestructor);
446 break;
448 case DLL_PROCESS_DETACH:
449 if(!lpReserved)
450 alc_deinit();
451 else
452 alc_deinit_safe();
453 ResetUIntMap(&TlsDestructor);
454 break;
456 return TRUE;
458 #elif defined(_MSC_VER)
459 #pragma section(".CRT$XCU",read)
460 static void alc_constructor(void);
461 static void alc_destructor(void);
462 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
464 static void alc_constructor(void)
466 atexit(alc_destructor);
467 alc_init();
470 static void alc_destructor(void)
472 alc_deinit();
474 #elif defined(HAVE_GCC_DESTRUCTOR)
475 static void alc_init(void) __attribute__((constructor));
476 static void alc_deinit(void) __attribute__((destructor));
477 #else
478 #error "No static initialization available on this platform!"
479 #endif
480 #elif defined(HAVE_GCC_DESTRUCTOR)
481 static void alc_init(void) __attribute__((constructor));
482 static void alc_deinit(void) __attribute__((destructor));
483 #else
484 #error "No global initialization available on this platform!"
485 #endif
487 static void alc_init(void)
489 const char *str;
491 LogFile = stderr;
493 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
494 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
495 ConeScale = 1.0f;
497 str = getenv("__ALSOFT_REVERSE_Z");
498 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
499 ZScale = -1.0f;
501 str = getenv("__ALSOFT_TRAP_ERROR");
502 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
504 TrapALError = AL_TRUE;
505 TrapALCError = AL_TRUE;
507 else
509 str = getenv("__ALSOFT_TRAP_AL_ERROR");
510 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
511 TrapALError = AL_TRUE;
513 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
514 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
515 TrapALCError = ALC_TRUE;
518 pthread_key_create(&LocalContext, ReleaseThreadCtx);
519 InitializeCriticalSection(&ListLock);
520 ThunkInit();
523 static void alc_deinit_safe(void)
525 ReleaseALC();
527 FreeHrtf();
528 FreeALConfig();
530 ThunkExit();
531 DeleteCriticalSection(&ListLock);
532 pthread_key_delete(LocalContext);
534 if(LogFile != stderr)
535 fclose(LogFile);
536 LogFile = NULL;
539 static void alc_deinit(void)
541 int i;
543 ReleaseALC();
545 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
546 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
548 for(i = 0;BackendList[i].Deinit;i++)
549 BackendList[i].Deinit();
550 BackendLoopback.Deinit();
552 alc_deinit_safe();
555 static void alc_initconfig(void)
557 const char *devs, *str;
558 float valf;
559 int i, n;
561 str = getenv("ALSOFT_LOGLEVEL");
562 if(str)
564 long lvl = strtol(str, NULL, 0);
565 if(lvl >= NoLog && lvl <= LogRef)
566 LogLevel = lvl;
569 str = getenv("ALSOFT_LOGFILE");
570 if(str && str[0])
572 FILE *logfile = fopen(str, "wat");
573 if(logfile) LogFile = logfile;
574 else ERR("Failed to open log file '%s'\n", str);
577 ReadALConfig();
579 InitHrtf();
581 #ifdef _WIN32
582 RTPrioLevel = 1;
583 #else
584 RTPrioLevel = 0;
585 #endif
586 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
588 if(ConfigValueStr(NULL, "resampler", &str))
590 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
591 DefaultResampler = PointResampler;
592 else if(strcasecmp(str, "linear") == 0)
593 DefaultResampler = LinearResampler;
594 else if(strcasecmp(str, "cubic") == 0)
595 DefaultResampler = CubicResampler;
596 else
598 char *end;
600 n = strtol(str, &end, 0);
601 if(*end == '\0' && (n == PointResampler || n == LinearResampler || n == CubicResampler))
602 DefaultResampler = n;
603 else
604 WARN("Invalid resampler: %s\n", str);
608 if(!TrapALCError)
609 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
611 if(!TrapALError)
612 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
614 if(ConfigValueFloat("reverb", "boost", &valf))
615 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
617 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
619 if(ConfigValueStr(NULL, "drivers", &devs))
621 int n;
622 size_t len;
623 const char *next = devs;
624 int endlist, delitem;
626 i = 0;
627 do {
628 devs = next;
629 next = strchr(devs, ',');
631 delitem = (devs[0] == '-');
632 if(devs[0] == '-') devs++;
634 if(!devs[0] || devs[0] == ',')
636 endlist = 0;
637 continue;
639 endlist = 1;
641 len = (next ? ((size_t)(next-devs)) : strlen(devs));
642 for(n = i;BackendList[n].Init;n++)
644 if(len == strlen(BackendList[n].name) &&
645 strncmp(BackendList[n].name, devs, len) == 0)
647 if(delitem)
649 do {
650 BackendList[n] = BackendList[n+1];
651 ++n;
652 } while(BackendList[n].Init);
654 else
656 struct BackendInfo Bkp = BackendList[n];
657 while(n > i)
659 BackendList[n] = BackendList[n-1];
660 --n;
662 BackendList[n] = Bkp;
664 i++;
666 break;
669 } while(next++);
671 if(endlist)
673 BackendList[i].name = NULL;
674 BackendList[i].Init = NULL;
675 BackendList[i].Deinit = NULL;
676 BackendList[i].Probe = NULL;
680 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
682 if(!BackendList[i].Init(&BackendList[i].Funcs))
684 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
685 continue;
688 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
689 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
691 PlaybackBackend = BackendList[i];
692 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
694 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
696 CaptureBackend = BackendList[i];
697 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
700 BackendLoopback.Init(&BackendLoopback.Funcs);
702 if(ConfigValueStr(NULL, "excludefx", &str))
704 size_t len;
705 const char *next = str;
707 do {
708 str = next;
709 next = strchr(str, ',');
711 if(!str[0] || next == str)
712 continue;
714 len = (next ? ((size_t)(next-str)) : strlen(str));
715 for(n = 0;EffectList[n].name;n++)
717 if(len == strlen(EffectList[n].name) &&
718 strncmp(EffectList[n].name, str, len) == 0)
719 DisabledEffects[EffectList[n].type] = AL_TRUE;
721 } while(next++);
724 InitEffect(&ForcedEffect);
725 str = getenv("__ALSOFT_DEFAULT_REVERB");
726 if(str && str[0])
727 GetReverbEffect(str, &ForcedEffect);
728 else if(ConfigValueStr(NULL, "default-reverb", &str))
729 GetReverbEffect(str, &ForcedEffect);
733 static void LockLists(void)
735 EnterCriticalSection(&ListLock);
738 static void UnlockLists(void)
740 LeaveCriticalSection(&ListLock);
744 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
746 DO_INITCONFIG();
748 LockLists();
749 free(*list);
750 *list = NULL;
751 *listsize = 0;
753 if(type == CAPTURE_DEVICE_PROBE)
754 CaptureBackend.Probe(type);
755 else
756 PlaybackBackend.Probe(type);
757 UnlockLists();
760 static void ProbeDeviceList(void)
761 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
762 static void ProbeAllDeviceList(void)
763 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
764 static void ProbeCaptureDeviceList(void)
765 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
768 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
770 size_t len = strlen(name);
771 void *temp;
773 if(len == 0)
774 return;
776 temp = realloc(*List, (*ListSize) + len + 2);
777 if(!temp)
779 ERR("Realloc failed to add %s!\n", name);
780 return;
782 *List = temp;
784 memcpy((*List)+(*ListSize), name, len+1);
785 *ListSize += len+1;
786 (*List)[*ListSize] = 0;
789 #define DECL_APPEND_LIST_FUNC(type) \
790 void Append##type##List(const ALCchar *name) \
791 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
793 DECL_APPEND_LIST_FUNC(Device)
794 DECL_APPEND_LIST_FUNC(AllDevice)
795 DECL_APPEND_LIST_FUNC(CaptureDevice)
797 #undef DECL_APPEND_LIST_FUNC
800 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
801 void SetDefaultChannelOrder(ALCdevice *device)
803 switch(device->FmtChans)
805 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
806 device->DevChannels[1] = FRONT_RIGHT;
807 device->DevChannels[2] = BACK_LEFT;
808 device->DevChannels[3] = BACK_RIGHT;
809 device->DevChannels[4] = FRONT_CENTER;
810 device->DevChannels[5] = LFE;
811 return;
813 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
814 device->DevChannels[1] = FRONT_RIGHT;
815 device->DevChannels[2] = BACK_LEFT;
816 device->DevChannels[3] = BACK_RIGHT;
817 device->DevChannels[4] = FRONT_CENTER;
818 device->DevChannels[5] = LFE;
819 device->DevChannels[6] = SIDE_LEFT;
820 device->DevChannels[7] = SIDE_RIGHT;
821 return;
823 /* Same as WFX order */
824 case DevFmtMono:
825 case DevFmtStereo:
826 case DevFmtQuad:
827 case DevFmtX51Side:
828 case DevFmtX61:
829 break;
831 SetDefaultWFXChannelOrder(device);
833 /* Sets the default order used by WaveFormatEx */
834 void SetDefaultWFXChannelOrder(ALCdevice *device)
836 switch(device->FmtChans)
838 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
840 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
841 device->DevChannels[1] = FRONT_RIGHT; break;
843 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
844 device->DevChannels[1] = FRONT_RIGHT;
845 device->DevChannels[2] = BACK_LEFT;
846 device->DevChannels[3] = BACK_RIGHT; break;
848 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
849 device->DevChannels[1] = FRONT_RIGHT;
850 device->DevChannels[2] = FRONT_CENTER;
851 device->DevChannels[3] = LFE;
852 device->DevChannels[4] = BACK_LEFT;
853 device->DevChannels[5] = BACK_RIGHT; break;
855 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
856 device->DevChannels[1] = FRONT_RIGHT;
857 device->DevChannels[2] = FRONT_CENTER;
858 device->DevChannels[3] = LFE;
859 device->DevChannels[4] = SIDE_LEFT;
860 device->DevChannels[5] = SIDE_RIGHT; break;
862 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
863 device->DevChannels[1] = FRONT_RIGHT;
864 device->DevChannels[2] = FRONT_CENTER;
865 device->DevChannels[3] = LFE;
866 device->DevChannels[4] = BACK_CENTER;
867 device->DevChannels[5] = SIDE_LEFT;
868 device->DevChannels[6] = SIDE_RIGHT; break;
870 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
871 device->DevChannels[1] = FRONT_RIGHT;
872 device->DevChannels[2] = FRONT_CENTER;
873 device->DevChannels[3] = LFE;
874 device->DevChannels[4] = BACK_LEFT;
875 device->DevChannels[5] = BACK_RIGHT;
876 device->DevChannels[6] = SIDE_LEFT;
877 device->DevChannels[7] = SIDE_RIGHT; break;
882 const ALCchar *DevFmtTypeString(enum DevFmtType type)
884 switch(type)
886 case DevFmtByte: return "Signed Byte";
887 case DevFmtUByte: return "Unsigned Byte";
888 case DevFmtShort: return "Signed Short";
889 case DevFmtUShort: return "Unsigned Short";
890 case DevFmtFloat: return "Float";
892 return "(unknown type)";
894 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
896 switch(chans)
898 case DevFmtMono: return "Mono";
899 case DevFmtStereo: return "Stereo";
900 case DevFmtQuad: return "Quadraphonic";
901 case DevFmtX51: return "5.1 Surround";
902 case DevFmtX51Side: return "5.1 Side";
903 case DevFmtX61: return "6.1 Surround";
904 case DevFmtX71: return "7.1 Surround";
906 return "(unknown channels)";
909 ALuint BytesFromDevFmt(enum DevFmtType type)
911 switch(type)
913 case DevFmtByte: return sizeof(ALbyte);
914 case DevFmtUByte: return sizeof(ALubyte);
915 case DevFmtShort: return sizeof(ALshort);
916 case DevFmtUShort: return sizeof(ALushort);
917 case DevFmtFloat: return sizeof(ALfloat);
919 return 0;
921 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
923 switch(chans)
925 case DevFmtMono: return 1;
926 case DevFmtStereo: return 2;
927 case DevFmtQuad: return 4;
928 case DevFmtX51: return 6;
929 case DevFmtX51Side: return 6;
930 case DevFmtX61: return 7;
931 case DevFmtX71: return 8;
933 return 0;
935 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
936 enum DevFmtType *type)
938 static const struct {
939 ALenum format;
940 enum DevFmtChannels channels;
941 enum DevFmtType type;
942 } list[] = {
943 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
944 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
945 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
947 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
948 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
949 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
951 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
952 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
953 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
955 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
956 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
957 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
959 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
960 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
961 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
963 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
964 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
965 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
967 ALuint i;
969 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
971 if(list[i].format == format)
973 *chans = list[i].channels;
974 *type = list[i].type;
975 return AL_TRUE;
979 return AL_FALSE;
982 static ALCboolean IsValidALCType(ALCenum type)
984 switch(type)
986 case ALC_BYTE_SOFT:
987 case ALC_UNSIGNED_BYTE_SOFT:
988 case ALC_SHORT_SOFT:
989 case ALC_UNSIGNED_SHORT_SOFT:
990 case ALC_INT_SOFT:
991 case ALC_UNSIGNED_INT_SOFT:
992 case ALC_FLOAT_SOFT:
993 return ALC_TRUE;
995 return ALC_FALSE;
998 static ALCboolean IsValidALCChannels(ALCenum channels)
1000 switch(channels)
1002 case ALC_MONO_SOFT:
1003 case ALC_STEREO_SOFT:
1004 case ALC_QUAD_SOFT:
1005 case ALC_5POINT1_SOFT:
1006 case ALC_6POINT1_SOFT:
1007 case ALC_7POINT1_SOFT:
1008 return ALC_TRUE;
1010 return ALC_FALSE;
1014 /* alcSetError
1016 * Stores the latest ALC Error
1018 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1020 if(TrapALCError)
1022 #ifdef _WIN32
1023 /* DebugBreak() will cause an exception if there is no debugger */
1024 if(IsDebuggerPresent())
1025 DebugBreak();
1026 #elif defined(SIGTRAP)
1027 raise(SIGTRAP);
1028 #endif
1031 if(device)
1032 device->LastError = errorCode;
1033 else
1034 g_eLastNullDeviceError = errorCode;
1038 /* UpdateDeviceParams
1040 * Updates device parameters according to the attribute list (caller is
1041 * responsible for holding the list lock).
1043 static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1045 ALCcontext *context;
1046 enum DevFmtChannels oldChans;
1047 enum DevFmtType oldType;
1048 ALCuint oldFreq;
1049 int oldMode;
1050 ALuint i;
1052 if(device->IsLoopbackDevice && !(attrList && attrList[0]))
1054 WARN("Missing attributes for loopback device\n");
1055 return ALC_INVALID_VALUE;
1058 // Check for attributes
1059 if(attrList && attrList[0])
1061 enum {
1062 GotFreq = 1<<0,
1063 GotChans = 1<<1,
1064 GotType = 1<<2,
1065 GotAll = GotFreq|GotChans|GotType
1067 ALCuint freq, numMono, numStereo, numSends;
1068 enum DevFmtChannels schans;
1069 enum DevFmtType stype;
1070 ALCuint attrIdx = 0;
1071 ALCint gotFmt = 0;
1073 // If a context is already running on the device, stop playback so the
1074 // device attributes can be updated
1075 if((device->Flags&DEVICE_RUNNING))
1076 ALCdevice_StopPlayback(device);
1077 device->Flags &= ~DEVICE_RUNNING;
1079 freq = device->Frequency;
1080 schans = device->FmtChans;
1081 stype = device->FmtType;
1082 numMono = device->NumMonoSources;
1083 numStereo = device->NumStereoSources;
1084 numSends = device->NumAuxSends;
1086 while(attrList[attrIdx])
1088 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1089 device->IsLoopbackDevice)
1091 ALCint val = attrList[attrIdx + 1];
1092 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1093 return ALC_INVALID_VALUE;
1094 schans = val;
1095 gotFmt |= GotChans;
1098 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1099 device->IsLoopbackDevice)
1101 ALCint val = attrList[attrIdx + 1];
1102 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1103 return ALC_INVALID_VALUE;
1104 stype = val;
1105 gotFmt |= GotType;
1108 if(attrList[attrIdx] == ALC_FREQUENCY)
1110 if(device->IsLoopbackDevice)
1112 freq = attrList[attrIdx + 1];
1113 if(freq < 8000)
1114 return ALC_INVALID_VALUE;
1115 gotFmt |= GotFreq;
1117 else
1119 freq = attrList[attrIdx + 1];
1120 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1124 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1126 numStereo = attrList[attrIdx + 1];
1127 if(numStereo > device->MaxNoOfSources)
1128 numStereo = device->MaxNoOfSources;
1130 numMono = device->MaxNoOfSources - numStereo;
1133 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1134 numSends = attrList[attrIdx + 1];
1136 attrIdx += 2;
1139 if(device->IsLoopbackDevice)
1141 if(gotFmt != GotAll)
1143 WARN("Missing format for loopback device\n");
1144 return ALC_INVALID_VALUE;
1147 else
1149 ConfigValueUInt(NULL, "frequency", &freq);
1150 freq = maxu(freq, 8000);
1152 ConfigValueUInt(NULL, "sends", &numSends);
1153 numSends = minu(MAX_SENDS, numSends);
1155 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1156 device->Frequency;
1158 device->Frequency = freq;
1159 device->FmtChans = schans;
1160 device->FmtType = stype;
1161 device->NumMonoSources = numMono;
1162 device->NumStereoSources = numStereo;
1163 device->NumAuxSends = numSends;
1166 if((device->Flags&DEVICE_RUNNING))
1167 return ALC_NO_ERROR;
1169 LockDevice(device);
1171 oldFreq = device->Frequency;
1172 oldChans = device->FmtChans;
1173 oldType = device->FmtType;
1175 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1176 DevFmtChannelsString(device->FmtChans),
1177 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1178 DevFmtTypeString(device->FmtType), device->Frequency,
1179 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1180 device->UpdateSize, device->NumUpdates);
1181 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1183 UnlockDevice(device);
1184 return ALC_INVALID_DEVICE;
1186 device->Flags |= DEVICE_RUNNING;
1188 if(device->FmtChans != oldChans)
1190 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1191 ERR("Failed to set %s, got %s instead\n",
1192 DevFmtChannelsString(oldChans),
1193 DevFmtChannelsString(device->FmtChans));
1194 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1196 if(device->Frequency != oldFreq)
1198 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1199 ERR("Failed to set %uhz, got %uhz instead\n",
1200 oldFreq, device->Frequency);
1201 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1204 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1205 DevFmtChannelsString(device->FmtChans),
1206 DevFmtTypeString(device->FmtType), device->Frequency,
1207 device->UpdateSize, device->NumUpdates);
1209 aluInitPanning(device);
1211 for(i = 0;i < MAXCHANNELS;i++)
1213 device->ClickRemoval[i] = 0.0f;
1214 device->PendingClicks[i] = 0.0f;
1217 device->Hrtf = NULL;
1218 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1219 device->Hrtf = GetHrtf(device);
1220 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1222 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1224 if(!device->Bs2b)
1226 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1227 bs2b_clear(device->Bs2b);
1229 bs2b_set_srate(device->Bs2b, device->Frequency);
1230 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1231 TRACE("BS2B level %d\n", device->Bs2bLevel);
1233 else
1235 free(device->Bs2b);
1236 device->Bs2b = NULL;
1237 TRACE("BS2B disabled\n");
1240 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1241 switch(device->FmtChans)
1243 case DevFmtMono:
1244 case DevFmtStereo:
1245 break;
1246 case DevFmtQuad:
1247 case DevFmtX51:
1248 case DevFmtX51Side:
1249 case DevFmtX61:
1250 case DevFmtX71:
1251 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1252 device->Flags |= DEVICE_DUPLICATE_STEREO;
1253 break;
1255 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1257 oldMode = SetMixerFPUMode();
1258 context = device->ContextList;
1259 while(context)
1261 ALsizei pos;
1263 context->UpdateSources = AL_FALSE;
1264 LockUIntMapRead(&context->EffectSlotMap);
1265 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1267 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1269 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1271 UnlockUIntMapRead(&context->EffectSlotMap);
1272 RestoreFPUMode(oldMode);
1273 UnlockDevice(device);
1274 ALCdevice_StopPlayback(device);
1275 device->Flags &= ~DEVICE_RUNNING;
1276 return ALC_INVALID_DEVICE;
1278 slot->NeedsUpdate = AL_FALSE;
1279 ALeffectState_Update(slot->EffectState, context, slot);
1281 UnlockUIntMapRead(&context->EffectSlotMap);
1283 LockUIntMapRead(&context->SourceMap);
1284 for(pos = 0;pos < context->SourceMap.size;pos++)
1286 ALsource *source = context->SourceMap.array[pos].value;
1287 ALuint s = device->NumAuxSends;
1288 while(s < MAX_SENDS)
1290 if(source->Send[s].Slot)
1291 DecrementRef(&source->Send[s].Slot->ref);
1292 source->Send[s].Slot = NULL;
1293 source->Send[s].WetGain = 1.0f;
1294 source->Send[s].WetGainHF = 1.0f;
1295 s++;
1297 source->NeedsUpdate = AL_FALSE;
1298 ALsource_Update(source, context);
1300 UnlockUIntMapRead(&context->SourceMap);
1302 context = context->next;
1304 RestoreFPUMode(oldMode);
1305 UnlockDevice(device);
1307 return ALC_NO_ERROR;
1310 /* FreeDevice
1312 * Frees the device structure, and destroys any objects the app failed to
1313 * delete. Called once there's no more references on the device.
1315 static ALCvoid FreeDevice(ALCdevice *device)
1317 TRACE("%p\n", device);
1319 if(device->DefaultSlot)
1321 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1322 device->DefaultSlot->EffectState = NULL;
1325 if(device->BufferMap.size > 0)
1327 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1328 ReleaseALBuffers(device);
1330 ResetUIntMap(&device->BufferMap);
1332 if(device->EffectMap.size > 0)
1334 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1335 ReleaseALEffects(device);
1337 ResetUIntMap(&device->EffectMap);
1339 if(device->FilterMap.size > 0)
1341 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1342 ReleaseALFilters(device);
1344 ResetUIntMap(&device->FilterMap);
1346 free(device->Bs2b);
1347 device->Bs2b = NULL;
1349 free(device->szDeviceName);
1350 device->szDeviceName = NULL;
1352 DeleteCriticalSection(&device->Mutex);
1354 free(device);
1358 void ALCdevice_IncRef(ALCdevice *device)
1360 RefCount ref;
1361 ref = IncrementRef(&device->ref);
1362 TRACEREF("%p increasing refcount to %u\n", device, ref);
1365 void ALCdevice_DecRef(ALCdevice *device)
1367 RefCount ref;
1368 ref = DecrementRef(&device->ref);
1369 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1370 if(ref == 0) FreeDevice(device);
1373 /* VerifyDevice
1375 * Checks if the device handle is valid, and increments its ref count if so.
1377 static ALCdevice *VerifyDevice(ALCdevice *device)
1379 ALCdevice *tmpDevice;
1381 if(!device)
1382 return NULL;
1384 LockLists();
1385 tmpDevice = DeviceList;
1386 while(tmpDevice && tmpDevice != device)
1387 tmpDevice = tmpDevice->next;
1389 if(tmpDevice)
1390 ALCdevice_IncRef(tmpDevice);
1391 UnlockLists();
1392 return tmpDevice;
1396 /* InitContext
1398 * Initializes context variables
1400 static ALvoid InitContext(ALCcontext *pContext)
1402 ALint i, j;
1404 //Initialise listener
1405 pContext->Listener.Gain = 1.0f;
1406 pContext->Listener.MetersPerUnit = 1.0f;
1407 pContext->Listener.Position[0] = 0.0f;
1408 pContext->Listener.Position[1] = 0.0f;
1409 pContext->Listener.Position[2] = 0.0f;
1410 pContext->Listener.Velocity[0] = 0.0f;
1411 pContext->Listener.Velocity[1] = 0.0f;
1412 pContext->Listener.Velocity[2] = 0.0f;
1413 pContext->Listener.Forward[0] = 0.0f;
1414 pContext->Listener.Forward[1] = 0.0f;
1415 pContext->Listener.Forward[2] = -1.0f;
1416 pContext->Listener.Up[0] = 0.0f;
1417 pContext->Listener.Up[1] = 1.0f;
1418 pContext->Listener.Up[2] = 0.0f;
1419 for(i = 0;i < 4;i++)
1421 for(j = 0;j < 4;j++)
1422 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1425 //Validate pContext
1426 pContext->LastError = AL_NO_ERROR;
1427 pContext->UpdateSources = AL_FALSE;
1428 pContext->ActiveSourceCount = 0;
1429 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1430 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1432 //Set globals
1433 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1434 pContext->SourceDistanceModel = AL_FALSE;
1435 pContext->DopplerFactor = 1.0f;
1436 pContext->DopplerVelocity = 1.0f;
1437 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1438 pContext->DeferUpdates = AL_FALSE;
1440 pContext->ExtensionList = alExtList;
1444 /* FreeContext
1446 * Cleans up the context, and destroys any remaining objects the app failed to
1447 * delete. Called once there's no more references on the context.
1449 static ALCvoid FreeContext(ALCcontext *context)
1451 TRACE("%p\n", context);
1453 if(context->SourceMap.size > 0)
1455 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1456 ReleaseALSources(context);
1458 ResetUIntMap(&context->SourceMap);
1460 if(context->EffectSlotMap.size > 0)
1462 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1463 ReleaseALAuxiliaryEffectSlots(context);
1465 ResetUIntMap(&context->EffectSlotMap);
1467 context->ActiveSourceCount = 0;
1468 free(context->ActiveSources);
1469 context->ActiveSources = NULL;
1470 context->MaxActiveSources = 0;
1472 context->ActiveEffectSlotCount = 0;
1473 free(context->ActiveEffectSlots);
1474 context->ActiveEffectSlots = NULL;
1475 context->MaxActiveEffectSlots = 0;
1477 ALCdevice_DecRef(context->Device);
1478 context->Device = NULL;
1480 //Invalidate context
1481 memset(context, 0, sizeof(ALCcontext));
1482 free(context);
1485 /* ReleaseContext
1487 * Removes the context reference from the given device and removes it from
1488 * being current on the running thread or globally.
1490 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1492 ALCcontext *volatile*tmp_ctx;
1494 if(pthread_getspecific(LocalContext) == context)
1496 WARN("%p released while current on thread\n", context);
1497 pthread_setspecific(LocalContext, NULL);
1498 ALCcontext_DecRef(context);
1501 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1502 ALCcontext_DecRef(context);
1504 LockDevice(device);
1505 tmp_ctx = &device->ContextList;
1506 while(*tmp_ctx)
1508 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1509 break;
1510 tmp_ctx = &(*tmp_ctx)->next;
1512 UnlockDevice(device);
1514 ALCcontext_DecRef(context);
1517 void ALCcontext_IncRef(ALCcontext *context)
1519 RefCount ref;
1520 ref = IncrementRef(&context->ref);
1521 TRACEREF("%p increasing refcount to %u\n", context, ref);
1524 void ALCcontext_DecRef(ALCcontext *context)
1526 RefCount ref;
1527 ref = DecrementRef(&context->ref);
1528 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1529 if(ref == 0) FreeContext(context);
1532 static void ReleaseThreadCtx(void *ptr)
1534 WARN("%p current for thread being destroyed\n", ptr);
1535 ALCcontext_DecRef(ptr);
1538 /* VerifyContext
1540 * Checks that the given context is valid, and increments its reference count.
1542 static ALCcontext *VerifyContext(ALCcontext *context)
1544 ALCdevice *dev;
1546 LockLists();
1547 dev = DeviceList;
1548 while(dev)
1550 ALCcontext *tmp_ctx = dev->ContextList;
1551 while(tmp_ctx)
1553 if(tmp_ctx == context)
1555 ALCcontext_IncRef(tmp_ctx);
1556 UnlockLists();
1557 return tmp_ctx;
1559 tmp_ctx = tmp_ctx->next;
1561 dev = dev->next;
1563 UnlockLists();
1565 return NULL;
1569 /* GetContextRef
1571 * Returns the currently active context, and adds a reference without locking
1572 * it.
1574 ALCcontext *GetContextRef(void)
1576 ALCcontext *context;
1578 context = pthread_getspecific(LocalContext);
1579 if(context)
1580 ALCcontext_IncRef(context);
1581 else
1583 LockLists();
1584 context = GlobalContext;
1585 if(context)
1586 ALCcontext_IncRef(context);
1587 UnlockLists();
1590 return context;
1593 ///////////////////////////////////////////////////////
1596 ///////////////////////////////////////////////////////
1597 // ALC Functions calls
1600 // This should probably move to another c file but for now ...
1601 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1603 ALCdevice *device = NULL;
1604 ALCenum err;
1606 DO_INITCONFIG();
1608 if(!CaptureBackend.name)
1610 alcSetError(NULL, ALC_INVALID_VALUE);
1611 return NULL;
1614 if(SampleSize <= 0)
1616 alcSetError(NULL, ALC_INVALID_VALUE);
1617 return NULL;
1620 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1621 deviceName = NULL;
1623 device = calloc(1, sizeof(ALCdevice));
1624 if(!device)
1626 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1627 return NULL;
1630 //Validate device
1631 device->Funcs = &CaptureBackend.Funcs;
1632 device->ref = 1;
1633 device->Connected = ALC_TRUE;
1634 device->IsCaptureDevice = AL_TRUE;
1635 device->IsLoopbackDevice = AL_FALSE;
1636 InitializeCriticalSection(&device->Mutex);
1638 InitUIntMap(&device->BufferMap, ~0);
1639 InitUIntMap(&device->EffectMap, ~0);
1640 InitUIntMap(&device->FilterMap, ~0);
1642 device->szDeviceName = NULL;
1644 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1645 device->Frequency = frequency;
1647 device->Flags |= DEVICE_CHANNELS_REQUEST;
1648 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1650 DeleteCriticalSection(&device->Mutex);
1651 free(device);
1652 alcSetError(NULL, ALC_INVALID_ENUM);
1653 return NULL;
1656 device->UpdateSize = SampleSize;
1657 device->NumUpdates = 1;
1659 LockLists();
1660 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1662 UnlockLists();
1663 DeleteCriticalSection(&device->Mutex);
1664 free(device);
1665 alcSetError(NULL, err);
1666 return NULL;
1668 UnlockLists();
1670 do {
1671 device->next = DeviceList;
1672 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1674 TRACE("Created device %p\n", device);
1675 return device;
1678 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1680 ALCdevice *volatile*list;
1682 LockLists();
1683 list = &DeviceList;
1684 while(*list && *list != pDevice)
1685 list = &(*list)->next;
1687 if(!*list || !(*list)->IsCaptureDevice)
1689 alcSetError(*list, ALC_INVALID_DEVICE);
1690 UnlockLists();
1691 return ALC_FALSE;
1694 *list = (*list)->next;
1695 UnlockLists();
1697 LockDevice(pDevice);
1698 ALCdevice_CloseCapture(pDevice);
1699 UnlockDevice(pDevice);
1701 ALCdevice_DecRef(pDevice);
1703 return ALC_TRUE;
1706 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1708 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1710 alcSetError(device, ALC_INVALID_DEVICE);
1711 if(device) ALCdevice_DecRef(device);
1712 return;
1714 LockDevice(device);
1715 if(device->Connected)
1716 ALCdevice_StartCapture(device);
1717 UnlockDevice(device);
1719 ALCdevice_DecRef(device);
1722 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1724 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1726 alcSetError(device, ALC_INVALID_DEVICE);
1727 if(device) ALCdevice_DecRef(device);
1728 return;
1730 LockDevice(device);
1731 if(device->Connected)
1732 ALCdevice_StopCapture(device);
1733 UnlockDevice(device);
1735 ALCdevice_DecRef(device);
1738 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1740 ALCenum err = ALC_INVALID_DEVICE;
1741 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1743 err = ALC_INVALID_VALUE;
1744 LockDevice(device);
1745 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1746 err = ALCdevice_CaptureSamples(device, buffer, samples);
1747 UnlockDevice(device);
1749 if(err != ALC_NO_ERROR)
1750 alcSetError(device, err);
1751 if(device) ALCdevice_DecRef(device);
1755 alcGetError
1757 Return last ALC generated error code
1759 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1761 ALCenum errorCode;
1763 if(VerifyDevice(device))
1765 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1766 ALCdevice_DecRef(device);
1768 else
1769 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1771 return errorCode;
1775 /* alcSuspendContext
1777 * Not functional
1779 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1781 (void)Context;
1784 /* alcProcessContext
1786 * Not functional
1788 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1790 (void)Context;
1794 /* alcGetString
1796 * Returns information about the Device, and error strings
1798 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1800 const ALCchar *value = NULL;
1802 switch(param)
1804 case ALC_NO_ERROR:
1805 value = alcNoError;
1806 break;
1808 case ALC_INVALID_ENUM:
1809 value = alcErrInvalidEnum;
1810 break;
1812 case ALC_INVALID_VALUE:
1813 value = alcErrInvalidValue;
1814 break;
1816 case ALC_INVALID_DEVICE:
1817 value = alcErrInvalidDevice;
1818 break;
1820 case ALC_INVALID_CONTEXT:
1821 value = alcErrInvalidContext;
1822 break;
1824 case ALC_OUT_OF_MEMORY:
1825 value = alcErrOutOfMemory;
1826 break;
1828 case ALC_DEVICE_SPECIFIER:
1829 if(VerifyDevice(pDevice))
1831 value = pDevice->szDeviceName;
1832 ALCdevice_DecRef(pDevice);
1834 else
1836 ProbeDeviceList();
1837 value = alcDeviceList;
1839 break;
1841 case ALC_ALL_DEVICES_SPECIFIER:
1842 ProbeAllDeviceList();
1843 value = alcAllDeviceList;
1844 break;
1846 case ALC_CAPTURE_DEVICE_SPECIFIER:
1847 if(VerifyDevice(pDevice))
1849 value = pDevice->szDeviceName;
1850 ALCdevice_DecRef(pDevice);
1852 else
1854 ProbeCaptureDeviceList();
1855 value = alcCaptureDeviceList;
1857 break;
1859 /* Default devices are always first in the list */
1860 case ALC_DEFAULT_DEVICE_SPECIFIER:
1861 if(!alcDeviceList)
1862 ProbeDeviceList();
1864 pDevice = VerifyDevice(pDevice);
1866 free(alcDefaultDeviceSpecifier);
1867 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1868 if(!alcDefaultDeviceSpecifier)
1869 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1871 value = alcDefaultDeviceSpecifier;
1872 if(pDevice) ALCdevice_DecRef(pDevice);
1873 break;
1875 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1876 if(!alcAllDeviceList)
1877 ProbeAllDeviceList();
1879 pDevice = VerifyDevice(pDevice);
1881 free(alcDefaultAllDeviceSpecifier);
1882 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1883 alcAllDeviceList : "");
1884 if(!alcDefaultAllDeviceSpecifier)
1885 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1887 value = alcDefaultAllDeviceSpecifier;
1888 if(pDevice) ALCdevice_DecRef(pDevice);
1889 break;
1891 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1892 if(!alcCaptureDeviceList)
1893 ProbeCaptureDeviceList();
1895 pDevice = VerifyDevice(pDevice);
1897 free(alcCaptureDefaultDeviceSpecifier);
1898 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1899 alcCaptureDeviceList : "");
1900 if(!alcCaptureDefaultDeviceSpecifier)
1901 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1903 value = alcCaptureDefaultDeviceSpecifier;
1904 if(pDevice) ALCdevice_DecRef(pDevice);
1905 break;
1907 case ALC_EXTENSIONS:
1908 if(!VerifyDevice(pDevice))
1909 value = alcNoDeviceExtList;
1910 else
1912 value = alcExtensionList;
1913 ALCdevice_DecRef(pDevice);
1915 break;
1917 default:
1918 pDevice = VerifyDevice(pDevice);
1919 alcSetError(pDevice, ALC_INVALID_ENUM);
1920 if(pDevice) ALCdevice_DecRef(pDevice);
1921 break;
1924 return value;
1928 /* alcGetIntegerv
1930 * Returns information about the Device and the version of Open AL
1932 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1934 device = VerifyDevice(device);
1936 if(size == 0 || data == NULL)
1938 alcSetError(device, ALC_INVALID_VALUE);
1939 if(device) ALCdevice_DecRef(device);
1940 return;
1943 if(!device)
1945 switch(param)
1947 case ALC_MAJOR_VERSION:
1948 *data = alcMajorVersion;
1949 break;
1950 case ALC_MINOR_VERSION:
1951 *data = alcMinorVersion;
1952 break;
1954 case ALC_ATTRIBUTES_SIZE:
1955 case ALC_ALL_ATTRIBUTES:
1956 case ALC_FREQUENCY:
1957 case ALC_REFRESH:
1958 case ALC_SYNC:
1959 case ALC_MONO_SOURCES:
1960 case ALC_STEREO_SOURCES:
1961 case ALC_CAPTURE_SAMPLES:
1962 case ALC_FORMAT_CHANNELS_SOFT:
1963 case ALC_FORMAT_TYPE_SOFT:
1964 alcSetError(NULL, ALC_INVALID_DEVICE);
1965 break;
1967 default:
1968 alcSetError(NULL, ALC_INVALID_ENUM);
1969 break;
1972 else if(device->IsCaptureDevice)
1974 switch(param)
1976 case ALC_CAPTURE_SAMPLES:
1977 LockDevice(device);
1978 *data = ALCdevice_AvailableSamples(device);
1979 UnlockDevice(device);
1980 break;
1982 case ALC_CONNECTED:
1983 *data = device->Connected;
1984 break;
1986 default:
1987 alcSetError(device, ALC_INVALID_ENUM);
1988 break;
1991 else /* render device */
1993 switch(param)
1995 case ALC_MAJOR_VERSION:
1996 *data = alcMajorVersion;
1997 break;
1999 case ALC_MINOR_VERSION:
2000 *data = alcMinorVersion;
2001 break;
2003 case ALC_EFX_MAJOR_VERSION:
2004 *data = alcEFXMajorVersion;
2005 break;
2007 case ALC_EFX_MINOR_VERSION:
2008 *data = alcEFXMinorVersion;
2009 break;
2011 case ALC_ATTRIBUTES_SIZE:
2012 *data = 13;
2013 break;
2015 case ALC_ALL_ATTRIBUTES:
2016 if(size < 13)
2017 alcSetError(device, ALC_INVALID_VALUE);
2018 else
2020 int i = 0;
2022 data[i++] = ALC_FREQUENCY;
2023 data[i++] = device->Frequency;
2025 if(!device->IsLoopbackDevice)
2027 data[i++] = ALC_REFRESH;
2028 data[i++] = device->Frequency / device->UpdateSize;
2030 data[i++] = ALC_SYNC;
2031 data[i++] = ALC_FALSE;
2033 else
2035 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2036 data[i++] = device->FmtChans;
2038 data[i++] = ALC_FORMAT_TYPE_SOFT;
2039 data[i++] = device->FmtType;
2042 data[i++] = ALC_MONO_SOURCES;
2043 data[i++] = device->NumMonoSources;
2045 data[i++] = ALC_STEREO_SOURCES;
2046 data[i++] = device->NumStereoSources;
2048 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2049 data[i++] = device->NumAuxSends;
2051 data[i++] = 0;
2053 break;
2055 case ALC_FREQUENCY:
2056 *data = device->Frequency;
2057 break;
2059 case ALC_REFRESH:
2060 if(device->IsLoopbackDevice)
2061 alcSetError(device, ALC_INVALID_DEVICE);
2062 else
2063 *data = device->Frequency / device->UpdateSize;
2064 break;
2066 case ALC_SYNC:
2067 if(device->IsLoopbackDevice)
2068 alcSetError(device, ALC_INVALID_DEVICE);
2069 else
2070 *data = ALC_FALSE;
2071 break;
2073 case ALC_FORMAT_CHANNELS_SOFT:
2074 if(!device->IsLoopbackDevice)
2075 alcSetError(device, ALC_INVALID_DEVICE);
2076 else
2077 *data = device->FmtChans;
2078 break;
2080 case ALC_FORMAT_TYPE_SOFT:
2081 if(!device->IsLoopbackDevice)
2082 alcSetError(device, ALC_INVALID_DEVICE);
2083 else
2084 *data = device->FmtType;
2085 break;
2087 case ALC_MONO_SOURCES:
2088 *data = device->NumMonoSources;
2089 break;
2091 case ALC_STEREO_SOURCES:
2092 *data = device->NumStereoSources;
2093 break;
2095 case ALC_MAX_AUXILIARY_SENDS:
2096 *data = device->NumAuxSends;
2097 break;
2099 case ALC_CONNECTED:
2100 *data = device->Connected;
2101 break;
2103 default:
2104 alcSetError(device, ALC_INVALID_ENUM);
2105 break;
2108 if(device)
2109 ALCdevice_DecRef(device);
2113 /* alcIsExtensionPresent
2115 * Determines if there is support for a particular extension
2117 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2119 ALCboolean bResult = ALC_FALSE;
2121 device = VerifyDevice(device);
2123 if(!extName)
2124 alcSetError(device, ALC_INVALID_VALUE);
2125 else
2127 size_t len = strlen(extName);
2128 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2129 while(ptr && *ptr)
2131 if(strncasecmp(ptr, extName, len) == 0 &&
2132 (ptr[len] == '\0' || isspace(ptr[len])))
2134 bResult = ALC_TRUE;
2135 break;
2137 if((ptr=strchr(ptr, ' ')) != NULL)
2139 do {
2140 ++ptr;
2141 } while(isspace(*ptr));
2145 if(device)
2146 ALCdevice_DecRef(device);
2147 return bResult;
2151 /* alcGetProcAddress
2153 * Retrieves the function address for a particular extension function
2155 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2157 ALCvoid *ptr = NULL;
2159 device = VerifyDevice(device);
2161 if(!funcName)
2162 alcSetError(device, ALC_INVALID_VALUE);
2163 else
2165 ALsizei i = 0;
2166 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2167 i++;
2168 ptr = alcFunctions[i].address;
2170 if(device)
2171 ALCdevice_DecRef(device);
2172 return ptr;
2176 /* alcGetEnumValue
2178 * Get the value for a particular ALC Enumerated Value
2180 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2182 ALCenum val = 0;
2184 device = VerifyDevice(device);
2186 if(!enumName)
2187 alcSetError(device, ALC_INVALID_VALUE);
2188 else
2190 ALsizei i = 0;
2191 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2192 i++;
2193 val = enumeration[i].value;
2195 if(device)
2196 ALCdevice_DecRef(device);
2197 return val;
2201 /* alcCreateContext
2203 * Create and attach a Context to a particular Device.
2205 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2207 ALCcontext *ALContext;
2208 ALCenum err;
2210 LockLists();
2211 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2213 UnlockLists();
2214 alcSetError(device, ALC_INVALID_DEVICE);
2215 if(device) ALCdevice_DecRef(device);
2216 return NULL;
2219 /* Reset Context Last Error code */
2220 device->LastError = ALC_NO_ERROR;
2222 if((err=UpdateDeviceParams(device, attrList)) != ALC_NO_ERROR)
2224 UnlockLists();
2225 alcSetError(device, err);
2226 if(err == ALC_INVALID_DEVICE)
2227 aluHandleDisconnect(device);
2228 ALCdevice_DecRef(device);
2229 return NULL;
2232 ALContext = calloc(1, sizeof(ALCcontext));
2233 if(ALContext)
2235 ALContext->ref = 1;
2237 ALContext->MaxActiveSources = 256;
2238 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2239 ALContext->MaxActiveSources);
2241 if(!ALContext || !ALContext->ActiveSources)
2243 if(!device->ContextList)
2245 ALCdevice_StopPlayback(device);
2246 device->Flags &= ~DEVICE_RUNNING;
2248 UnlockLists();
2250 free(ALContext);
2251 ALContext = NULL;
2253 alcSetError(device, ALC_OUT_OF_MEMORY);
2254 ALCdevice_DecRef(device);
2255 return NULL;
2258 ALContext->Device = device;
2259 ALCdevice_IncRef(device);
2260 InitContext(ALContext);
2262 do {
2263 ALContext->next = device->ContextList;
2264 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2265 UnlockLists();
2267 if(device->DefaultSlot)
2268 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2269 ALContext->LastError = AL_NO_ERROR;
2271 ALCdevice_DecRef(device);
2273 TRACE("Created context %p\n", ALContext);
2274 return ALContext;
2277 /* alcDestroyContext
2279 * Remove a Context
2281 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2283 ALCdevice *Device;
2285 LockLists();
2286 /* alcGetContextsDevice sets an error for invalid contexts */
2287 Device = alcGetContextsDevice(context);
2288 if(Device)
2290 ReleaseContext(context, Device);
2291 if(!Device->ContextList)
2293 ALCdevice_StopPlayback(Device);
2294 Device->Flags &= ~DEVICE_RUNNING;
2297 UnlockLists();
2301 /* alcGetCurrentContext
2303 * Returns the currently active Context
2305 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2307 ALCcontext *Context;
2309 Context = pthread_getspecific(LocalContext);
2310 if(!Context) Context = GlobalContext;
2312 return Context;
2315 /* alcGetThreadContext
2317 * Returns the currently active thread-local Context
2319 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2321 ALCcontext *Context;
2322 Context = pthread_getspecific(LocalContext);
2323 return Context;
2327 /* alcMakeContextCurrent
2329 * Makes the given Context the active Context
2331 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2333 /* context must be a valid Context or NULL */
2334 if(context && !(context=VerifyContext(context)))
2336 alcSetError(NULL, ALC_INVALID_CONTEXT);
2337 return ALC_FALSE;
2339 /* context's reference count is already incremented */
2340 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2341 if(context) ALCcontext_DecRef(context);
2343 if((context=pthread_getspecific(LocalContext)) != NULL)
2345 pthread_setspecific(LocalContext, NULL);
2346 ALCcontext_DecRef(context);
2349 return ALC_TRUE;
2352 /* alcSetThreadContext
2354 * Makes the given Context the active Context for the current thread
2356 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2358 ALCcontext *old;
2360 /* context must be a valid Context or NULL */
2361 if(context && !(context=VerifyContext(context)))
2363 alcSetError(NULL, ALC_INVALID_CONTEXT);
2364 return ALC_FALSE;
2366 /* context's reference count is already incremented */
2367 old = pthread_getspecific(LocalContext);
2368 pthread_setspecific(LocalContext, context);
2369 if(old) ALCcontext_DecRef(old);
2371 return ALC_TRUE;
2375 /* alcGetContextsDevice
2377 * Returns the Device that a particular Context is attached to
2379 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2381 ALCdevice *Device;
2383 if(!(Context=VerifyContext(Context)))
2385 alcSetError(NULL, ALC_INVALID_CONTEXT);
2386 return NULL;
2388 Device = Context->Device;
2389 ALCcontext_DecRef(Context);
2391 return Device;
2395 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2397 static const struct {
2398 const char name[32];
2399 enum DevFmtChannels channels;
2400 enum DevFmtType type;
2401 } formats[] = {
2402 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2403 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2404 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2405 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2406 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2407 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2409 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2410 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2411 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2412 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2413 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2414 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2416 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2417 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2418 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2419 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2420 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2421 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2423 size_t i;
2425 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2427 if(strcasecmp(str, formats[i].name) == 0)
2429 *chans = formats[i].channels;
2430 *type = formats[i].type;
2431 return;
2435 ERR("Unknown format: \"%s\"\n", str);
2436 *chans = DevFmtStereo;
2437 *type = DevFmtShort;
2440 /* alcOpenDevice
2442 * Open the Device specified.
2444 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2446 const ALCchar *fmt;
2447 ALCdevice *device;
2448 ALCenum err;
2450 DO_INITCONFIG();
2452 if(!PlaybackBackend.name)
2454 alcSetError(NULL, ALC_INVALID_VALUE);
2455 return NULL;
2458 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2459 deviceName = NULL;
2461 device = calloc(1, sizeof(ALCdevice)+sizeof(ALeffectslot));
2462 if(!device)
2464 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2465 return NULL;
2468 //Validate device
2469 device->Funcs = &PlaybackBackend.Funcs;
2470 device->ref = 1;
2471 device->Connected = ALC_TRUE;
2472 device->IsCaptureDevice = AL_FALSE;
2473 device->IsLoopbackDevice = AL_FALSE;
2474 InitializeCriticalSection(&device->Mutex);
2475 device->LastError = ALC_NO_ERROR;
2477 device->Flags = 0;
2478 device->Bs2b = NULL;
2479 device->Bs2bLevel = 0;
2480 device->szDeviceName = NULL;
2482 device->ContextList = NULL;
2484 device->MaxNoOfSources = 256;
2485 device->AuxiliaryEffectSlotMax = 4;
2486 device->NumAuxSends = MAX_SENDS;
2488 InitUIntMap(&device->BufferMap, ~0);
2489 InitUIntMap(&device->EffectMap, ~0);
2490 InitUIntMap(&device->FilterMap, ~0);
2492 //Set output format
2493 device->NumUpdates = 4;
2494 device->UpdateSize = 1024;
2496 device->Frequency = DEFAULT_OUTPUT_RATE;
2497 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2498 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2499 device->Frequency = maxu(device->Frequency, 8000);
2501 fmt = "AL_FORMAT_STEREO32";
2502 if(ConfigValueStr(NULL, "format", &fmt))
2503 device->Flags |= DEVICE_CHANNELS_REQUEST;
2504 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2506 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2507 if(device->NumUpdates < 2) device->NumUpdates = 4;
2509 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2510 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2512 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2513 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2515 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2516 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2518 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2519 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2521 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2523 device->NumStereoSources = 1;
2524 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2526 device->DefaultSlot = (ALeffectslot*)(device+1);
2527 if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR)
2528 device->DefaultSlot = NULL;
2530 // Find a playback device to open
2531 LockLists();
2532 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2534 UnlockLists();
2535 DeleteCriticalSection(&device->Mutex);
2536 free(device);
2537 alcSetError(NULL, err);
2538 return NULL;
2540 UnlockLists();
2542 do {
2543 device->next = DeviceList;
2544 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2546 TRACE("Created device %p\n", device);
2547 return device;
2550 /* alcCloseDevice
2552 * Close the specified Device
2554 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2556 ALCdevice *volatile*list;
2557 ALCcontext *ctx;
2559 LockLists();
2560 list = &DeviceList;
2561 while(*list && *list != pDevice)
2562 list = &(*list)->next;
2564 if(!*list || (*list)->IsCaptureDevice)
2566 alcSetError(*list, ALC_INVALID_DEVICE);
2567 UnlockLists();
2568 return ALC_FALSE;
2571 *list = (*list)->next;
2572 UnlockLists();
2574 if((ctx=pDevice->ContextList) != NULL)
2576 do {
2577 WARN("Releasing context %p\n", ctx);
2578 ReleaseContext(ctx, pDevice);
2579 } while((ctx=pDevice->ContextList) != NULL);
2580 ALCdevice_StopPlayback(pDevice);
2581 pDevice->Flags &= ~DEVICE_RUNNING;
2583 ALCdevice_ClosePlayback(pDevice);
2585 ALCdevice_DecRef(pDevice);
2587 return ALC_TRUE;
2591 /* alcLoopbackOpenDeviceSOFT
2593 * Open a loopback device, for manual rendering.
2595 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2597 ALCdevice *device;
2599 DO_INITCONFIG();
2601 device = calloc(1, sizeof(ALCdevice));
2602 if(!device)
2604 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2605 return NULL;
2608 //Validate device
2609 device->Funcs = &BackendLoopback.Funcs;
2610 device->ref = 1;
2611 device->Connected = ALC_TRUE;
2612 device->IsCaptureDevice = AL_FALSE;
2613 device->IsLoopbackDevice = AL_TRUE;
2614 InitializeCriticalSection(&device->Mutex);
2615 device->LastError = ALC_NO_ERROR;
2617 device->Flags = 0;
2618 device->Bs2b = NULL;
2619 device->Bs2bLevel = 0;
2620 device->szDeviceName = NULL;
2622 device->ContextList = NULL;
2624 device->MaxNoOfSources = 256;
2625 device->AuxiliaryEffectSlotMax = 4;
2626 device->NumAuxSends = MAX_SENDS;
2628 InitUIntMap(&device->BufferMap, ~0);
2629 InitUIntMap(&device->EffectMap, ~0);
2630 InitUIntMap(&device->FilterMap, ~0);
2632 //Set output format
2633 device->NumUpdates = 0;
2634 device->UpdateSize = 0;
2636 device->Frequency = 44100;
2637 device->FmtChans = DevFmtStereo;
2638 device->FmtType = DevFmtShort;
2640 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2641 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2643 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2644 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2646 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2647 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2649 device->NumStereoSources = 1;
2650 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2652 // Open the "backend"
2653 ALCdevice_OpenPlayback(device, "Loopback");
2654 do {
2655 device->next = DeviceList;
2656 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2658 TRACE("Created device %p\n", device);
2659 return device;
2662 /* alcIsRenderFormatSupportedSOFT
2664 * Determines if the loopback device supports the given format for rendering.
2666 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2668 ALCboolean ret = ALC_FALSE;
2670 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2671 alcSetError(device, ALC_INVALID_DEVICE);
2672 else if(freq <= 0)
2673 alcSetError(device, ALC_INVALID_VALUE);
2674 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2675 alcSetError(device, ALC_INVALID_ENUM);
2676 else
2678 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2679 freq >= 8000)
2680 ret = ALC_TRUE;
2682 if(device) ALCdevice_DecRef(device);
2684 return ret;
2687 /* alcRenderSamplesSOFT
2689 * Renders some samples into a buffer, using the format last set by the
2690 * attributes given to alcCreateContext.
2692 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2694 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2695 alcSetError(device, ALC_INVALID_DEVICE);
2696 else if(samples < 0 || (samples > 0 && buffer == NULL))
2697 alcSetError(device, ALC_INVALID_VALUE);
2698 else
2699 aluMixData(device, buffer, samples);
2700 if(device) ALCdevice_DecRef(device);
2704 static void ReleaseALC(void)
2706 ALCdevice *dev;
2708 free(alcDeviceList); alcDeviceList = NULL;
2709 alcDeviceListSize = 0;
2710 free(alcAllDeviceList); alcAllDeviceList = NULL;
2711 alcAllDeviceListSize = 0;
2712 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2713 alcCaptureDeviceListSize = 0;
2715 free(alcDefaultDeviceSpecifier);
2716 alcDefaultDeviceSpecifier = NULL;
2717 free(alcDefaultAllDeviceSpecifier);
2718 alcDefaultAllDeviceSpecifier = NULL;
2719 free(alcCaptureDefaultDeviceSpecifier);
2720 alcCaptureDefaultDeviceSpecifier = NULL;
2722 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2724 ALCuint num = 0;
2725 do {
2726 num++;
2727 } while((dev=dev->next) != NULL);
2728 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2732 ///////////////////////////////////////////////////////