Not all devices will have a default effect slot
[openal-soft.git] / Alc / ALc.c
blob6ce5efaf769a2d643a4f3af383c334df27732dd3
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <math.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <memory.h>
27 #include <ctype.h>
28 #include <signal.h>
30 #include "alMain.h"
31 #include "alSource.h"
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "alThunk.h"
35 #include "alSource.h"
36 #include "alBuffer.h"
37 #include "alAuxEffectSlot.h"
38 #include "alError.h"
39 #include "bs2b.h"
40 #include "alu.h"
43 #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
44 static struct BackendInfo BackendList[] = {
45 #ifdef HAVE_PULSEAUDIO
46 { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs },
47 #endif
48 #ifdef HAVE_ALSA
49 { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs },
50 #endif
51 #ifdef HAVE_COREAUDIO
52 { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs },
53 #endif
54 #ifdef HAVE_OSS
55 { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs },
56 #endif
57 #ifdef HAVE_SOLARIS
58 { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs },
59 #endif
60 #ifdef HAVE_SNDIO
61 { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs },
62 #endif
63 #ifdef HAVE_MMDEVAPI
64 { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs },
65 #endif
66 #ifdef HAVE_DSOUND
67 { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs },
68 #endif
69 #ifdef HAVE_WINMM
70 { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs },
71 #endif
72 #ifdef HAVE_PORTAUDIO
73 { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs },
74 #endif
75 #ifdef HAVE_OPENSL
76 { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs },
77 #endif
79 { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs },
80 #ifdef HAVE_WAVE
81 { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs },
82 #endif
84 { NULL, NULL, NULL, NULL, EmptyFuncs }
86 static struct BackendInfo BackendLoopback = {
87 "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs
89 #undef EmptyFuncs
91 static struct BackendInfo PlaybackBackend;
92 static struct BackendInfo CaptureBackend;
94 ///////////////////////////////////////////////////////
95 // STRING and EXTENSIONS
97 typedef struct ALCfunction {
98 const ALCchar *funcName;
99 ALCvoid *address;
100 } ALCfunction;
102 typedef struct ALCenums {
103 const ALCchar *enumName;
104 ALCenum value;
105 } ALCenums;
108 static const ALCfunction alcFunctions[] = {
109 { "alcCreateContext", (ALCvoid *) alcCreateContext },
110 { "alcMakeContextCurrent", (ALCvoid *) alcMakeContextCurrent },
111 { "alcProcessContext", (ALCvoid *) alcProcessContext },
112 { "alcSuspendContext", (ALCvoid *) alcSuspendContext },
113 { "alcDestroyContext", (ALCvoid *) alcDestroyContext },
114 { "alcGetCurrentContext", (ALCvoid *) alcGetCurrentContext },
115 { "alcGetContextsDevice", (ALCvoid *) alcGetContextsDevice },
116 { "alcOpenDevice", (ALCvoid *) alcOpenDevice },
117 { "alcCloseDevice", (ALCvoid *) alcCloseDevice },
118 { "alcGetError", (ALCvoid *) alcGetError },
119 { "alcIsExtensionPresent", (ALCvoid *) alcIsExtensionPresent },
120 { "alcGetProcAddress", (ALCvoid *) alcGetProcAddress },
121 { "alcGetEnumValue", (ALCvoid *) alcGetEnumValue },
122 { "alcGetString", (ALCvoid *) alcGetString },
123 { "alcGetIntegerv", (ALCvoid *) alcGetIntegerv },
124 { "alcCaptureOpenDevice", (ALCvoid *) alcCaptureOpenDevice },
125 { "alcCaptureCloseDevice", (ALCvoid *) alcCaptureCloseDevice },
126 { "alcCaptureStart", (ALCvoid *) alcCaptureStart },
127 { "alcCaptureStop", (ALCvoid *) alcCaptureStop },
128 { "alcCaptureSamples", (ALCvoid *) alcCaptureSamples },
130 { "alcSetThreadContext", (ALCvoid *) alcSetThreadContext },
131 { "alcGetThreadContext", (ALCvoid *) alcGetThreadContext },
133 { "alcLoopbackOpenDeviceSOFT", (ALCvoid *) alcLoopbackOpenDeviceSOFT},
134 { "alcIsRenderFormatSupportedSOFT",(ALCvoid *) alcIsRenderFormatSupportedSOFT},
135 { "alcRenderSamplesSOFT", (ALCvoid *) alcRenderSamplesSOFT },
137 { "alEnable", (ALCvoid *) alEnable },
138 { "alDisable", (ALCvoid *) alDisable },
139 { "alIsEnabled", (ALCvoid *) alIsEnabled },
140 { "alGetString", (ALCvoid *) alGetString },
141 { "alGetBooleanv", (ALCvoid *) alGetBooleanv },
142 { "alGetIntegerv", (ALCvoid *) alGetIntegerv },
143 { "alGetFloatv", (ALCvoid *) alGetFloatv },
144 { "alGetDoublev", (ALCvoid *) alGetDoublev },
145 { "alGetBoolean", (ALCvoid *) alGetBoolean },
146 { "alGetInteger", (ALCvoid *) alGetInteger },
147 { "alGetFloat", (ALCvoid *) alGetFloat },
148 { "alGetDouble", (ALCvoid *) alGetDouble },
149 { "alGetError", (ALCvoid *) alGetError },
150 { "alIsExtensionPresent", (ALCvoid *) alIsExtensionPresent },
151 { "alGetProcAddress", (ALCvoid *) alGetProcAddress },
152 { "alGetEnumValue", (ALCvoid *) alGetEnumValue },
153 { "alListenerf", (ALCvoid *) alListenerf },
154 { "alListener3f", (ALCvoid *) alListener3f },
155 { "alListenerfv", (ALCvoid *) alListenerfv },
156 { "alListeneri", (ALCvoid *) alListeneri },
157 { "alListener3i", (ALCvoid *) alListener3i },
158 { "alListeneriv", (ALCvoid *) alListeneriv },
159 { "alGetListenerf", (ALCvoid *) alGetListenerf },
160 { "alGetListener3f", (ALCvoid *) alGetListener3f },
161 { "alGetListenerfv", (ALCvoid *) alGetListenerfv },
162 { "alGetListeneri", (ALCvoid *) alGetListeneri },
163 { "alGetListener3i", (ALCvoid *) alGetListener3i },
164 { "alGetListeneriv", (ALCvoid *) alGetListeneriv },
165 { "alGenSources", (ALCvoid *) alGenSources },
166 { "alDeleteSources", (ALCvoid *) alDeleteSources },
167 { "alIsSource", (ALCvoid *) alIsSource },
168 { "alSourcef", (ALCvoid *) alSourcef },
169 { "alSource3f", (ALCvoid *) alSource3f },
170 { "alSourcefv", (ALCvoid *) alSourcefv },
171 { "alSourcei", (ALCvoid *) alSourcei },
172 { "alSource3i", (ALCvoid *) alSource3i },
173 { "alSourceiv", (ALCvoid *) alSourceiv },
174 { "alGetSourcef", (ALCvoid *) alGetSourcef },
175 { "alGetSource3f", (ALCvoid *) alGetSource3f },
176 { "alGetSourcefv", (ALCvoid *) alGetSourcefv },
177 { "alGetSourcei", (ALCvoid *) alGetSourcei },
178 { "alGetSource3i", (ALCvoid *) alGetSource3i },
179 { "alGetSourceiv", (ALCvoid *) alGetSourceiv },
180 { "alSourcePlayv", (ALCvoid *) alSourcePlayv },
181 { "alSourceStopv", (ALCvoid *) alSourceStopv },
182 { "alSourceRewindv", (ALCvoid *) alSourceRewindv },
183 { "alSourcePausev", (ALCvoid *) alSourcePausev },
184 { "alSourcePlay", (ALCvoid *) alSourcePlay },
185 { "alSourceStop", (ALCvoid *) alSourceStop },
186 { "alSourceRewind", (ALCvoid *) alSourceRewind },
187 { "alSourcePause", (ALCvoid *) alSourcePause },
188 { "alSourceQueueBuffers", (ALCvoid *) alSourceQueueBuffers },
189 { "alSourceUnqueueBuffers", (ALCvoid *) alSourceUnqueueBuffers },
190 { "alGenBuffers", (ALCvoid *) alGenBuffers },
191 { "alDeleteBuffers", (ALCvoid *) alDeleteBuffers },
192 { "alIsBuffer", (ALCvoid *) alIsBuffer },
193 { "alBufferData", (ALCvoid *) alBufferData },
194 { "alBufferf", (ALCvoid *) alBufferf },
195 { "alBuffer3f", (ALCvoid *) alBuffer3f },
196 { "alBufferfv", (ALCvoid *) alBufferfv },
197 { "alBufferi", (ALCvoid *) alBufferi },
198 { "alBuffer3i", (ALCvoid *) alBuffer3i },
199 { "alBufferiv", (ALCvoid *) alBufferiv },
200 { "alGetBufferf", (ALCvoid *) alGetBufferf },
201 { "alGetBuffer3f", (ALCvoid *) alGetBuffer3f },
202 { "alGetBufferfv", (ALCvoid *) alGetBufferfv },
203 { "alGetBufferi", (ALCvoid *) alGetBufferi },
204 { "alGetBuffer3i", (ALCvoid *) alGetBuffer3i },
205 { "alGetBufferiv", (ALCvoid *) alGetBufferiv },
206 { "alDopplerFactor", (ALCvoid *) alDopplerFactor },
207 { "alDopplerVelocity", (ALCvoid *) alDopplerVelocity },
208 { "alSpeedOfSound", (ALCvoid *) alSpeedOfSound },
209 { "alDistanceModel", (ALCvoid *) alDistanceModel },
211 { "alGenFilters", (ALCvoid *) alGenFilters },
212 { "alDeleteFilters", (ALCvoid *) alDeleteFilters },
213 { "alIsFilter", (ALCvoid *) alIsFilter },
214 { "alFilteri", (ALCvoid *) alFilteri },
215 { "alFilteriv", (ALCvoid *) alFilteriv },
216 { "alFilterf", (ALCvoid *) alFilterf },
217 { "alFilterfv", (ALCvoid *) alFilterfv },
218 { "alGetFilteri", (ALCvoid *) alGetFilteri },
219 { "alGetFilteriv", (ALCvoid *) alGetFilteriv },
220 { "alGetFilterf", (ALCvoid *) alGetFilterf },
221 { "alGetFilterfv", (ALCvoid *) alGetFilterfv },
222 { "alGenEffects", (ALCvoid *) alGenEffects },
223 { "alDeleteEffects", (ALCvoid *) alDeleteEffects },
224 { "alIsEffect", (ALCvoid *) alIsEffect },
225 { "alEffecti", (ALCvoid *) alEffecti },
226 { "alEffectiv", (ALCvoid *) alEffectiv },
227 { "alEffectf", (ALCvoid *) alEffectf },
228 { "alEffectfv", (ALCvoid *) alEffectfv },
229 { "alGetEffecti", (ALCvoid *) alGetEffecti },
230 { "alGetEffectiv", (ALCvoid *) alGetEffectiv },
231 { "alGetEffectf", (ALCvoid *) alGetEffectf },
232 { "alGetEffectfv", (ALCvoid *) alGetEffectfv },
233 { "alGenAuxiliaryEffectSlots", (ALCvoid *) alGenAuxiliaryEffectSlots},
234 { "alDeleteAuxiliaryEffectSlots",(ALCvoid *) alDeleteAuxiliaryEffectSlots},
235 { "alIsAuxiliaryEffectSlot", (ALCvoid *) alIsAuxiliaryEffectSlot },
236 { "alAuxiliaryEffectSloti", (ALCvoid *) alAuxiliaryEffectSloti },
237 { "alAuxiliaryEffectSlotiv", (ALCvoid *) alAuxiliaryEffectSlotiv },
238 { "alAuxiliaryEffectSlotf", (ALCvoid *) alAuxiliaryEffectSlotf },
239 { "alAuxiliaryEffectSlotfv", (ALCvoid *) alAuxiliaryEffectSlotfv },
240 { "alGetAuxiliaryEffectSloti", (ALCvoid *) alGetAuxiliaryEffectSloti},
241 { "alGetAuxiliaryEffectSlotiv", (ALCvoid *) alGetAuxiliaryEffectSlotiv},
242 { "alGetAuxiliaryEffectSlotf", (ALCvoid *) alGetAuxiliaryEffectSlotf},
243 { "alGetAuxiliaryEffectSlotfv", (ALCvoid *) alGetAuxiliaryEffectSlotfv},
245 { "alBufferSubDataSOFT", (ALCvoid *) alBufferSubDataSOFT },
247 { "alBufferSamplesSOFT", (ALCvoid *) alBufferSamplesSOFT },
248 { "alBufferSubSamplesSOFT", (ALCvoid *) alBufferSubSamplesSOFT },
249 { "alGetBufferSamplesSOFT", (ALCvoid *) alGetBufferSamplesSOFT },
250 { "alIsBufferFormatSupportedSOFT",(ALCvoid *) alIsBufferFormatSupportedSOFT},
252 { "alDeferUpdatesSOFT", (ALCvoid *) alDeferUpdatesSOFT },
253 { "alProcessUpdatesSOFT", (ALCvoid *) alProcessUpdatesSOFT },
255 { NULL, (ALCvoid *) NULL }
258 static const ALCenums enumeration[] = {
259 // Types
260 { "ALC_INVALID", ALC_INVALID },
261 { "ALC_FALSE", ALC_FALSE },
262 { "ALC_TRUE", ALC_TRUE },
264 // ALC Properties
265 { "ALC_MAJOR_VERSION", ALC_MAJOR_VERSION },
266 { "ALC_MINOR_VERSION", ALC_MINOR_VERSION },
267 { "ALC_ATTRIBUTES_SIZE", ALC_ATTRIBUTES_SIZE },
268 { "ALC_ALL_ATTRIBUTES", ALC_ALL_ATTRIBUTES },
269 { "ALC_DEFAULT_DEVICE_SPECIFIER", ALC_DEFAULT_DEVICE_SPECIFIER },
270 { "ALC_DEVICE_SPECIFIER", ALC_DEVICE_SPECIFIER },
271 { "ALC_ALL_DEVICES_SPECIFIER", ALC_ALL_DEVICES_SPECIFIER },
272 { "ALC_DEFAULT_ALL_DEVICES_SPECIFIER", ALC_DEFAULT_ALL_DEVICES_SPECIFIER },
273 { "ALC_EXTENSIONS", ALC_EXTENSIONS },
274 { "ALC_FREQUENCY", ALC_FREQUENCY },
275 { "ALC_REFRESH", ALC_REFRESH },
276 { "ALC_SYNC", ALC_SYNC },
277 { "ALC_MONO_SOURCES", ALC_MONO_SOURCES },
278 { "ALC_STEREO_SOURCES", ALC_STEREO_SOURCES },
279 { "ALC_CAPTURE_DEVICE_SPECIFIER", ALC_CAPTURE_DEVICE_SPECIFIER },
280 { "ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER", ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER},
281 { "ALC_CAPTURE_SAMPLES", ALC_CAPTURE_SAMPLES },
282 { "ALC_CONNECTED", ALC_CONNECTED },
284 // EFX Properties
285 { "ALC_EFX_MAJOR_VERSION", ALC_EFX_MAJOR_VERSION },
286 { "ALC_EFX_MINOR_VERSION", ALC_EFX_MINOR_VERSION },
287 { "ALC_MAX_AUXILIARY_SENDS", ALC_MAX_AUXILIARY_SENDS },
289 // Loopback device Properties
290 { "ALC_FORMAT_CHANNELS_SOFT", ALC_FORMAT_CHANNELS_SOFT },
291 { "ALC_FORMAT_TYPE_SOFT", ALC_FORMAT_TYPE_SOFT },
293 // Buffer Channel Configurations
294 { "ALC_MONO_SOFT", ALC_MONO_SOFT },
295 { "ALC_STEREO_SOFT", ALC_STEREO_SOFT },
296 { "ALC_QUAD_SOFT", ALC_QUAD_SOFT },
297 { "ALC_5POINT1_SOFT", ALC_5POINT1_SOFT },
298 { "ALC_6POINT1_SOFT", ALC_6POINT1_SOFT },
299 { "ALC_7POINT1_SOFT", ALC_7POINT1_SOFT },
301 // Buffer Sample Types
302 { "ALC_BYTE_SOFT", ALC_BYTE_SOFT },
303 { "ALC_UNSIGNED_BYTE_SOFT", ALC_UNSIGNED_BYTE_SOFT },
304 { "ALC_SHORT_SOFT", ALC_SHORT_SOFT },
305 { "ALC_UNSIGNED_SHORT_SOFT", ALC_UNSIGNED_SHORT_SOFT },
306 { "ALC_INT_SOFT", ALC_INT_SOFT },
307 { "ALC_UNSIGNED_INT_SOFT", ALC_UNSIGNED_INT_SOFT },
308 { "ALC_FLOAT_SOFT", ALC_FLOAT_SOFT },
310 // ALC Error Message
311 { "ALC_NO_ERROR", ALC_NO_ERROR },
312 { "ALC_INVALID_DEVICE", ALC_INVALID_DEVICE },
313 { "ALC_INVALID_CONTEXT", ALC_INVALID_CONTEXT },
314 { "ALC_INVALID_ENUM", ALC_INVALID_ENUM },
315 { "ALC_INVALID_VALUE", ALC_INVALID_VALUE },
316 { "ALC_OUT_OF_MEMORY", ALC_OUT_OF_MEMORY },
318 { NULL, (ALCenum)0 }
320 // Error strings
321 static const ALCchar alcNoError[] = "No Error";
322 static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
323 static const ALCchar alcErrInvalidContext[] = "Invalid Context";
324 static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
325 static const ALCchar alcErrInvalidValue[] = "Invalid Value";
326 static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
328 /* Device lists. Sizes only include the first ending null character, not the
329 * second */
330 static ALCchar *alcDeviceList;
331 static size_t alcDeviceListSize;
332 static ALCchar *alcAllDeviceList;
333 static size_t alcAllDeviceListSize;
334 static ALCchar *alcCaptureDeviceList;
335 static size_t alcCaptureDeviceListSize;
336 /* Default is always the first in the list */
337 static ALCchar *alcDefaultDeviceSpecifier;
338 static ALCchar *alcDefaultAllDeviceSpecifier;
339 static ALCchar *alcCaptureDefaultDeviceSpecifier;
342 static const ALCchar alcNoDeviceExtList[] =
343 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
344 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
345 static const ALCchar alcExtensionList[] =
346 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
347 "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
348 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
349 static const ALCint alcMajorVersion = 1;
350 static const ALCint alcMinorVersion = 1;
352 static const ALCint alcEFXMajorVersion = 1;
353 static const ALCint alcEFXMinorVersion = 0;
355 ///////////////////////////////////////////////////////
358 ///////////////////////////////////////////////////////
359 // Global Variables
361 static CRITICAL_SECTION ListLock;
363 /* Device List */
364 static ALCdevice *volatile DeviceList = NULL;
366 // Thread-local current context
367 static pthread_key_t LocalContext;
368 // Process-wide current context
369 static ALCcontext *GlobalContext;
371 /* Device Error */
372 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
374 // Default context extensions
375 static const ALchar alExtList[] =
376 "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 "
377 "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
378 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
379 "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data "
380 "AL_SOFTX_deferred_updates AL_SOFT_loop_points "
381 "AL_SOFTX_non_virtual_channels";
383 // Mixing Priority Level
384 ALint RTPrioLevel;
386 // Output Log File
387 FILE *LogFile;
389 // Output Log Level
390 #ifdef _DEBUG
391 enum LogLevel LogLevel = LogWarning;
392 #else
393 enum LogLevel LogLevel = LogError;
394 #endif
396 /* Flag to trap ALC device errors */
397 static ALCboolean TrapALCError = ALC_FALSE;
399 /* One-time configuration init control */
400 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
402 /* Forced effect that applies to sources that don't have an effect on send 0 */
403 static ALeffect ForcedEffect;
405 ///////////////////////////////////////////////////////
408 ///////////////////////////////////////////////////////
409 // ALC Related helper functions
410 static void ReleaseALC(void);
411 static void ReleaseThreadCtx(void *ptr);
413 static void alc_initconfig(void);
414 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
416 #if defined(_WIN32)
417 static void alc_init(void);
418 static void alc_deinit(void);
419 static void alc_deinit_safe(void);
421 UIntMap TlsDestructor;
423 #ifndef AL_LIBTYPE_STATIC
424 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
426 ALsizei i;
427 (void)hModule;
429 // Perform actions based on the reason for calling.
430 switch(ul_reason_for_call)
432 case DLL_PROCESS_ATTACH:
433 InitUIntMap(&TlsDestructor, ~0);
434 alc_init();
435 break;
437 case DLL_THREAD_DETACH:
438 LockUIntMapRead(&TlsDestructor);
439 for(i = 0;i < TlsDestructor.size;i++)
441 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
442 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
443 if(ptr && callback)
444 callback(ptr);
446 UnlockUIntMapRead(&TlsDestructor);
447 break;
449 case DLL_PROCESS_DETACH:
450 if(!lpReserved)
451 alc_deinit();
452 else
453 alc_deinit_safe();
454 ResetUIntMap(&TlsDestructor);
455 break;
457 return TRUE;
459 #elif defined(_MSC_VER)
460 #pragma section(".CRT$XCU",read)
461 static void alc_constructor(void);
462 static void alc_destructor(void);
463 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
465 static void alc_constructor(void)
467 atexit(alc_destructor);
468 alc_init();
471 static void alc_destructor(void)
473 alc_deinit();
475 #elif defined(HAVE_GCC_DESTRUCTOR)
476 static void alc_init(void) __attribute__((constructor));
477 static void alc_deinit(void) __attribute__((destructor));
478 #else
479 #error "No static initialization available on this platform!"
480 #endif
481 #elif defined(HAVE_GCC_DESTRUCTOR)
482 static void alc_init(void) __attribute__((constructor));
483 static void alc_deinit(void) __attribute__((destructor));
484 #else
485 #error "No global initialization available on this platform!"
486 #endif
488 static void alc_init(void)
490 const char *str;
492 LogFile = stderr;
494 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
495 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
496 ConeScale = 1.0f;
498 str = getenv("__ALSOFT_REVERSE_Z");
499 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
500 ZScale = -1.0f;
502 str = getenv("__ALSOFT_TRAP_ERROR");
503 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
505 TrapALError = AL_TRUE;
506 TrapALCError = AL_TRUE;
508 else
510 str = getenv("__ALSOFT_TRAP_AL_ERROR");
511 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
512 TrapALError = AL_TRUE;
514 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
515 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
516 TrapALCError = ALC_TRUE;
519 pthread_key_create(&LocalContext, ReleaseThreadCtx);
520 InitializeCriticalSection(&ListLock);
521 ThunkInit();
524 static void alc_deinit_safe(void)
526 ReleaseALC();
528 FreeHrtf();
529 FreeALConfig();
531 ThunkExit();
532 DeleteCriticalSection(&ListLock);
533 pthread_key_delete(LocalContext);
535 if(LogFile != stderr)
536 fclose(LogFile);
537 LogFile = NULL;
540 static void alc_deinit(void)
542 int i;
544 ReleaseALC();
546 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
547 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
549 for(i = 0;BackendList[i].Deinit;i++)
550 BackendList[i].Deinit();
551 BackendLoopback.Deinit();
553 alc_deinit_safe();
556 static void alc_initconfig(void)
558 const char *devs, *str;
559 float valf;
560 int i, n;
562 str = getenv("ALSOFT_LOGLEVEL");
563 if(str)
565 long lvl = strtol(str, NULL, 0);
566 if(lvl >= NoLog && lvl <= LogRef)
567 LogLevel = lvl;
570 str = getenv("ALSOFT_LOGFILE");
571 if(str && str[0])
573 FILE *logfile = fopen(str, "wat");
574 if(logfile) LogFile = logfile;
575 else ERR("Failed to open log file '%s'\n", str);
578 ReadALConfig();
580 InitHrtf();
582 #ifdef _WIN32
583 RTPrioLevel = 1;
584 #else
585 RTPrioLevel = 0;
586 #endif
587 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
589 if(ConfigValueStr(NULL, "resampler", &str))
591 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
592 DefaultResampler = POINT_RESAMPLER;
593 else if(strcasecmp(str, "linear") == 0)
594 DefaultResampler = LINEAR_RESAMPLER;
595 else if(strcasecmp(str, "cubic") == 0)
596 DefaultResampler = CUBIC_RESAMPLER;
597 else
599 char *end;
601 n = strtol(str, &end, 0);
602 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
603 DefaultResampler = n;
604 else
605 WARN("Invalid resampler: %s\n", str);
609 if(!TrapALCError)
610 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
612 if(!TrapALError)
613 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
615 if(ConfigValueFloat("reverb", "boost", &valf))
616 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
618 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
620 if(ConfigValueStr(NULL, "drivers", &devs))
622 int n;
623 size_t len;
624 const char *next = devs;
625 int endlist, delitem;
627 i = 0;
628 do {
629 devs = next;
630 next = strchr(devs, ',');
632 delitem = (devs[0] == '-');
633 if(devs[0] == '-') devs++;
635 if(!devs[0] || devs[0] == ',')
637 endlist = 0;
638 continue;
640 endlist = 1;
642 len = (next ? ((size_t)(next-devs)) : strlen(devs));
643 for(n = i;BackendList[n].Init;n++)
645 if(len == strlen(BackendList[n].name) &&
646 strncmp(BackendList[n].name, devs, len) == 0)
648 if(delitem)
650 do {
651 BackendList[n] = BackendList[n+1];
652 ++n;
653 } while(BackendList[n].Init);
655 else
657 struct BackendInfo Bkp = BackendList[n];
658 while(n > i)
660 BackendList[n] = BackendList[n-1];
661 --n;
663 BackendList[n] = Bkp;
665 i++;
667 break;
670 } while(next++);
672 if(endlist)
674 BackendList[i].name = NULL;
675 BackendList[i].Init = NULL;
676 BackendList[i].Deinit = NULL;
677 BackendList[i].Probe = NULL;
681 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
683 if(!BackendList[i].Init(&BackendList[i].Funcs))
685 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
686 continue;
689 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
690 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
692 PlaybackBackend = BackendList[i];
693 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
695 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
697 CaptureBackend = BackendList[i];
698 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
701 BackendLoopback.Init(&BackendLoopback.Funcs);
703 if(ConfigValueStr(NULL, "excludefx", &str))
705 size_t len;
706 const char *next = str;
708 do {
709 str = next;
710 next = strchr(str, ',');
712 if(!str[0] || next == str)
713 continue;
715 len = (next ? ((size_t)(next-str)) : strlen(str));
716 for(n = 0;EffectList[n].name;n++)
718 if(len == strlen(EffectList[n].name) &&
719 strncmp(EffectList[n].name, str, len) == 0)
720 DisabledEffects[EffectList[n].type] = AL_TRUE;
722 } while(next++);
725 str = getenv("__ALSOFT_DEFAULT_REVERB");
726 if(str && str[0])
727 GetReverbEffect(str, &ForcedEffect);
728 else if(ConfigValueStr(NULL, "default-reverb", &str))
729 GetReverbEffect(str, &ForcedEffect);
733 static void LockLists(void)
735 EnterCriticalSection(&ListLock);
738 static void UnlockLists(void)
740 LeaveCriticalSection(&ListLock);
744 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
746 DO_INITCONFIG();
748 LockLists();
749 free(*list);
750 *list = NULL;
751 *listsize = 0;
753 if(type == CAPTURE_DEVICE_PROBE)
754 CaptureBackend.Probe(type);
755 else
756 PlaybackBackend.Probe(type);
757 UnlockLists();
760 static void ProbeDeviceList(void)
761 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
762 static void ProbeAllDeviceList(void)
763 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
764 static void ProbeCaptureDeviceList(void)
765 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
768 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
770 size_t len = strlen(name);
771 void *temp;
773 if(len == 0)
774 return;
776 temp = realloc(*List, (*ListSize) + len + 2);
777 if(!temp)
779 ERR("Realloc failed to add %s!\n", name);
780 return;
782 *List = temp;
784 memcpy((*List)+(*ListSize), name, len+1);
785 *ListSize += len+1;
786 (*List)[*ListSize] = 0;
789 #define DECL_APPEND_LIST_FUNC(type) \
790 void Append##type##List(const ALCchar *name) \
791 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
793 DECL_APPEND_LIST_FUNC(Device)
794 DECL_APPEND_LIST_FUNC(AllDevice)
795 DECL_APPEND_LIST_FUNC(CaptureDevice)
797 #undef DECL_APPEND_LIST_FUNC
800 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
801 void SetDefaultChannelOrder(ALCdevice *device)
803 switch(device->FmtChans)
805 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
806 device->DevChannels[1] = FRONT_RIGHT;
807 device->DevChannels[2] = BACK_LEFT;
808 device->DevChannels[3] = BACK_RIGHT;
809 device->DevChannels[4] = FRONT_CENTER;
810 device->DevChannels[5] = LFE;
811 return;
813 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
814 device->DevChannels[1] = FRONT_RIGHT;
815 device->DevChannels[2] = BACK_LEFT;
816 device->DevChannels[3] = BACK_RIGHT;
817 device->DevChannels[4] = FRONT_CENTER;
818 device->DevChannels[5] = LFE;
819 device->DevChannels[6] = SIDE_LEFT;
820 device->DevChannels[7] = SIDE_RIGHT;
821 return;
823 /* Same as WFX order */
824 case DevFmtMono:
825 case DevFmtStereo:
826 case DevFmtQuad:
827 case DevFmtX51Side:
828 case DevFmtX61:
829 break;
831 SetDefaultWFXChannelOrder(device);
833 /* Sets the default order used by WaveFormatEx */
834 void SetDefaultWFXChannelOrder(ALCdevice *device)
836 switch(device->FmtChans)
838 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
840 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
841 device->DevChannels[1] = FRONT_RIGHT; break;
843 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
844 device->DevChannels[1] = FRONT_RIGHT;
845 device->DevChannels[2] = BACK_LEFT;
846 device->DevChannels[3] = BACK_RIGHT; break;
848 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
849 device->DevChannels[1] = FRONT_RIGHT;
850 device->DevChannels[2] = FRONT_CENTER;
851 device->DevChannels[3] = LFE;
852 device->DevChannels[4] = BACK_LEFT;
853 device->DevChannels[5] = BACK_RIGHT; break;
855 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
856 device->DevChannels[1] = FRONT_RIGHT;
857 device->DevChannels[2] = FRONT_CENTER;
858 device->DevChannels[3] = LFE;
859 device->DevChannels[4] = SIDE_LEFT;
860 device->DevChannels[5] = SIDE_RIGHT; break;
862 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
863 device->DevChannels[1] = FRONT_RIGHT;
864 device->DevChannels[2] = FRONT_CENTER;
865 device->DevChannels[3] = LFE;
866 device->DevChannels[4] = BACK_CENTER;
867 device->DevChannels[5] = SIDE_LEFT;
868 device->DevChannels[6] = SIDE_RIGHT; break;
870 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
871 device->DevChannels[1] = FRONT_RIGHT;
872 device->DevChannels[2] = FRONT_CENTER;
873 device->DevChannels[3] = LFE;
874 device->DevChannels[4] = BACK_LEFT;
875 device->DevChannels[5] = BACK_RIGHT;
876 device->DevChannels[6] = SIDE_LEFT;
877 device->DevChannels[7] = SIDE_RIGHT; break;
882 const ALCchar *DevFmtTypeString(enum DevFmtType type)
884 switch(type)
886 case DevFmtByte: return "Signed Byte";
887 case DevFmtUByte: return "Unsigned Byte";
888 case DevFmtShort: return "Signed Short";
889 case DevFmtUShort: return "Unsigned Short";
890 case DevFmtFloat: return "Float";
892 return "(unknown type)";
894 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
896 switch(chans)
898 case DevFmtMono: return "Mono";
899 case DevFmtStereo: return "Stereo";
900 case DevFmtQuad: return "Quadraphonic";
901 case DevFmtX51: return "5.1 Surround";
902 case DevFmtX51Side: return "5.1 Side";
903 case DevFmtX61: return "6.1 Surround";
904 case DevFmtX71: return "7.1 Surround";
906 return "(unknown channels)";
909 ALuint BytesFromDevFmt(enum DevFmtType type)
911 switch(type)
913 case DevFmtByte: return sizeof(ALbyte);
914 case DevFmtUByte: return sizeof(ALubyte);
915 case DevFmtShort: return sizeof(ALshort);
916 case DevFmtUShort: return sizeof(ALushort);
917 case DevFmtFloat: return sizeof(ALfloat);
919 return 0;
921 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
923 switch(chans)
925 case DevFmtMono: return 1;
926 case DevFmtStereo: return 2;
927 case DevFmtQuad: return 4;
928 case DevFmtX51: return 6;
929 case DevFmtX51Side: return 6;
930 case DevFmtX61: return 7;
931 case DevFmtX71: return 8;
933 return 0;
935 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
936 enum DevFmtType *type)
938 static const struct {
939 ALenum format;
940 enum DevFmtChannels channels;
941 enum DevFmtType type;
942 } list[] = {
943 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
944 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
945 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
947 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
948 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
949 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
951 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
952 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
953 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
955 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
956 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
957 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
959 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
960 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
961 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
963 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
964 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
965 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
967 ALuint i;
969 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
971 if(list[i].format == format)
973 *chans = list[i].channels;
974 *type = list[i].type;
975 return AL_TRUE;
979 return AL_FALSE;
982 static ALCboolean IsValidALCType(ALCenum type)
984 switch(type)
986 case ALC_BYTE_SOFT:
987 case ALC_UNSIGNED_BYTE_SOFT:
988 case ALC_SHORT_SOFT:
989 case ALC_UNSIGNED_SHORT_SOFT:
990 case ALC_INT_SOFT:
991 case ALC_UNSIGNED_INT_SOFT:
992 case ALC_FLOAT_SOFT:
993 return ALC_TRUE;
995 return ALC_FALSE;
998 static ALCboolean IsValidALCChannels(ALCenum channels)
1000 switch(channels)
1002 case ALC_MONO_SOFT:
1003 case ALC_STEREO_SOFT:
1004 case ALC_QUAD_SOFT:
1005 case ALC_5POINT1_SOFT:
1006 case ALC_6POINT1_SOFT:
1007 case ALC_7POINT1_SOFT:
1008 return ALC_TRUE;
1010 return ALC_FALSE;
1014 /* alcSetError
1016 * Stores the latest ALC Error
1018 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1020 if(TrapALCError)
1022 #ifdef _WIN32
1023 /* DebugBreak() will cause an exception if there is no debugger */
1024 if(IsDebuggerPresent())
1025 DebugBreak();
1026 #elif defined(SIGTRAP)
1027 raise(SIGTRAP);
1028 #endif
1031 if(device)
1032 device->LastError = errorCode;
1033 else
1034 g_eLastNullDeviceError = errorCode;
1038 /* UpdateDeviceParams
1040 * Updates device parameters according to the attribute list (caller is
1041 * responsible for holding the list lock).
1043 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1045 ALCcontext *context;
1046 enum DevFmtChannels oldChans;
1047 enum DevFmtType oldType;
1048 ALCuint oldFreq;
1049 int oldMode;
1050 ALuint i;
1052 // Check for attributes
1053 if(attrList && attrList[0])
1055 ALCuint freq, numMono, numStereo, numSends;
1056 enum DevFmtChannels schans;
1057 enum DevFmtType stype;
1058 ALuint attrIdx;
1060 // If a context is already running on the device, stop playback so the
1061 // device attributes can be updated
1062 if((device->Flags&DEVICE_RUNNING))
1063 ALCdevice_StopPlayback(device);
1064 device->Flags &= ~DEVICE_RUNNING;
1066 freq = device->Frequency;
1067 schans = device->FmtChans;
1068 stype = device->FmtType;
1069 numMono = device->NumMonoSources;
1070 numStereo = device->NumStereoSources;
1071 numSends = device->NumAuxSends;
1073 attrIdx = 0;
1074 while(attrList[attrIdx])
1076 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1077 device->IsLoopbackDevice)
1079 ALCint val = attrList[attrIdx + 1];
1080 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1082 alcSetError(device, ALC_INVALID_VALUE);
1083 return ALC_FALSE;
1085 schans = val;
1088 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1089 device->IsLoopbackDevice)
1091 ALCint val = attrList[attrIdx + 1];
1092 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1094 alcSetError(device, ALC_INVALID_VALUE);
1095 return ALC_FALSE;
1097 stype = val;
1100 if(attrList[attrIdx] == ALC_FREQUENCY)
1102 if(device->IsLoopbackDevice)
1104 freq = attrList[attrIdx + 1];
1105 if(freq < 8000)
1107 alcSetError(device, ALC_INVALID_VALUE);
1108 return ALC_FALSE;
1111 else
1113 freq = attrList[attrIdx + 1];
1114 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1118 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1120 numStereo = attrList[attrIdx + 1];
1121 if(numStereo > device->MaxNoOfSources)
1122 numStereo = device->MaxNoOfSources;
1124 numMono = device->MaxNoOfSources - numStereo;
1127 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1128 numSends = attrList[attrIdx + 1];
1130 attrIdx += 2;
1133 if(!device->IsLoopbackDevice)
1135 ConfigValueUInt(NULL, "frequency", &freq);
1136 freq = maxu(freq, 8000);
1138 ConfigValueUInt(NULL, "sends", &numSends);
1139 numSends = minu(MAX_SENDS, numSends);
1141 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1142 device->Frequency;
1144 device->Frequency = freq;
1145 device->FmtChans = schans;
1146 device->FmtType = stype;
1147 device->NumMonoSources = numMono;
1148 device->NumStereoSources = numStereo;
1149 device->NumAuxSends = numSends;
1152 if((device->Flags&DEVICE_RUNNING))
1153 return ALC_TRUE;
1155 LockDevice(device);
1157 oldFreq = device->Frequency;
1158 oldChans = device->FmtChans;
1159 oldType = device->FmtType;
1161 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1162 DevFmtChannelsString(device->FmtChans),
1163 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1164 DevFmtTypeString(device->FmtType), device->Frequency,
1165 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1166 device->UpdateSize, device->NumUpdates);
1167 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1169 UnlockDevice(device);
1170 return ALC_FALSE;
1172 device->Flags |= DEVICE_RUNNING;
1174 if(device->FmtChans != oldChans)
1176 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1177 ERR("Failed to set %s, got %s instead\n",
1178 DevFmtChannelsString(oldChans),
1179 DevFmtChannelsString(device->FmtChans));
1180 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1182 if(device->Frequency != oldFreq)
1184 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1185 ERR("Failed to set %uhz, got %uhz instead\n",
1186 oldFreq, device->Frequency);
1187 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1190 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1191 DevFmtChannelsString(device->FmtChans),
1192 DevFmtTypeString(device->FmtType), device->Frequency,
1193 device->UpdateSize, device->NumUpdates);
1195 aluInitPanning(device);
1197 for(i = 0;i < MAXCHANNELS;i++)
1199 device->ClickRemoval[i] = 0.0f;
1200 device->PendingClicks[i] = 0.0f;
1203 device->Hrtf = NULL;
1204 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1205 device->Hrtf = GetHrtf(device);
1206 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1208 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1210 if(!device->Bs2b)
1212 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1213 bs2b_clear(device->Bs2b);
1215 bs2b_set_srate(device->Bs2b, device->Frequency);
1216 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1217 TRACE("BS2B level %d\n", device->Bs2bLevel);
1219 else
1221 free(device->Bs2b);
1222 device->Bs2b = NULL;
1223 TRACE("BS2B disabled\n");
1226 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1227 switch(device->FmtChans)
1229 case DevFmtMono:
1230 case DevFmtStereo:
1231 break;
1232 case DevFmtQuad:
1233 case DevFmtX51:
1234 case DevFmtX51Side:
1235 case DevFmtX61:
1236 case DevFmtX71:
1237 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1238 device->Flags |= DEVICE_DUPLICATE_STEREO;
1239 break;
1241 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1243 oldMode = SetMixerFPUMode();
1244 context = device->ContextList;
1245 while(context)
1247 ALsizei pos;
1249 context->UpdateSources = AL_FALSE;
1250 LockUIntMapRead(&context->EffectSlotMap);
1251 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1253 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1255 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1257 UnlockUIntMapRead(&context->EffectSlotMap);
1258 RestoreFPUMode(oldMode);
1259 UnlockDevice(device);
1260 ALCdevice_StopPlayback(device);
1261 device->Flags &= ~DEVICE_RUNNING;
1262 return ALC_FALSE;
1264 slot->NeedsUpdate = AL_FALSE;
1265 ALeffectState_Update(slot->EffectState, context, slot);
1267 UnlockUIntMapRead(&context->EffectSlotMap);
1269 LockUIntMapRead(&context->SourceMap);
1270 for(pos = 0;pos < context->SourceMap.size;pos++)
1272 ALsource *source = context->SourceMap.array[pos].value;
1273 ALuint s = device->NumAuxSends;
1274 while(s < MAX_SENDS)
1276 if(source->Send[s].Slot)
1277 DecrementRef(&source->Send[s].Slot->ref);
1278 source->Send[s].Slot = NULL;
1279 source->Send[s].WetGain = 1.0f;
1280 source->Send[s].WetGainHF = 1.0f;
1281 s++;
1283 source->NeedsUpdate = AL_FALSE;
1284 ALsource_Update(source, context);
1286 UnlockUIntMapRead(&context->SourceMap);
1288 context = context->next;
1290 RestoreFPUMode(oldMode);
1291 UnlockDevice(device);
1293 return ALC_TRUE;
1296 /* FreeDevice
1298 * Frees the device structure, and destroys any objects the app failed to
1299 * delete. Called once there's no more references on the device.
1301 static ALCvoid FreeDevice(ALCdevice *device)
1303 TRACE("%p\n", device);
1305 if(device->DefaultSlot)
1307 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1308 device->DefaultSlot->EffectState = NULL;
1311 if(device->BufferMap.size > 0)
1313 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1314 ReleaseALBuffers(device);
1316 ResetUIntMap(&device->BufferMap);
1318 if(device->EffectMap.size > 0)
1320 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1321 ReleaseALEffects(device);
1323 ResetUIntMap(&device->EffectMap);
1325 if(device->FilterMap.size > 0)
1327 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1328 ReleaseALFilters(device);
1330 ResetUIntMap(&device->FilterMap);
1332 free(device->Bs2b);
1333 device->Bs2b = NULL;
1335 free(device->szDeviceName);
1336 device->szDeviceName = NULL;
1338 DeleteCriticalSection(&device->Mutex);
1340 free(device);
1344 void ALCdevice_IncRef(ALCdevice *device)
1346 RefCount ref;
1347 ref = IncrementRef(&device->ref);
1348 TRACEREF("%p increasing refcount to %u\n", device, ref);
1351 void ALCdevice_DecRef(ALCdevice *device)
1353 RefCount ref;
1354 ref = DecrementRef(&device->ref);
1355 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1356 if(ref == 0) FreeDevice(device);
1359 /* VerifyDevice
1361 * Checks if the device handle is valid, and increments its ref count if so.
1363 static ALCdevice *VerifyDevice(ALCdevice *device)
1365 ALCdevice *tmpDevice;
1367 if(!device)
1368 return NULL;
1370 LockLists();
1371 tmpDevice = DeviceList;
1372 while(tmpDevice && tmpDevice != device)
1373 tmpDevice = tmpDevice->next;
1375 if(tmpDevice)
1376 ALCdevice_IncRef(tmpDevice);
1377 UnlockLists();
1378 return tmpDevice;
1382 /* InitContext
1384 * Initializes context variables
1386 static ALvoid InitContext(ALCcontext *pContext)
1388 ALint i, j;
1390 //Initialise listener
1391 pContext->Listener.Gain = 1.0f;
1392 pContext->Listener.MetersPerUnit = 1.0f;
1393 pContext->Listener.Position[0] = 0.0f;
1394 pContext->Listener.Position[1] = 0.0f;
1395 pContext->Listener.Position[2] = 0.0f;
1396 pContext->Listener.Velocity[0] = 0.0f;
1397 pContext->Listener.Velocity[1] = 0.0f;
1398 pContext->Listener.Velocity[2] = 0.0f;
1399 pContext->Listener.Forward[0] = 0.0f;
1400 pContext->Listener.Forward[1] = 0.0f;
1401 pContext->Listener.Forward[2] = -1.0f;
1402 pContext->Listener.Up[0] = 0.0f;
1403 pContext->Listener.Up[1] = 1.0f;
1404 pContext->Listener.Up[2] = 0.0f;
1405 for(i = 0;i < 4;i++)
1407 for(j = 0;j < 4;j++)
1408 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1411 //Validate pContext
1412 pContext->LastError = AL_NO_ERROR;
1413 pContext->UpdateSources = AL_FALSE;
1414 pContext->ActiveSourceCount = 0;
1415 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1416 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1418 //Set globals
1419 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1420 pContext->SourceDistanceModel = AL_FALSE;
1421 pContext->DopplerFactor = 1.0f;
1422 pContext->DopplerVelocity = 1.0f;
1423 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1424 pContext->DeferUpdates = AL_FALSE;
1426 pContext->ExtensionList = alExtList;
1430 /* FreeContext
1432 * Cleans up the context, and destroys any remaining objects the app failed to
1433 * delete. Called once there's no more references on the context.
1435 static ALCvoid FreeContext(ALCcontext *context)
1437 TRACE("%p\n", context);
1439 if(context->SourceMap.size > 0)
1441 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1442 ReleaseALSources(context);
1444 ResetUIntMap(&context->SourceMap);
1446 if(context->EffectSlotMap.size > 0)
1448 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1449 ReleaseALAuxiliaryEffectSlots(context);
1451 ResetUIntMap(&context->EffectSlotMap);
1453 context->ActiveSourceCount = 0;
1454 free(context->ActiveSources);
1455 context->ActiveSources = NULL;
1456 context->MaxActiveSources = 0;
1458 context->ActiveEffectSlotCount = 0;
1459 free(context->ActiveEffectSlots);
1460 context->ActiveEffectSlots = NULL;
1461 context->MaxActiveEffectSlots = 0;
1463 ALCdevice_DecRef(context->Device);
1464 context->Device = NULL;
1466 //Invalidate context
1467 memset(context, 0, sizeof(ALCcontext));
1468 free(context);
1471 /* ReleaseContext
1473 * Removes the context reference from the given device and removes it from
1474 * being current on the running thread or globally.
1476 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1478 ALCcontext *volatile*tmp_ctx;
1480 if(pthread_getspecific(LocalContext) == context)
1482 WARN("%p released while current on thread\n", context);
1483 pthread_setspecific(LocalContext, NULL);
1484 ALCcontext_DecRef(context);
1487 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1488 ALCcontext_DecRef(context);
1490 LockDevice(device);
1491 tmp_ctx = &device->ContextList;
1492 while(*tmp_ctx)
1494 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1495 break;
1496 tmp_ctx = &(*tmp_ctx)->next;
1498 UnlockDevice(device);
1500 ALCcontext_DecRef(context);
1503 void ALCcontext_IncRef(ALCcontext *context)
1505 RefCount ref;
1506 ref = IncrementRef(&context->ref);
1507 TRACEREF("%p increasing refcount to %u\n", context, ref);
1510 void ALCcontext_DecRef(ALCcontext *context)
1512 RefCount ref;
1513 ref = DecrementRef(&context->ref);
1514 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1515 if(ref == 0) FreeContext(context);
1518 static void ReleaseThreadCtx(void *ptr)
1520 WARN("%p current for thread being destroyed\n", ptr);
1521 ALCcontext_DecRef(ptr);
1524 /* VerifyContext
1526 * Checks that the given context is valid, and increments its reference count.
1528 static ALCcontext *VerifyContext(ALCcontext *context)
1530 ALCdevice *dev;
1532 LockLists();
1533 dev = DeviceList;
1534 while(dev)
1536 ALCcontext *tmp_ctx = dev->ContextList;
1537 while(tmp_ctx)
1539 if(tmp_ctx == context)
1541 ALCcontext_IncRef(tmp_ctx);
1542 UnlockLists();
1543 return tmp_ctx;
1545 tmp_ctx = tmp_ctx->next;
1547 dev = dev->next;
1549 UnlockLists();
1551 return NULL;
1555 /* GetContextRef
1557 * Returns the currently active context, and adds a reference without locking
1558 * it.
1560 ALCcontext *GetContextRef(void)
1562 ALCcontext *context;
1564 context = pthread_getspecific(LocalContext);
1565 if(context)
1566 ALCcontext_IncRef(context);
1567 else
1569 LockLists();
1570 context = GlobalContext;
1571 if(context)
1572 ALCcontext_IncRef(context);
1573 UnlockLists();
1576 return context;
1579 ///////////////////////////////////////////////////////
1582 ///////////////////////////////////////////////////////
1583 // ALC Functions calls
1586 // This should probably move to another c file but for now ...
1587 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1589 ALCdevice *device = NULL;
1590 ALCenum err;
1592 DO_INITCONFIG();
1594 if(!CaptureBackend.name)
1596 alcSetError(NULL, ALC_INVALID_VALUE);
1597 return NULL;
1600 if(SampleSize <= 0)
1602 alcSetError(NULL, ALC_INVALID_VALUE);
1603 return NULL;
1606 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1607 deviceName = NULL;
1609 device = calloc(1, sizeof(ALCdevice));
1610 if(!device)
1612 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1613 return NULL;
1616 //Validate device
1617 device->Funcs = &CaptureBackend.Funcs;
1618 device->ref = 1;
1619 device->Connected = ALC_TRUE;
1620 device->IsCaptureDevice = AL_TRUE;
1621 device->IsLoopbackDevice = AL_FALSE;
1622 InitializeCriticalSection(&device->Mutex);
1624 InitUIntMap(&device->BufferMap, ~0);
1625 InitUIntMap(&device->EffectMap, ~0);
1626 InitUIntMap(&device->FilterMap, ~0);
1628 device->szDeviceName = NULL;
1630 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1631 device->Frequency = frequency;
1633 device->Flags |= DEVICE_CHANNELS_REQUEST;
1634 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1636 DeleteCriticalSection(&device->Mutex);
1637 free(device);
1638 alcSetError(NULL, ALC_INVALID_ENUM);
1639 return NULL;
1642 device->UpdateSize = SampleSize;
1643 device->NumUpdates = 1;
1645 LockLists();
1646 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1648 UnlockLists();
1649 DeleteCriticalSection(&device->Mutex);
1650 free(device);
1651 alcSetError(NULL, err);
1652 return NULL;
1654 UnlockLists();
1656 do {
1657 device->next = DeviceList;
1658 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1660 TRACE("Created device %p\n", device);
1661 return device;
1664 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1666 ALCdevice *volatile*list;
1668 LockLists();
1669 list = &DeviceList;
1670 while(*list && *list != pDevice)
1671 list = &(*list)->next;
1673 if(!*list || !(*list)->IsCaptureDevice)
1675 alcSetError(*list, ALC_INVALID_DEVICE);
1676 UnlockLists();
1677 return ALC_FALSE;
1680 *list = (*list)->next;
1681 UnlockLists();
1683 LockDevice(pDevice);
1684 ALCdevice_CloseCapture(pDevice);
1685 UnlockDevice(pDevice);
1687 ALCdevice_DecRef(pDevice);
1689 return ALC_TRUE;
1692 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1694 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1696 alcSetError(device, ALC_INVALID_DEVICE);
1697 if(device) ALCdevice_DecRef(device);
1698 return;
1700 LockDevice(device);
1701 if(device->Connected)
1702 ALCdevice_StartCapture(device);
1703 UnlockDevice(device);
1705 ALCdevice_DecRef(device);
1708 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1710 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1712 alcSetError(device, ALC_INVALID_DEVICE);
1713 if(device) ALCdevice_DecRef(device);
1714 return;
1716 LockDevice(device);
1717 if(device->Connected)
1718 ALCdevice_StopCapture(device);
1719 UnlockDevice(device);
1721 ALCdevice_DecRef(device);
1724 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1726 ALCenum err = ALC_INVALID_DEVICE;
1727 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1729 err = ALC_INVALID_VALUE;
1730 LockDevice(device);
1731 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1732 err = ALCdevice_CaptureSamples(device, buffer, samples);
1733 UnlockDevice(device);
1735 if(err != ALC_NO_ERROR)
1736 alcSetError(device, err);
1737 if(device) ALCdevice_DecRef(device);
1741 alcGetError
1743 Return last ALC generated error code
1745 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1747 ALCenum errorCode;
1749 if(VerifyDevice(device))
1751 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1752 ALCdevice_DecRef(device);
1754 else
1755 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1757 return errorCode;
1761 /* alcSuspendContext
1763 * Not functional
1765 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1767 (void)Context;
1770 /* alcProcessContext
1772 * Not functional
1774 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1776 (void)Context;
1780 /* alcGetString
1782 * Returns information about the Device, and error strings
1784 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1786 const ALCchar *value = NULL;
1788 switch(param)
1790 case ALC_NO_ERROR:
1791 value = alcNoError;
1792 break;
1794 case ALC_INVALID_ENUM:
1795 value = alcErrInvalidEnum;
1796 break;
1798 case ALC_INVALID_VALUE:
1799 value = alcErrInvalidValue;
1800 break;
1802 case ALC_INVALID_DEVICE:
1803 value = alcErrInvalidDevice;
1804 break;
1806 case ALC_INVALID_CONTEXT:
1807 value = alcErrInvalidContext;
1808 break;
1810 case ALC_OUT_OF_MEMORY:
1811 value = alcErrOutOfMemory;
1812 break;
1814 case ALC_DEVICE_SPECIFIER:
1815 if(VerifyDevice(pDevice))
1817 value = pDevice->szDeviceName;
1818 ALCdevice_DecRef(pDevice);
1820 else
1822 ProbeDeviceList();
1823 value = alcDeviceList;
1825 break;
1827 case ALC_ALL_DEVICES_SPECIFIER:
1828 ProbeAllDeviceList();
1829 value = alcAllDeviceList;
1830 break;
1832 case ALC_CAPTURE_DEVICE_SPECIFIER:
1833 if(VerifyDevice(pDevice))
1835 value = pDevice->szDeviceName;
1836 ALCdevice_DecRef(pDevice);
1838 else
1840 ProbeCaptureDeviceList();
1841 value = alcCaptureDeviceList;
1843 break;
1845 /* Default devices are always first in the list */
1846 case ALC_DEFAULT_DEVICE_SPECIFIER:
1847 if(!alcDeviceList)
1848 ProbeDeviceList();
1850 pDevice = VerifyDevice(pDevice);
1852 free(alcDefaultDeviceSpecifier);
1853 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1854 if(!alcDefaultDeviceSpecifier)
1855 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1857 value = alcDefaultDeviceSpecifier;
1858 if(pDevice) ALCdevice_DecRef(pDevice);
1859 break;
1861 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1862 if(!alcAllDeviceList)
1863 ProbeAllDeviceList();
1865 pDevice = VerifyDevice(pDevice);
1867 free(alcDefaultAllDeviceSpecifier);
1868 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1869 alcAllDeviceList : "");
1870 if(!alcDefaultAllDeviceSpecifier)
1871 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1873 value = alcDefaultAllDeviceSpecifier;
1874 if(pDevice) ALCdevice_DecRef(pDevice);
1875 break;
1877 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1878 if(!alcCaptureDeviceList)
1879 ProbeCaptureDeviceList();
1881 pDevice = VerifyDevice(pDevice);
1883 free(alcCaptureDefaultDeviceSpecifier);
1884 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1885 alcCaptureDeviceList : "");
1886 if(!alcCaptureDefaultDeviceSpecifier)
1887 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1889 value = alcCaptureDefaultDeviceSpecifier;
1890 if(pDevice) ALCdevice_DecRef(pDevice);
1891 break;
1893 case ALC_EXTENSIONS:
1894 if(!VerifyDevice(pDevice))
1895 value = alcNoDeviceExtList;
1896 else
1898 value = alcExtensionList;
1899 ALCdevice_DecRef(pDevice);
1901 break;
1903 default:
1904 pDevice = VerifyDevice(pDevice);
1905 alcSetError(pDevice, ALC_INVALID_ENUM);
1906 if(pDevice) ALCdevice_DecRef(pDevice);
1907 break;
1910 return value;
1914 /* alcGetIntegerv
1916 * Returns information about the Device and the version of Open AL
1918 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1920 device = VerifyDevice(device);
1922 if(size == 0 || data == NULL)
1924 alcSetError(device, ALC_INVALID_VALUE);
1925 if(device) ALCdevice_DecRef(device);
1926 return;
1929 if(!device)
1931 switch(param)
1933 case ALC_MAJOR_VERSION:
1934 *data = alcMajorVersion;
1935 break;
1936 case ALC_MINOR_VERSION:
1937 *data = alcMinorVersion;
1938 break;
1940 case ALC_ATTRIBUTES_SIZE:
1941 case ALC_ALL_ATTRIBUTES:
1942 case ALC_FREQUENCY:
1943 case ALC_REFRESH:
1944 case ALC_SYNC:
1945 case ALC_MONO_SOURCES:
1946 case ALC_STEREO_SOURCES:
1947 case ALC_CAPTURE_SAMPLES:
1948 case ALC_FORMAT_CHANNELS_SOFT:
1949 case ALC_FORMAT_TYPE_SOFT:
1950 alcSetError(NULL, ALC_INVALID_DEVICE);
1951 break;
1953 default:
1954 alcSetError(NULL, ALC_INVALID_ENUM);
1955 break;
1958 else if(device->IsCaptureDevice)
1960 switch(param)
1962 case ALC_CAPTURE_SAMPLES:
1963 LockDevice(device);
1964 *data = ALCdevice_AvailableSamples(device);
1965 UnlockDevice(device);
1966 break;
1968 case ALC_CONNECTED:
1969 *data = device->Connected;
1970 break;
1972 default:
1973 alcSetError(device, ALC_INVALID_ENUM);
1974 break;
1977 else /* render device */
1979 switch(param)
1981 case ALC_MAJOR_VERSION:
1982 *data = alcMajorVersion;
1983 break;
1985 case ALC_MINOR_VERSION:
1986 *data = alcMinorVersion;
1987 break;
1989 case ALC_EFX_MAJOR_VERSION:
1990 *data = alcEFXMajorVersion;
1991 break;
1993 case ALC_EFX_MINOR_VERSION:
1994 *data = alcEFXMinorVersion;
1995 break;
1997 case ALC_ATTRIBUTES_SIZE:
1998 *data = 13;
1999 break;
2001 case ALC_ALL_ATTRIBUTES:
2002 if(size < 13)
2003 alcSetError(device, ALC_INVALID_VALUE);
2004 else
2006 int i = 0;
2008 data[i++] = ALC_FREQUENCY;
2009 data[i++] = device->Frequency;
2011 if(!device->IsLoopbackDevice)
2013 data[i++] = ALC_REFRESH;
2014 data[i++] = device->Frequency / device->UpdateSize;
2016 data[i++] = ALC_SYNC;
2017 data[i++] = ALC_FALSE;
2019 else
2021 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2022 data[i++] = device->FmtChans;
2024 data[i++] = ALC_FORMAT_TYPE_SOFT;
2025 data[i++] = device->FmtType;
2028 data[i++] = ALC_MONO_SOURCES;
2029 data[i++] = device->NumMonoSources;
2031 data[i++] = ALC_STEREO_SOURCES;
2032 data[i++] = device->NumStereoSources;
2034 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2035 data[i++] = device->NumAuxSends;
2037 data[i++] = 0;
2039 break;
2041 case ALC_FREQUENCY:
2042 *data = device->Frequency;
2043 break;
2045 case ALC_REFRESH:
2046 if(device->IsLoopbackDevice)
2047 alcSetError(device, ALC_INVALID_DEVICE);
2048 else
2049 *data = device->Frequency / device->UpdateSize;
2050 break;
2052 case ALC_SYNC:
2053 if(device->IsLoopbackDevice)
2054 alcSetError(device, ALC_INVALID_DEVICE);
2055 else
2056 *data = ALC_FALSE;
2057 break;
2059 case ALC_FORMAT_CHANNELS_SOFT:
2060 if(!device->IsLoopbackDevice)
2061 alcSetError(device, ALC_INVALID_DEVICE);
2062 else
2063 *data = device->FmtChans;
2064 break;
2066 case ALC_FORMAT_TYPE_SOFT:
2067 if(!device->IsLoopbackDevice)
2068 alcSetError(device, ALC_INVALID_DEVICE);
2069 else
2070 *data = device->FmtType;
2071 break;
2073 case ALC_MONO_SOURCES:
2074 *data = device->NumMonoSources;
2075 break;
2077 case ALC_STEREO_SOURCES:
2078 *data = device->NumStereoSources;
2079 break;
2081 case ALC_MAX_AUXILIARY_SENDS:
2082 *data = device->NumAuxSends;
2083 break;
2085 case ALC_CONNECTED:
2086 *data = device->Connected;
2087 break;
2089 default:
2090 alcSetError(device, ALC_INVALID_ENUM);
2091 break;
2094 if(device)
2095 ALCdevice_DecRef(device);
2099 /* alcIsExtensionPresent
2101 * Determines if there is support for a particular extension
2103 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2105 ALCboolean bResult = ALC_FALSE;
2107 device = VerifyDevice(device);
2109 if(!extName)
2110 alcSetError(device, ALC_INVALID_VALUE);
2111 else
2113 size_t len = strlen(extName);
2114 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2115 while(ptr && *ptr)
2117 if(strncasecmp(ptr, extName, len) == 0 &&
2118 (ptr[len] == '\0' || isspace(ptr[len])))
2120 bResult = ALC_TRUE;
2121 break;
2123 if((ptr=strchr(ptr, ' ')) != NULL)
2125 do {
2126 ++ptr;
2127 } while(isspace(*ptr));
2131 if(device)
2132 ALCdevice_DecRef(device);
2133 return bResult;
2137 /* alcGetProcAddress
2139 * Retrieves the function address for a particular extension function
2141 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2143 ALCvoid *ptr = NULL;
2145 device = VerifyDevice(device);
2147 if(!funcName)
2148 alcSetError(device, ALC_INVALID_VALUE);
2149 else
2151 ALsizei i = 0;
2152 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2153 i++;
2154 ptr = alcFunctions[i].address;
2156 if(device)
2157 ALCdevice_DecRef(device);
2158 return ptr;
2162 /* alcGetEnumValue
2164 * Get the value for a particular ALC Enumerated Value
2166 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2168 ALCenum val = 0;
2170 device = VerifyDevice(device);
2172 if(!enumName)
2173 alcSetError(device, ALC_INVALID_VALUE);
2174 else
2176 ALsizei i = 0;
2177 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2178 i++;
2179 val = enumeration[i].value;
2181 if(device)
2182 ALCdevice_DecRef(device);
2183 return val;
2187 /* alcCreateContext
2189 * Create and attach a Context to a particular Device.
2191 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2193 ALCcontext *ALContext;
2195 LockLists();
2196 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2198 UnlockLists();
2199 alcSetError(device, ALC_INVALID_DEVICE);
2200 if(device) ALCdevice_DecRef(device);
2201 return NULL;
2204 /* Reset Context Last Error code */
2205 device->LastError = ALC_NO_ERROR;
2207 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2209 UnlockLists();
2210 alcSetError(device, ALC_INVALID_DEVICE);
2211 aluHandleDisconnect(device);
2212 ALCdevice_DecRef(device);
2213 return NULL;
2216 ALContext = calloc(1, sizeof(ALCcontext));
2217 if(ALContext)
2219 ALContext->ref = 1;
2221 ALContext->MaxActiveSources = 256;
2222 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2223 ALContext->MaxActiveSources);
2225 if(!ALContext || !ALContext->ActiveSources)
2227 if(!device->ContextList)
2229 ALCdevice_StopPlayback(device);
2230 device->Flags &= ~DEVICE_RUNNING;
2232 UnlockLists();
2234 free(ALContext);
2235 ALContext = NULL;
2237 alcSetError(device, ALC_OUT_OF_MEMORY);
2238 ALCdevice_DecRef(device);
2239 return NULL;
2242 ALContext->Device = device;
2243 ALCdevice_IncRef(device);
2244 InitContext(ALContext);
2246 do {
2247 ALContext->next = device->ContextList;
2248 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2249 UnlockLists();
2251 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2253 ALCdevice_DecRef(device);
2255 TRACE("Created context %p\n", ALContext);
2256 return ALContext;
2259 /* alcDestroyContext
2261 * Remove a Context
2263 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2265 ALCdevice *Device;
2267 LockLists();
2268 /* alcGetContextsDevice sets an error for invalid contexts */
2269 Device = alcGetContextsDevice(context);
2270 if(Device)
2272 ReleaseContext(context, Device);
2273 if(!Device->ContextList)
2275 ALCdevice_StopPlayback(Device);
2276 Device->Flags &= ~DEVICE_RUNNING;
2279 UnlockLists();
2283 /* alcGetCurrentContext
2285 * Returns the currently active Context
2287 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2289 ALCcontext *Context;
2291 Context = pthread_getspecific(LocalContext);
2292 if(!Context) Context = GlobalContext;
2294 return Context;
2297 /* alcGetThreadContext
2299 * Returns the currently active thread-local Context
2301 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2303 ALCcontext *Context;
2304 Context = pthread_getspecific(LocalContext);
2305 return Context;
2309 /* alcMakeContextCurrent
2311 * Makes the given Context the active Context
2313 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2315 /* context must be a valid Context or NULL */
2316 if(context && !(context=VerifyContext(context)))
2318 alcSetError(NULL, ALC_INVALID_CONTEXT);
2319 return ALC_FALSE;
2321 /* context's reference count is already incremented */
2322 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2323 if(context) ALCcontext_DecRef(context);
2325 if((context=pthread_getspecific(LocalContext)) != NULL)
2327 pthread_setspecific(LocalContext, NULL);
2328 ALCcontext_DecRef(context);
2331 return ALC_TRUE;
2334 /* alcSetThreadContext
2336 * Makes the given Context the active Context for the current thread
2338 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2340 ALCcontext *old;
2342 /* context must be a valid Context or NULL */
2343 if(context && !(context=VerifyContext(context)))
2345 alcSetError(NULL, ALC_INVALID_CONTEXT);
2346 return ALC_FALSE;
2348 /* context's reference count is already incremented */
2349 old = pthread_getspecific(LocalContext);
2350 pthread_setspecific(LocalContext, context);
2351 if(old) ALCcontext_DecRef(old);
2353 return ALC_TRUE;
2357 /* alcGetContextsDevice
2359 * Returns the Device that a particular Context is attached to
2361 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2363 ALCdevice *Device;
2365 if(!(Context=VerifyContext(Context)))
2367 alcSetError(NULL, ALC_INVALID_CONTEXT);
2368 return NULL;
2370 Device = Context->Device;
2371 ALCcontext_DecRef(Context);
2373 return Device;
2377 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2379 static const struct {
2380 const char name[32];
2381 enum DevFmtChannels channels;
2382 enum DevFmtType type;
2383 } formats[] = {
2384 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2385 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2386 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2387 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2388 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2389 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2391 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2392 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2393 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2394 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2395 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2396 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2398 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2399 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2400 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2401 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2402 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2403 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2405 size_t i;
2407 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2409 if(strcasecmp(str, formats[i].name) == 0)
2411 *chans = formats[i].channels;
2412 *type = formats[i].type;
2413 return;
2417 ERR("Unknown format: \"%s\"\n", str);
2418 *chans = DevFmtStereo;
2419 *type = DevFmtShort;
2422 /* alcOpenDevice
2424 * Open the Device specified.
2426 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2428 const ALCchar *fmt;
2429 ALCdevice *device;
2430 ALCenum err;
2431 ALCint i;
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 device->DefaultSlot->EffectState = NoneCreate();
2511 device->DefaultSlot->Gain = 1.0;
2512 device->DefaultSlot->AuxSendAuto = AL_TRUE;
2513 device->DefaultSlot->NeedsUpdate = AL_FALSE;
2514 for(i = 0;i < BUFFERSIZE;i++)
2515 device->DefaultSlot->WetBuffer[i] = 0.0f;
2516 for(i = 0;i < 1;i++)
2518 device->DefaultSlot->ClickRemoval[i] = 0.0f;
2519 device->DefaultSlot->PendingClicks[i] = 0.0f;
2521 device->DefaultSlot->ref = 0;
2523 // Find a playback device to open
2524 LockLists();
2525 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2527 UnlockLists();
2528 DeleteCriticalSection(&device->Mutex);
2529 free(device);
2530 alcSetError(NULL, err);
2531 return NULL;
2533 UnlockLists();
2535 do {
2536 device->next = DeviceList;
2537 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2539 TRACE("Created device %p\n", device);
2540 return device;
2543 /* alcCloseDevice
2545 * Close the specified Device
2547 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2549 ALCdevice *volatile*list;
2550 ALCcontext *ctx;
2552 LockLists();
2553 list = &DeviceList;
2554 while(*list && *list != pDevice)
2555 list = &(*list)->next;
2557 if(!*list || (*list)->IsCaptureDevice)
2559 alcSetError(*list, ALC_INVALID_DEVICE);
2560 UnlockLists();
2561 return ALC_FALSE;
2564 *list = (*list)->next;
2565 UnlockLists();
2567 if((ctx=pDevice->ContextList) != NULL)
2569 do {
2570 WARN("Releasing context %p\n", ctx);
2571 ReleaseContext(ctx, pDevice);
2572 } while((ctx=pDevice->ContextList) != NULL);
2573 ALCdevice_StopPlayback(pDevice);
2574 pDevice->Flags &= ~DEVICE_RUNNING;
2576 ALCdevice_ClosePlayback(pDevice);
2578 ALCdevice_DecRef(pDevice);
2580 return ALC_TRUE;
2584 /* alcLoopbackOpenDeviceSOFT
2586 * Open a loopback device, for manual rendering.
2588 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2590 ALCdevice *device;
2592 DO_INITCONFIG();
2594 device = calloc(1, sizeof(ALCdevice));
2595 if(!device)
2597 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2598 return NULL;
2601 //Validate device
2602 device->Funcs = &BackendLoopback.Funcs;
2603 device->ref = 1;
2604 device->Connected = ALC_TRUE;
2605 device->IsCaptureDevice = AL_FALSE;
2606 device->IsLoopbackDevice = AL_TRUE;
2607 InitializeCriticalSection(&device->Mutex);
2608 device->LastError = ALC_NO_ERROR;
2610 device->Flags = 0;
2611 device->Bs2b = NULL;
2612 device->Bs2bLevel = 0;
2613 device->szDeviceName = NULL;
2615 device->ContextList = NULL;
2617 device->MaxNoOfSources = 256;
2618 device->AuxiliaryEffectSlotMax = 4;
2619 device->NumAuxSends = MAX_SENDS;
2621 InitUIntMap(&device->BufferMap, ~0);
2622 InitUIntMap(&device->EffectMap, ~0);
2623 InitUIntMap(&device->FilterMap, ~0);
2625 //Set output format
2626 device->NumUpdates = 0;
2627 device->UpdateSize = 0;
2629 device->Frequency = 44100;
2630 device->FmtChans = DevFmtStereo;
2631 device->FmtType = DevFmtShort;
2633 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2634 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2636 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2637 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2639 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2640 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2642 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2644 device->NumStereoSources = 1;
2645 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2647 // Open the "backend"
2648 ALCdevice_OpenPlayback(device, "Loopback");
2649 do {
2650 device->next = DeviceList;
2651 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2653 TRACE("Created device %p\n", device);
2654 return device;
2657 /* alcIsRenderFormatSupportedSOFT
2659 * Determines if the loopback device supports the given format for rendering.
2661 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2663 ALCboolean ret = ALC_FALSE;
2665 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2666 alcSetError(device, ALC_INVALID_DEVICE);
2667 else if(freq <= 0)
2668 alcSetError(device, ALC_INVALID_VALUE);
2669 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2670 alcSetError(device, ALC_INVALID_ENUM);
2671 else
2673 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2674 freq >= 8000)
2675 ret = ALC_TRUE;
2677 if(device) ALCdevice_DecRef(device);
2679 return ret;
2682 /* alcRenderSamplesSOFT
2684 * Renders some samples into a buffer, using the format last set by the
2685 * attributes given to alcCreateContext.
2687 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2689 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2690 alcSetError(device, ALC_INVALID_DEVICE);
2691 else if(samples < 0 || (samples > 0 && buffer == NULL))
2692 alcSetError(device, ALC_INVALID_VALUE);
2693 else
2694 aluMixData(device, buffer, samples);
2695 if(device) ALCdevice_DecRef(device);
2699 static void ReleaseALC(void)
2701 ALCdevice *dev;
2703 free(alcDeviceList); alcDeviceList = NULL;
2704 alcDeviceListSize = 0;
2705 free(alcAllDeviceList); alcAllDeviceList = NULL;
2706 alcAllDeviceListSize = 0;
2707 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2708 alcCaptureDeviceListSize = 0;
2710 free(alcDefaultDeviceSpecifier);
2711 alcDefaultDeviceSpecifier = NULL;
2712 free(alcDefaultAllDeviceSpecifier);
2713 alcDefaultAllDeviceSpecifier = NULL;
2714 free(alcCaptureDefaultDeviceSpecifier);
2715 alcCaptureDefaultDeviceSpecifier = NULL;
2717 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2719 ALCuint num = 0;
2720 do {
2721 num++;
2722 } while((dev=dev->next) != NULL);
2723 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2727 ///////////////////////////////////////////////////////