Don't enable BS2B for loopback devices
[openal-soft.git] / Alc / ALc.c
blobf5f7bbe04f3fbbed3ab5593d9b64aac273a14ef8
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <math.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <memory.h>
27 #include <ctype.h>
28 #include <signal.h>
30 #include "alMain.h"
31 #include "alSource.h"
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "alThunk.h"
35 #include "alSource.h"
36 #include "alBuffer.h"
37 #include "alAuxEffectSlot.h"
38 #include "alError.h"
39 #include "bs2b.h"
40 #include "alu.h"
43 #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
44 static struct BackendInfo BackendList[] = {
45 #ifdef HAVE_PULSEAUDIO
46 { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs },
47 #endif
48 #ifdef HAVE_ALSA
49 { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs },
50 #endif
51 #ifdef HAVE_COREAUDIO
52 { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs },
53 #endif
54 #ifdef HAVE_OSS
55 { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs },
56 #endif
57 #ifdef HAVE_SOLARIS
58 { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs },
59 #endif
60 #ifdef HAVE_SNDIO
61 { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs },
62 #endif
63 #ifdef HAVE_MMDEVAPI
64 { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs },
65 #endif
66 #ifdef HAVE_DSOUND
67 { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs },
68 #endif
69 #ifdef HAVE_WINMM
70 { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs },
71 #endif
72 #ifdef HAVE_PORTAUDIO
73 { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs },
74 #endif
75 #ifdef HAVE_OPENSL
76 { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs },
77 #endif
79 { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs },
80 #ifdef HAVE_WAVE
81 { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs },
82 #endif
84 { NULL, NULL, NULL, NULL, EmptyFuncs }
86 static struct BackendInfo BackendLoopback = {
87 "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs
89 #undef EmptyFuncs
91 static struct BackendInfo PlaybackBackend;
92 static struct BackendInfo CaptureBackend;
94 ///////////////////////////////////////////////////////
95 // STRING and EXTENSIONS
97 typedef struct ALCfunction {
98 const ALCchar *funcName;
99 ALCvoid *address;
100 } ALCfunction;
102 typedef struct ALCenums {
103 const ALCchar *enumName;
104 ALCenum value;
105 } ALCenums;
108 static const ALCfunction alcFunctions[] = {
109 { "alcCreateContext", (ALCvoid *) alcCreateContext },
110 { "alcMakeContextCurrent", (ALCvoid *) alcMakeContextCurrent },
111 { "alcProcessContext", (ALCvoid *) alcProcessContext },
112 { "alcSuspendContext", (ALCvoid *) alcSuspendContext },
113 { "alcDestroyContext", (ALCvoid *) alcDestroyContext },
114 { "alcGetCurrentContext", (ALCvoid *) alcGetCurrentContext },
115 { "alcGetContextsDevice", (ALCvoid *) alcGetContextsDevice },
116 { "alcOpenDevice", (ALCvoid *) alcOpenDevice },
117 { "alcCloseDevice", (ALCvoid *) alcCloseDevice },
118 { "alcGetError", (ALCvoid *) alcGetError },
119 { "alcIsExtensionPresent", (ALCvoid *) alcIsExtensionPresent },
120 { "alcGetProcAddress", (ALCvoid *) alcGetProcAddress },
121 { "alcGetEnumValue", (ALCvoid *) alcGetEnumValue },
122 { "alcGetString", (ALCvoid *) alcGetString },
123 { "alcGetIntegerv", (ALCvoid *) alcGetIntegerv },
124 { "alcCaptureOpenDevice", (ALCvoid *) alcCaptureOpenDevice },
125 { "alcCaptureCloseDevice", (ALCvoid *) alcCaptureCloseDevice },
126 { "alcCaptureStart", (ALCvoid *) alcCaptureStart },
127 { "alcCaptureStop", (ALCvoid *) alcCaptureStop },
128 { "alcCaptureSamples", (ALCvoid *) alcCaptureSamples },
130 { "alcSetThreadContext", (ALCvoid *) alcSetThreadContext },
131 { "alcGetThreadContext", (ALCvoid *) alcGetThreadContext },
133 { "alcLoopbackOpenDeviceSOFT", (ALCvoid *) alcLoopbackOpenDeviceSOFT},
134 { "alcIsRenderFormatSupportedSOFT",(ALCvoid *) alcIsRenderFormatSupportedSOFT},
135 { "alcRenderSamplesSOFT", (ALCvoid *) alcRenderSamplesSOFT },
137 { "alEnable", (ALCvoid *) alEnable },
138 { "alDisable", (ALCvoid *) alDisable },
139 { "alIsEnabled", (ALCvoid *) alIsEnabled },
140 { "alGetString", (ALCvoid *) alGetString },
141 { "alGetBooleanv", (ALCvoid *) alGetBooleanv },
142 { "alGetIntegerv", (ALCvoid *) alGetIntegerv },
143 { "alGetFloatv", (ALCvoid *) alGetFloatv },
144 { "alGetDoublev", (ALCvoid *) alGetDoublev },
145 { "alGetBoolean", (ALCvoid *) alGetBoolean },
146 { "alGetInteger", (ALCvoid *) alGetInteger },
147 { "alGetFloat", (ALCvoid *) alGetFloat },
148 { "alGetDouble", (ALCvoid *) alGetDouble },
149 { "alGetError", (ALCvoid *) alGetError },
150 { "alIsExtensionPresent", (ALCvoid *) alIsExtensionPresent },
151 { "alGetProcAddress", (ALCvoid *) alGetProcAddress },
152 { "alGetEnumValue", (ALCvoid *) alGetEnumValue },
153 { "alListenerf", (ALCvoid *) alListenerf },
154 { "alListener3f", (ALCvoid *) alListener3f },
155 { "alListenerfv", (ALCvoid *) alListenerfv },
156 { "alListeneri", (ALCvoid *) alListeneri },
157 { "alListener3i", (ALCvoid *) alListener3i },
158 { "alListeneriv", (ALCvoid *) alListeneriv },
159 { "alGetListenerf", (ALCvoid *) alGetListenerf },
160 { "alGetListener3f", (ALCvoid *) alGetListener3f },
161 { "alGetListenerfv", (ALCvoid *) alGetListenerfv },
162 { "alGetListeneri", (ALCvoid *) alGetListeneri },
163 { "alGetListener3i", (ALCvoid *) alGetListener3i },
164 { "alGetListeneriv", (ALCvoid *) alGetListeneriv },
165 { "alGenSources", (ALCvoid *) alGenSources },
166 { "alDeleteSources", (ALCvoid *) alDeleteSources },
167 { "alIsSource", (ALCvoid *) alIsSource },
168 { "alSourcef", (ALCvoid *) alSourcef },
169 { "alSource3f", (ALCvoid *) alSource3f },
170 { "alSourcefv", (ALCvoid *) alSourcefv },
171 { "alSourcei", (ALCvoid *) alSourcei },
172 { "alSource3i", (ALCvoid *) alSource3i },
173 { "alSourceiv", (ALCvoid *) alSourceiv },
174 { "alGetSourcef", (ALCvoid *) alGetSourcef },
175 { "alGetSource3f", (ALCvoid *) alGetSource3f },
176 { "alGetSourcefv", (ALCvoid *) alGetSourcefv },
177 { "alGetSourcei", (ALCvoid *) alGetSourcei },
178 { "alGetSource3i", (ALCvoid *) alGetSource3i },
179 { "alGetSourceiv", (ALCvoid *) alGetSourceiv },
180 { "alSourcePlayv", (ALCvoid *) alSourcePlayv },
181 { "alSourceStopv", (ALCvoid *) alSourceStopv },
182 { "alSourceRewindv", (ALCvoid *) alSourceRewindv },
183 { "alSourcePausev", (ALCvoid *) alSourcePausev },
184 { "alSourcePlay", (ALCvoid *) alSourcePlay },
185 { "alSourceStop", (ALCvoid *) alSourceStop },
186 { "alSourceRewind", (ALCvoid *) alSourceRewind },
187 { "alSourcePause", (ALCvoid *) alSourcePause },
188 { "alSourceQueueBuffers", (ALCvoid *) alSourceQueueBuffers },
189 { "alSourceUnqueueBuffers", (ALCvoid *) alSourceUnqueueBuffers },
190 { "alGenBuffers", (ALCvoid *) alGenBuffers },
191 { "alDeleteBuffers", (ALCvoid *) alDeleteBuffers },
192 { "alIsBuffer", (ALCvoid *) alIsBuffer },
193 { "alBufferData", (ALCvoid *) alBufferData },
194 { "alBufferf", (ALCvoid *) alBufferf },
195 { "alBuffer3f", (ALCvoid *) alBuffer3f },
196 { "alBufferfv", (ALCvoid *) alBufferfv },
197 { "alBufferi", (ALCvoid *) alBufferi },
198 { "alBuffer3i", (ALCvoid *) alBuffer3i },
199 { "alBufferiv", (ALCvoid *) alBufferiv },
200 { "alGetBufferf", (ALCvoid *) alGetBufferf },
201 { "alGetBuffer3f", (ALCvoid *) alGetBuffer3f },
202 { "alGetBufferfv", (ALCvoid *) alGetBufferfv },
203 { "alGetBufferi", (ALCvoid *) alGetBufferi },
204 { "alGetBuffer3i", (ALCvoid *) alGetBuffer3i },
205 { "alGetBufferiv", (ALCvoid *) alGetBufferiv },
206 { "alDopplerFactor", (ALCvoid *) alDopplerFactor },
207 { "alDopplerVelocity", (ALCvoid *) alDopplerVelocity },
208 { "alSpeedOfSound", (ALCvoid *) alSpeedOfSound },
209 { "alDistanceModel", (ALCvoid *) alDistanceModel },
211 { "alGenFilters", (ALCvoid *) alGenFilters },
212 { "alDeleteFilters", (ALCvoid *) alDeleteFilters },
213 { "alIsFilter", (ALCvoid *) alIsFilter },
214 { "alFilteri", (ALCvoid *) alFilteri },
215 { "alFilteriv", (ALCvoid *) alFilteriv },
216 { "alFilterf", (ALCvoid *) alFilterf },
217 { "alFilterfv", (ALCvoid *) alFilterfv },
218 { "alGetFilteri", (ALCvoid *) alGetFilteri },
219 { "alGetFilteriv", (ALCvoid *) alGetFilteriv },
220 { "alGetFilterf", (ALCvoid *) alGetFilterf },
221 { "alGetFilterfv", (ALCvoid *) alGetFilterfv },
222 { "alGenEffects", (ALCvoid *) alGenEffects },
223 { "alDeleteEffects", (ALCvoid *) alDeleteEffects },
224 { "alIsEffect", (ALCvoid *) alIsEffect },
225 { "alEffecti", (ALCvoid *) alEffecti },
226 { "alEffectiv", (ALCvoid *) alEffectiv },
227 { "alEffectf", (ALCvoid *) alEffectf },
228 { "alEffectfv", (ALCvoid *) alEffectfv },
229 { "alGetEffecti", (ALCvoid *) alGetEffecti },
230 { "alGetEffectiv", (ALCvoid *) alGetEffectiv },
231 { "alGetEffectf", (ALCvoid *) alGetEffectf },
232 { "alGetEffectfv", (ALCvoid *) alGetEffectfv },
233 { "alGenAuxiliaryEffectSlots", (ALCvoid *) alGenAuxiliaryEffectSlots},
234 { "alDeleteAuxiliaryEffectSlots",(ALCvoid *) alDeleteAuxiliaryEffectSlots},
235 { "alIsAuxiliaryEffectSlot", (ALCvoid *) alIsAuxiliaryEffectSlot },
236 { "alAuxiliaryEffectSloti", (ALCvoid *) alAuxiliaryEffectSloti },
237 { "alAuxiliaryEffectSlotiv", (ALCvoid *) alAuxiliaryEffectSlotiv },
238 { "alAuxiliaryEffectSlotf", (ALCvoid *) alAuxiliaryEffectSlotf },
239 { "alAuxiliaryEffectSlotfv", (ALCvoid *) alAuxiliaryEffectSlotfv },
240 { "alGetAuxiliaryEffectSloti", (ALCvoid *) alGetAuxiliaryEffectSloti},
241 { "alGetAuxiliaryEffectSlotiv", (ALCvoid *) alGetAuxiliaryEffectSlotiv},
242 { "alGetAuxiliaryEffectSlotf", (ALCvoid *) alGetAuxiliaryEffectSlotf},
243 { "alGetAuxiliaryEffectSlotfv", (ALCvoid *) alGetAuxiliaryEffectSlotfv},
245 { "alBufferSubDataSOFT", (ALCvoid *) alBufferSubDataSOFT },
247 { "alBufferSamplesSOFT", (ALCvoid *) alBufferSamplesSOFT },
248 { "alBufferSubSamplesSOFT", (ALCvoid *) alBufferSubSamplesSOFT },
249 { "alGetBufferSamplesSOFT", (ALCvoid *) alGetBufferSamplesSOFT },
250 { "alIsBufferFormatSupportedSOFT",(ALCvoid *) alIsBufferFormatSupportedSOFT},
252 { "alDeferUpdatesSOFT", (ALCvoid *) alDeferUpdatesSOFT },
253 { "alProcessUpdatesSOFT", (ALCvoid *) alProcessUpdatesSOFT },
255 { NULL, (ALCvoid *) NULL }
258 static const ALCenums enumeration[] = {
259 // Types
260 { "ALC_INVALID", ALC_INVALID },
261 { "ALC_FALSE", ALC_FALSE },
262 { "ALC_TRUE", ALC_TRUE },
264 // ALC Properties
265 { "ALC_MAJOR_VERSION", ALC_MAJOR_VERSION },
266 { "ALC_MINOR_VERSION", ALC_MINOR_VERSION },
267 { "ALC_ATTRIBUTES_SIZE", ALC_ATTRIBUTES_SIZE },
268 { "ALC_ALL_ATTRIBUTES", ALC_ALL_ATTRIBUTES },
269 { "ALC_DEFAULT_DEVICE_SPECIFIER", ALC_DEFAULT_DEVICE_SPECIFIER },
270 { "ALC_DEVICE_SPECIFIER", ALC_DEVICE_SPECIFIER },
271 { "ALC_ALL_DEVICES_SPECIFIER", ALC_ALL_DEVICES_SPECIFIER },
272 { "ALC_DEFAULT_ALL_DEVICES_SPECIFIER", ALC_DEFAULT_ALL_DEVICES_SPECIFIER },
273 { "ALC_EXTENSIONS", ALC_EXTENSIONS },
274 { "ALC_FREQUENCY", ALC_FREQUENCY },
275 { "ALC_REFRESH", ALC_REFRESH },
276 { "ALC_SYNC", ALC_SYNC },
277 { "ALC_MONO_SOURCES", ALC_MONO_SOURCES },
278 { "ALC_STEREO_SOURCES", ALC_STEREO_SOURCES },
279 { "ALC_CAPTURE_DEVICE_SPECIFIER", ALC_CAPTURE_DEVICE_SPECIFIER },
280 { "ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER", ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER},
281 { "ALC_CAPTURE_SAMPLES", ALC_CAPTURE_SAMPLES },
282 { "ALC_CONNECTED", ALC_CONNECTED },
284 // EFX Properties
285 { "ALC_EFX_MAJOR_VERSION", ALC_EFX_MAJOR_VERSION },
286 { "ALC_EFX_MINOR_VERSION", ALC_EFX_MINOR_VERSION },
287 { "ALC_MAX_AUXILIARY_SENDS", ALC_MAX_AUXILIARY_SENDS },
289 // Loopback device Properties
290 { "ALC_FORMAT_CHANNELS_SOFT", ALC_FORMAT_CHANNELS_SOFT },
291 { "ALC_FORMAT_TYPE_SOFT", ALC_FORMAT_TYPE_SOFT },
293 // Buffer Channel Configurations
294 { "ALC_MONO_SOFT", ALC_MONO_SOFT },
295 { "ALC_STEREO_SOFT", ALC_STEREO_SOFT },
296 { "ALC_QUAD_SOFT", ALC_QUAD_SOFT },
297 { "ALC_5POINT1_SOFT", ALC_5POINT1_SOFT },
298 { "ALC_6POINT1_SOFT", ALC_6POINT1_SOFT },
299 { "ALC_7POINT1_SOFT", ALC_7POINT1_SOFT },
301 // Buffer Sample Types
302 { "ALC_BYTE_SOFT", ALC_BYTE_SOFT },
303 { "ALC_UNSIGNED_BYTE_SOFT", ALC_UNSIGNED_BYTE_SOFT },
304 { "ALC_SHORT_SOFT", ALC_SHORT_SOFT },
305 { "ALC_UNSIGNED_SHORT_SOFT", ALC_UNSIGNED_SHORT_SOFT },
306 { "ALC_INT_SOFT", ALC_INT_SOFT },
307 { "ALC_UNSIGNED_INT_SOFT", ALC_UNSIGNED_INT_SOFT },
308 { "ALC_FLOAT_SOFT", ALC_FLOAT_SOFT },
310 // ALC Error Message
311 { "ALC_NO_ERROR", ALC_NO_ERROR },
312 { "ALC_INVALID_DEVICE", ALC_INVALID_DEVICE },
313 { "ALC_INVALID_CONTEXT", ALC_INVALID_CONTEXT },
314 { "ALC_INVALID_ENUM", ALC_INVALID_ENUM },
315 { "ALC_INVALID_VALUE", ALC_INVALID_VALUE },
316 { "ALC_OUT_OF_MEMORY", ALC_OUT_OF_MEMORY },
318 { NULL, (ALCenum)0 }
320 // Error strings
321 static const ALCchar alcNoError[] = "No Error";
322 static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
323 static const ALCchar alcErrInvalidContext[] = "Invalid Context";
324 static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
325 static const ALCchar alcErrInvalidValue[] = "Invalid Value";
326 static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
328 /* Device lists. Sizes only include the first ending null character, not the
329 * second */
330 static ALCchar *alcDeviceList;
331 static size_t alcDeviceListSize;
332 static ALCchar *alcAllDeviceList;
333 static size_t alcAllDeviceListSize;
334 static ALCchar *alcCaptureDeviceList;
335 static size_t alcCaptureDeviceListSize;
336 /* Default is always the first in the list */
337 static ALCchar *alcDefaultDeviceSpecifier;
338 static ALCchar *alcDefaultAllDeviceSpecifier;
339 static ALCchar *alcCaptureDefaultDeviceSpecifier;
342 static const ALCchar alcNoDeviceExtList[] =
343 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
344 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
345 static const ALCchar alcExtensionList[] =
346 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
347 "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
348 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
349 static const ALCint alcMajorVersion = 1;
350 static const ALCint alcMinorVersion = 1;
352 static const ALCint alcEFXMajorVersion = 1;
353 static const ALCint alcEFXMinorVersion = 0;
355 ///////////////////////////////////////////////////////
358 ///////////////////////////////////////////////////////
359 // Global Variables
361 static CRITICAL_SECTION ListLock;
363 /* Device List */
364 static ALCdevice *volatile DeviceList = NULL;
366 // Thread-local current context
367 static pthread_key_t LocalContext;
368 // Process-wide current context
369 static ALCcontext *GlobalContext;
371 /* Device Error */
372 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
374 // Default context extensions
375 static const ALchar alExtList[] =
376 "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 "
377 "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
378 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
379 "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data "
380 "AL_SOFTX_deferred_updates AL_SOFT_loop_points "
381 "AL_SOFTX_non_virtual_channels";
383 // Mixing Priority Level
384 ALint RTPrioLevel;
386 // Output Log File
387 FILE *LogFile;
389 // Output Log Level
390 #ifdef _DEBUG
391 enum LogLevel LogLevel = LogWarning;
392 #else
393 enum LogLevel LogLevel = LogError;
394 #endif
396 /* Flag to trap ALC device errors */
397 static ALCboolean TrapALCError = ALC_FALSE;
399 /* One-time configuration init control */
400 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
402 /* Forced effect that applies to sources that don't have an effect on send 0 */
403 static ALeffect ForcedEffect;
405 ///////////////////////////////////////////////////////
408 ///////////////////////////////////////////////////////
409 // ALC Related helper functions
410 static void ReleaseALC(void);
411 static void ReleaseThreadCtx(void *ptr);
413 static void alc_initconfig(void);
414 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
416 #if defined(_WIN32)
417 static void alc_init(void);
418 static void alc_deinit(void);
419 static void alc_deinit_safe(void);
421 UIntMap TlsDestructor;
423 #ifndef AL_LIBTYPE_STATIC
424 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
426 ALsizei i;
427 (void)hModule;
429 // Perform actions based on the reason for calling.
430 switch(ul_reason_for_call)
432 case DLL_PROCESS_ATTACH:
433 InitUIntMap(&TlsDestructor, ~0);
434 alc_init();
435 break;
437 case DLL_THREAD_DETACH:
438 LockUIntMapRead(&TlsDestructor);
439 for(i = 0;i < TlsDestructor.size;i++)
441 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
442 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
443 if(ptr && callback)
444 callback(ptr);
446 UnlockUIntMapRead(&TlsDestructor);
447 break;
449 case DLL_PROCESS_DETACH:
450 if(!lpReserved)
451 alc_deinit();
452 else
453 alc_deinit_safe();
454 ResetUIntMap(&TlsDestructor);
455 break;
457 return TRUE;
459 #elif defined(_MSC_VER)
460 #pragma section(".CRT$XCU",read)
461 static void alc_constructor(void);
462 static void alc_destructor(void);
463 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
465 static void alc_constructor(void)
467 atexit(alc_destructor);
468 alc_init();
471 static void alc_destructor(void)
473 alc_deinit();
475 #elif defined(HAVE_GCC_DESTRUCTOR)
476 static void alc_init(void) __attribute__((constructor));
477 static void alc_deinit(void) __attribute__((destructor));
478 #else
479 #error "No static initialization available on this platform!"
480 #endif
481 #elif defined(HAVE_GCC_DESTRUCTOR)
482 static void alc_init(void) __attribute__((constructor));
483 static void alc_deinit(void) __attribute__((destructor));
484 #else
485 #error "No global initialization available on this platform!"
486 #endif
488 static void alc_init(void)
490 const char *str;
492 LogFile = stderr;
494 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
495 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
496 ConeScale = 1.0f;
498 str = getenv("__ALSOFT_REVERSE_Z");
499 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
500 ZScale = -1.0f;
502 str = getenv("__ALSOFT_TRAP_ERROR");
503 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
505 TrapALError = AL_TRUE;
506 TrapALCError = AL_TRUE;
508 else
510 str = getenv("__ALSOFT_TRAP_AL_ERROR");
511 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
512 TrapALError = AL_TRUE;
514 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
515 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
516 TrapALCError = ALC_TRUE;
519 pthread_key_create(&LocalContext, ReleaseThreadCtx);
520 InitializeCriticalSection(&ListLock);
521 ThunkInit();
524 static void alc_deinit_safe(void)
526 ReleaseALC();
528 FreeHrtf();
529 FreeALConfig();
531 ThunkExit();
532 DeleteCriticalSection(&ListLock);
533 pthread_key_delete(LocalContext);
535 if(LogFile != stderr)
536 fclose(LogFile);
537 LogFile = NULL;
540 static void alc_deinit(void)
542 int i;
544 ReleaseALC();
546 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
547 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
549 for(i = 0;BackendList[i].Deinit;i++)
550 BackendList[i].Deinit();
551 BackendLoopback.Deinit();
553 alc_deinit_safe();
556 static void alc_initconfig(void)
558 const char *devs, *str;
559 float valf;
560 int i, n;
562 str = getenv("ALSOFT_LOGLEVEL");
563 if(str)
565 long lvl = strtol(str, NULL, 0);
566 if(lvl >= NoLog && lvl <= LogRef)
567 LogLevel = lvl;
570 str = getenv("ALSOFT_LOGFILE");
571 if(str && str[0])
573 FILE *logfile = fopen(str, "wat");
574 if(logfile) LogFile = logfile;
575 else ERR("Failed to open log file '%s'\n", str);
578 ReadALConfig();
580 InitHrtf();
582 #ifdef _WIN32
583 RTPrioLevel = 1;
584 #else
585 RTPrioLevel = 0;
586 #endif
587 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
589 if(ConfigValueStr(NULL, "resampler", &str))
591 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
592 DefaultResampler = POINT_RESAMPLER;
593 else if(strcasecmp(str, "linear") == 0)
594 DefaultResampler = LINEAR_RESAMPLER;
595 else if(strcasecmp(str, "cubic") == 0)
596 DefaultResampler = CUBIC_RESAMPLER;
597 else
599 char *end;
601 n = strtol(str, &end, 0);
602 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
603 DefaultResampler = n;
604 else
605 WARN("Invalid resampler: %s\n", str);
609 if(!TrapALCError)
610 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
612 if(!TrapALError)
613 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
615 if(ConfigValueFloat("reverb", "boost", &valf))
616 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
618 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
620 if(ConfigValueStr(NULL, "drivers", &devs))
622 int n;
623 size_t len;
624 const char *next = devs;
625 int endlist, delitem;
627 i = 0;
628 do {
629 devs = next;
630 next = strchr(devs, ',');
632 delitem = (devs[0] == '-');
633 if(devs[0] == '-') devs++;
635 if(!devs[0] || devs[0] == ',')
637 endlist = 0;
638 continue;
640 endlist = 1;
642 len = (next ? ((size_t)(next-devs)) : strlen(devs));
643 for(n = i;BackendList[n].Init;n++)
645 if(len == strlen(BackendList[n].name) &&
646 strncmp(BackendList[n].name, devs, len) == 0)
648 if(delitem)
650 do {
651 BackendList[n] = BackendList[n+1];
652 ++n;
653 } while(BackendList[n].Init);
655 else
657 struct BackendInfo Bkp = BackendList[n];
658 while(n > i)
660 BackendList[n] = BackendList[n-1];
661 --n;
663 BackendList[n] = Bkp;
665 i++;
667 break;
670 } while(next++);
672 if(endlist)
674 BackendList[i].name = NULL;
675 BackendList[i].Init = NULL;
676 BackendList[i].Deinit = NULL;
677 BackendList[i].Probe = NULL;
681 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
683 if(!BackendList[i].Init(&BackendList[i].Funcs))
685 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
686 continue;
689 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
690 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
692 PlaybackBackend = BackendList[i];
693 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
695 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
697 CaptureBackend = BackendList[i];
698 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
701 BackendLoopback.Init(&BackendLoopback.Funcs);
703 if(ConfigValueStr(NULL, "excludefx", &str))
705 size_t len;
706 const char *next = str;
708 do {
709 str = next;
710 next = strchr(str, ',');
712 if(!str[0] || next == str)
713 continue;
715 len = (next ? ((size_t)(next-str)) : strlen(str));
716 for(n = 0;EffectList[n].name;n++)
718 if(len == strlen(EffectList[n].name) &&
719 strncmp(EffectList[n].name, str, len) == 0)
720 DisabledEffects[EffectList[n].type] = AL_TRUE;
722 } while(next++);
725 InitEffect(&ForcedEffect);
726 str = getenv("__ALSOFT_DEFAULT_REVERB");
727 if(str && str[0])
728 GetReverbEffect(str, &ForcedEffect);
729 else if(ConfigValueStr(NULL, "default-reverb", &str))
730 GetReverbEffect(str, &ForcedEffect);
734 static void LockLists(void)
736 EnterCriticalSection(&ListLock);
739 static void UnlockLists(void)
741 LeaveCriticalSection(&ListLock);
745 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
747 DO_INITCONFIG();
749 LockLists();
750 free(*list);
751 *list = NULL;
752 *listsize = 0;
754 if(type == CAPTURE_DEVICE_PROBE)
755 CaptureBackend.Probe(type);
756 else
757 PlaybackBackend.Probe(type);
758 UnlockLists();
761 static void ProbeDeviceList(void)
762 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
763 static void ProbeAllDeviceList(void)
764 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
765 static void ProbeCaptureDeviceList(void)
766 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
769 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
771 size_t len = strlen(name);
772 void *temp;
774 if(len == 0)
775 return;
777 temp = realloc(*List, (*ListSize) + len + 2);
778 if(!temp)
780 ERR("Realloc failed to add %s!\n", name);
781 return;
783 *List = temp;
785 memcpy((*List)+(*ListSize), name, len+1);
786 *ListSize += len+1;
787 (*List)[*ListSize] = 0;
790 #define DECL_APPEND_LIST_FUNC(type) \
791 void Append##type##List(const ALCchar *name) \
792 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
794 DECL_APPEND_LIST_FUNC(Device)
795 DECL_APPEND_LIST_FUNC(AllDevice)
796 DECL_APPEND_LIST_FUNC(CaptureDevice)
798 #undef DECL_APPEND_LIST_FUNC
801 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
802 void SetDefaultChannelOrder(ALCdevice *device)
804 switch(device->FmtChans)
806 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
807 device->DevChannels[1] = FRONT_RIGHT;
808 device->DevChannels[2] = BACK_LEFT;
809 device->DevChannels[3] = BACK_RIGHT;
810 device->DevChannels[4] = FRONT_CENTER;
811 device->DevChannels[5] = LFE;
812 return;
814 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
815 device->DevChannels[1] = FRONT_RIGHT;
816 device->DevChannels[2] = BACK_LEFT;
817 device->DevChannels[3] = BACK_RIGHT;
818 device->DevChannels[4] = FRONT_CENTER;
819 device->DevChannels[5] = LFE;
820 device->DevChannels[6] = SIDE_LEFT;
821 device->DevChannels[7] = SIDE_RIGHT;
822 return;
824 /* Same as WFX order */
825 case DevFmtMono:
826 case DevFmtStereo:
827 case DevFmtQuad:
828 case DevFmtX51Side:
829 case DevFmtX61:
830 break;
832 SetDefaultWFXChannelOrder(device);
834 /* Sets the default order used by WaveFormatEx */
835 void SetDefaultWFXChannelOrder(ALCdevice *device)
837 switch(device->FmtChans)
839 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
841 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
842 device->DevChannels[1] = FRONT_RIGHT; break;
844 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
845 device->DevChannels[1] = FRONT_RIGHT;
846 device->DevChannels[2] = BACK_LEFT;
847 device->DevChannels[3] = BACK_RIGHT; break;
849 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
850 device->DevChannels[1] = FRONT_RIGHT;
851 device->DevChannels[2] = FRONT_CENTER;
852 device->DevChannels[3] = LFE;
853 device->DevChannels[4] = BACK_LEFT;
854 device->DevChannels[5] = BACK_RIGHT; break;
856 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
857 device->DevChannels[1] = FRONT_RIGHT;
858 device->DevChannels[2] = FRONT_CENTER;
859 device->DevChannels[3] = LFE;
860 device->DevChannels[4] = SIDE_LEFT;
861 device->DevChannels[5] = SIDE_RIGHT; break;
863 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
864 device->DevChannels[1] = FRONT_RIGHT;
865 device->DevChannels[2] = FRONT_CENTER;
866 device->DevChannels[3] = LFE;
867 device->DevChannels[4] = BACK_CENTER;
868 device->DevChannels[5] = SIDE_LEFT;
869 device->DevChannels[6] = SIDE_RIGHT; break;
871 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
872 device->DevChannels[1] = FRONT_RIGHT;
873 device->DevChannels[2] = FRONT_CENTER;
874 device->DevChannels[3] = LFE;
875 device->DevChannels[4] = BACK_LEFT;
876 device->DevChannels[5] = BACK_RIGHT;
877 device->DevChannels[6] = SIDE_LEFT;
878 device->DevChannels[7] = SIDE_RIGHT; break;
883 const ALCchar *DevFmtTypeString(enum DevFmtType type)
885 switch(type)
887 case DevFmtByte: return "Signed Byte";
888 case DevFmtUByte: return "Unsigned Byte";
889 case DevFmtShort: return "Signed Short";
890 case DevFmtUShort: return "Unsigned Short";
891 case DevFmtFloat: return "Float";
893 return "(unknown type)";
895 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
897 switch(chans)
899 case DevFmtMono: return "Mono";
900 case DevFmtStereo: return "Stereo";
901 case DevFmtQuad: return "Quadraphonic";
902 case DevFmtX51: return "5.1 Surround";
903 case DevFmtX51Side: return "5.1 Side";
904 case DevFmtX61: return "6.1 Surround";
905 case DevFmtX71: return "7.1 Surround";
907 return "(unknown channels)";
910 ALuint BytesFromDevFmt(enum DevFmtType type)
912 switch(type)
914 case DevFmtByte: return sizeof(ALbyte);
915 case DevFmtUByte: return sizeof(ALubyte);
916 case DevFmtShort: return sizeof(ALshort);
917 case DevFmtUShort: return sizeof(ALushort);
918 case DevFmtFloat: return sizeof(ALfloat);
920 return 0;
922 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
924 switch(chans)
926 case DevFmtMono: return 1;
927 case DevFmtStereo: return 2;
928 case DevFmtQuad: return 4;
929 case DevFmtX51: return 6;
930 case DevFmtX51Side: return 6;
931 case DevFmtX61: return 7;
932 case DevFmtX71: return 8;
934 return 0;
936 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
937 enum DevFmtType *type)
939 static const struct {
940 ALenum format;
941 enum DevFmtChannels channels;
942 enum DevFmtType type;
943 } list[] = {
944 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
945 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
946 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
948 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
949 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
950 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
952 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
953 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
954 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
956 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
957 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
958 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
960 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
961 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
962 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
964 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
965 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
966 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
968 ALuint i;
970 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
972 if(list[i].format == format)
974 *chans = list[i].channels;
975 *type = list[i].type;
976 return AL_TRUE;
980 return AL_FALSE;
983 static ALCboolean IsValidALCType(ALCenum type)
985 switch(type)
987 case ALC_BYTE_SOFT:
988 case ALC_UNSIGNED_BYTE_SOFT:
989 case ALC_SHORT_SOFT:
990 case ALC_UNSIGNED_SHORT_SOFT:
991 case ALC_INT_SOFT:
992 case ALC_UNSIGNED_INT_SOFT:
993 case ALC_FLOAT_SOFT:
994 return ALC_TRUE;
996 return ALC_FALSE;
999 static ALCboolean IsValidALCChannels(ALCenum channels)
1001 switch(channels)
1003 case ALC_MONO_SOFT:
1004 case ALC_STEREO_SOFT:
1005 case ALC_QUAD_SOFT:
1006 case ALC_5POINT1_SOFT:
1007 case ALC_6POINT1_SOFT:
1008 case ALC_7POINT1_SOFT:
1009 return ALC_TRUE;
1011 return ALC_FALSE;
1015 /* alcSetError
1017 * Stores the latest ALC Error
1019 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1021 if(TrapALCError)
1023 #ifdef _WIN32
1024 /* DebugBreak() will cause an exception if there is no debugger */
1025 if(IsDebuggerPresent())
1026 DebugBreak();
1027 #elif defined(SIGTRAP)
1028 raise(SIGTRAP);
1029 #endif
1032 if(device)
1033 device->LastError = errorCode;
1034 else
1035 g_eLastNullDeviceError = errorCode;
1039 /* UpdateDeviceParams
1041 * Updates device parameters according to the attribute list (caller is
1042 * responsible for holding the list lock).
1044 static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1046 ALCcontext *context;
1047 enum DevFmtChannels oldChans;
1048 enum DevFmtType oldType;
1049 ALCuint oldFreq;
1050 int oldMode;
1051 ALuint i;
1053 if(device->IsLoopbackDevice && !(attrList && attrList[0]))
1055 WARN("Missing attributes for loopback device\n");
1056 return ALC_INVALID_VALUE;
1059 // Check for attributes
1060 if(attrList && attrList[0])
1062 enum {
1063 GotFreq = 1<<0,
1064 GotChans = 1<<1,
1065 GotType = 1<<2,
1066 GotAll = GotFreq|GotChans|GotType
1068 ALCuint freq, numMono, numStereo, numSends;
1069 enum DevFmtChannels schans;
1070 enum DevFmtType stype;
1071 ALCuint attrIdx = 0;
1072 ALCint gotFmt = 0;
1074 // If a context is already running on the device, stop playback so the
1075 // device attributes can be updated
1076 if((device->Flags&DEVICE_RUNNING))
1077 ALCdevice_StopPlayback(device);
1078 device->Flags &= ~DEVICE_RUNNING;
1080 freq = device->Frequency;
1081 schans = device->FmtChans;
1082 stype = device->FmtType;
1083 numMono = device->NumMonoSources;
1084 numStereo = device->NumStereoSources;
1085 numSends = device->NumAuxSends;
1087 while(attrList[attrIdx])
1089 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1090 device->IsLoopbackDevice)
1092 ALCint val = attrList[attrIdx + 1];
1093 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1094 return ALC_INVALID_VALUE;
1095 schans = val;
1096 gotFmt |= GotChans;
1099 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1100 device->IsLoopbackDevice)
1102 ALCint val = attrList[attrIdx + 1];
1103 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1104 return ALC_INVALID_VALUE;
1105 stype = val;
1106 gotFmt |= GotType;
1109 if(attrList[attrIdx] == ALC_FREQUENCY)
1111 if(device->IsLoopbackDevice)
1113 freq = attrList[attrIdx + 1];
1114 if(freq < 8000)
1115 return ALC_INVALID_VALUE;
1116 gotFmt |= GotFreq;
1118 else
1120 freq = attrList[attrIdx + 1];
1121 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1125 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1127 numStereo = attrList[attrIdx + 1];
1128 if(numStereo > device->MaxNoOfSources)
1129 numStereo = device->MaxNoOfSources;
1131 numMono = device->MaxNoOfSources - numStereo;
1134 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1135 numSends = attrList[attrIdx + 1];
1137 attrIdx += 2;
1140 if(device->IsLoopbackDevice)
1142 if(gotFmt != GotAll)
1144 WARN("Missing format for loopback device\n");
1145 return ALC_INVALID_VALUE;
1148 else
1150 ConfigValueUInt(NULL, "frequency", &freq);
1151 freq = maxu(freq, 8000);
1153 ConfigValueUInt(NULL, "sends", &numSends);
1154 numSends = minu(MAX_SENDS, numSends);
1156 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1157 device->Frequency;
1159 device->Frequency = freq;
1160 device->FmtChans = schans;
1161 device->FmtType = stype;
1162 device->NumMonoSources = numMono;
1163 device->NumStereoSources = numStereo;
1164 device->NumAuxSends = numSends;
1167 if((device->Flags&DEVICE_RUNNING))
1168 return ALC_NO_ERROR;
1170 LockDevice(device);
1172 oldFreq = device->Frequency;
1173 oldChans = device->FmtChans;
1174 oldType = device->FmtType;
1176 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1177 DevFmtChannelsString(device->FmtChans),
1178 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1179 DevFmtTypeString(device->FmtType), device->Frequency,
1180 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1181 device->UpdateSize, device->NumUpdates);
1182 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1184 UnlockDevice(device);
1185 return ALC_INVALID_DEVICE;
1187 device->Flags |= DEVICE_RUNNING;
1189 if(device->FmtChans != oldChans)
1191 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1192 ERR("Failed to set %s, got %s instead\n",
1193 DevFmtChannelsString(oldChans),
1194 DevFmtChannelsString(device->FmtChans));
1195 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1197 if(device->Frequency != oldFreq)
1199 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1200 ERR("Failed to set %uhz, got %uhz instead\n",
1201 oldFreq, device->Frequency);
1202 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1205 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1206 DevFmtChannelsString(device->FmtChans),
1207 DevFmtTypeString(device->FmtType), device->Frequency,
1208 device->UpdateSize, device->NumUpdates);
1210 aluInitPanning(device);
1212 for(i = 0;i < MAXCHANNELS;i++)
1214 device->ClickRemoval[i] = 0.0f;
1215 device->PendingClicks[i] = 0.0f;
1218 device->Hrtf = NULL;
1219 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1220 device->Hrtf = GetHrtf(device);
1221 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1223 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1225 if(!device->Bs2b)
1227 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1228 bs2b_clear(device->Bs2b);
1230 bs2b_set_srate(device->Bs2b, device->Frequency);
1231 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1232 TRACE("BS2B level %d\n", device->Bs2bLevel);
1234 else
1236 free(device->Bs2b);
1237 device->Bs2b = NULL;
1238 TRACE("BS2B disabled\n");
1241 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1242 switch(device->FmtChans)
1244 case DevFmtMono:
1245 case DevFmtStereo:
1246 break;
1247 case DevFmtQuad:
1248 case DevFmtX51:
1249 case DevFmtX51Side:
1250 case DevFmtX61:
1251 case DevFmtX71:
1252 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1253 device->Flags |= DEVICE_DUPLICATE_STEREO;
1254 break;
1256 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1258 oldMode = SetMixerFPUMode();
1259 context = device->ContextList;
1260 while(context)
1262 ALsizei pos;
1264 context->UpdateSources = AL_FALSE;
1265 LockUIntMapRead(&context->EffectSlotMap);
1266 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1268 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1270 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1272 UnlockUIntMapRead(&context->EffectSlotMap);
1273 RestoreFPUMode(oldMode);
1274 UnlockDevice(device);
1275 ALCdevice_StopPlayback(device);
1276 device->Flags &= ~DEVICE_RUNNING;
1277 return ALC_INVALID_DEVICE;
1279 slot->NeedsUpdate = AL_FALSE;
1280 ALeffectState_Update(slot->EffectState, context, slot);
1282 UnlockUIntMapRead(&context->EffectSlotMap);
1284 LockUIntMapRead(&context->SourceMap);
1285 for(pos = 0;pos < context->SourceMap.size;pos++)
1287 ALsource *source = context->SourceMap.array[pos].value;
1288 ALuint s = device->NumAuxSends;
1289 while(s < MAX_SENDS)
1291 if(source->Send[s].Slot)
1292 DecrementRef(&source->Send[s].Slot->ref);
1293 source->Send[s].Slot = NULL;
1294 source->Send[s].WetGain = 1.0f;
1295 source->Send[s].WetGainHF = 1.0f;
1296 s++;
1298 source->NeedsUpdate = AL_FALSE;
1299 ALsource_Update(source, context);
1301 UnlockUIntMapRead(&context->SourceMap);
1303 context = context->next;
1305 RestoreFPUMode(oldMode);
1306 UnlockDevice(device);
1308 return ALC_NO_ERROR;
1311 /* FreeDevice
1313 * Frees the device structure, and destroys any objects the app failed to
1314 * delete. Called once there's no more references on the device.
1316 static ALCvoid FreeDevice(ALCdevice *device)
1318 TRACE("%p\n", device);
1320 if(device->DefaultSlot)
1322 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1323 device->DefaultSlot->EffectState = NULL;
1326 if(device->BufferMap.size > 0)
1328 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1329 ReleaseALBuffers(device);
1331 ResetUIntMap(&device->BufferMap);
1333 if(device->EffectMap.size > 0)
1335 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1336 ReleaseALEffects(device);
1338 ResetUIntMap(&device->EffectMap);
1340 if(device->FilterMap.size > 0)
1342 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1343 ReleaseALFilters(device);
1345 ResetUIntMap(&device->FilterMap);
1347 free(device->Bs2b);
1348 device->Bs2b = NULL;
1350 free(device->szDeviceName);
1351 device->szDeviceName = NULL;
1353 DeleteCriticalSection(&device->Mutex);
1355 free(device);
1359 void ALCdevice_IncRef(ALCdevice *device)
1361 RefCount ref;
1362 ref = IncrementRef(&device->ref);
1363 TRACEREF("%p increasing refcount to %u\n", device, ref);
1366 void ALCdevice_DecRef(ALCdevice *device)
1368 RefCount ref;
1369 ref = DecrementRef(&device->ref);
1370 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1371 if(ref == 0) FreeDevice(device);
1374 /* VerifyDevice
1376 * Checks if the device handle is valid, and increments its ref count if so.
1378 static ALCdevice *VerifyDevice(ALCdevice *device)
1380 ALCdevice *tmpDevice;
1382 if(!device)
1383 return NULL;
1385 LockLists();
1386 tmpDevice = DeviceList;
1387 while(tmpDevice && tmpDevice != device)
1388 tmpDevice = tmpDevice->next;
1390 if(tmpDevice)
1391 ALCdevice_IncRef(tmpDevice);
1392 UnlockLists();
1393 return tmpDevice;
1397 /* InitContext
1399 * Initializes context variables
1401 static ALvoid InitContext(ALCcontext *pContext)
1403 ALint i, j;
1405 //Initialise listener
1406 pContext->Listener.Gain = 1.0f;
1407 pContext->Listener.MetersPerUnit = 1.0f;
1408 pContext->Listener.Position[0] = 0.0f;
1409 pContext->Listener.Position[1] = 0.0f;
1410 pContext->Listener.Position[2] = 0.0f;
1411 pContext->Listener.Velocity[0] = 0.0f;
1412 pContext->Listener.Velocity[1] = 0.0f;
1413 pContext->Listener.Velocity[2] = 0.0f;
1414 pContext->Listener.Forward[0] = 0.0f;
1415 pContext->Listener.Forward[1] = 0.0f;
1416 pContext->Listener.Forward[2] = -1.0f;
1417 pContext->Listener.Up[0] = 0.0f;
1418 pContext->Listener.Up[1] = 1.0f;
1419 pContext->Listener.Up[2] = 0.0f;
1420 for(i = 0;i < 4;i++)
1422 for(j = 0;j < 4;j++)
1423 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1426 //Validate pContext
1427 pContext->LastError = AL_NO_ERROR;
1428 pContext->UpdateSources = AL_FALSE;
1429 pContext->ActiveSourceCount = 0;
1430 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1431 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1433 //Set globals
1434 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1435 pContext->SourceDistanceModel = AL_FALSE;
1436 pContext->DopplerFactor = 1.0f;
1437 pContext->DopplerVelocity = 1.0f;
1438 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1439 pContext->DeferUpdates = AL_FALSE;
1441 pContext->ExtensionList = alExtList;
1445 /* FreeContext
1447 * Cleans up the context, and destroys any remaining objects the app failed to
1448 * delete. Called once there's no more references on the context.
1450 static ALCvoid FreeContext(ALCcontext *context)
1452 TRACE("%p\n", context);
1454 if(context->SourceMap.size > 0)
1456 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1457 ReleaseALSources(context);
1459 ResetUIntMap(&context->SourceMap);
1461 if(context->EffectSlotMap.size > 0)
1463 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1464 ReleaseALAuxiliaryEffectSlots(context);
1466 ResetUIntMap(&context->EffectSlotMap);
1468 context->ActiveSourceCount = 0;
1469 free(context->ActiveSources);
1470 context->ActiveSources = NULL;
1471 context->MaxActiveSources = 0;
1473 context->ActiveEffectSlotCount = 0;
1474 free(context->ActiveEffectSlots);
1475 context->ActiveEffectSlots = NULL;
1476 context->MaxActiveEffectSlots = 0;
1478 ALCdevice_DecRef(context->Device);
1479 context->Device = NULL;
1481 //Invalidate context
1482 memset(context, 0, sizeof(ALCcontext));
1483 free(context);
1486 /* ReleaseContext
1488 * Removes the context reference from the given device and removes it from
1489 * being current on the running thread or globally.
1491 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1493 ALCcontext *volatile*tmp_ctx;
1495 if(pthread_getspecific(LocalContext) == context)
1497 WARN("%p released while current on thread\n", context);
1498 pthread_setspecific(LocalContext, NULL);
1499 ALCcontext_DecRef(context);
1502 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1503 ALCcontext_DecRef(context);
1505 LockDevice(device);
1506 tmp_ctx = &device->ContextList;
1507 while(*tmp_ctx)
1509 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1510 break;
1511 tmp_ctx = &(*tmp_ctx)->next;
1513 UnlockDevice(device);
1515 ALCcontext_DecRef(context);
1518 void ALCcontext_IncRef(ALCcontext *context)
1520 RefCount ref;
1521 ref = IncrementRef(&context->ref);
1522 TRACEREF("%p increasing refcount to %u\n", context, ref);
1525 void ALCcontext_DecRef(ALCcontext *context)
1527 RefCount ref;
1528 ref = DecrementRef(&context->ref);
1529 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1530 if(ref == 0) FreeContext(context);
1533 static void ReleaseThreadCtx(void *ptr)
1535 WARN("%p current for thread being destroyed\n", ptr);
1536 ALCcontext_DecRef(ptr);
1539 /* VerifyContext
1541 * Checks that the given context is valid, and increments its reference count.
1543 static ALCcontext *VerifyContext(ALCcontext *context)
1545 ALCdevice *dev;
1547 LockLists();
1548 dev = DeviceList;
1549 while(dev)
1551 ALCcontext *tmp_ctx = dev->ContextList;
1552 while(tmp_ctx)
1554 if(tmp_ctx == context)
1556 ALCcontext_IncRef(tmp_ctx);
1557 UnlockLists();
1558 return tmp_ctx;
1560 tmp_ctx = tmp_ctx->next;
1562 dev = dev->next;
1564 UnlockLists();
1566 return NULL;
1570 /* GetContextRef
1572 * Returns the currently active context, and adds a reference without locking
1573 * it.
1575 ALCcontext *GetContextRef(void)
1577 ALCcontext *context;
1579 context = pthread_getspecific(LocalContext);
1580 if(context)
1581 ALCcontext_IncRef(context);
1582 else
1584 LockLists();
1585 context = GlobalContext;
1586 if(context)
1587 ALCcontext_IncRef(context);
1588 UnlockLists();
1591 return context;
1594 ///////////////////////////////////////////////////////
1597 ///////////////////////////////////////////////////////
1598 // ALC Functions calls
1601 // This should probably move to another c file but for now ...
1602 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1604 ALCdevice *device = NULL;
1605 ALCenum err;
1607 DO_INITCONFIG();
1609 if(!CaptureBackend.name)
1611 alcSetError(NULL, ALC_INVALID_VALUE);
1612 return NULL;
1615 if(SampleSize <= 0)
1617 alcSetError(NULL, ALC_INVALID_VALUE);
1618 return NULL;
1621 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1622 deviceName = NULL;
1624 device = calloc(1, sizeof(ALCdevice));
1625 if(!device)
1627 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1628 return NULL;
1631 //Validate device
1632 device->Funcs = &CaptureBackend.Funcs;
1633 device->ref = 1;
1634 device->Connected = ALC_TRUE;
1635 device->IsCaptureDevice = AL_TRUE;
1636 device->IsLoopbackDevice = AL_FALSE;
1637 InitializeCriticalSection(&device->Mutex);
1639 InitUIntMap(&device->BufferMap, ~0);
1640 InitUIntMap(&device->EffectMap, ~0);
1641 InitUIntMap(&device->FilterMap, ~0);
1643 device->szDeviceName = NULL;
1645 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1646 device->Frequency = frequency;
1648 device->Flags |= DEVICE_CHANNELS_REQUEST;
1649 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1651 DeleteCriticalSection(&device->Mutex);
1652 free(device);
1653 alcSetError(NULL, ALC_INVALID_ENUM);
1654 return NULL;
1657 device->UpdateSize = SampleSize;
1658 device->NumUpdates = 1;
1660 LockLists();
1661 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1663 UnlockLists();
1664 DeleteCriticalSection(&device->Mutex);
1665 free(device);
1666 alcSetError(NULL, err);
1667 return NULL;
1669 UnlockLists();
1671 do {
1672 device->next = DeviceList;
1673 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1675 TRACE("Created device %p\n", device);
1676 return device;
1679 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1681 ALCdevice *volatile*list;
1683 LockLists();
1684 list = &DeviceList;
1685 while(*list && *list != pDevice)
1686 list = &(*list)->next;
1688 if(!*list || !(*list)->IsCaptureDevice)
1690 alcSetError(*list, ALC_INVALID_DEVICE);
1691 UnlockLists();
1692 return ALC_FALSE;
1695 *list = (*list)->next;
1696 UnlockLists();
1698 LockDevice(pDevice);
1699 ALCdevice_CloseCapture(pDevice);
1700 UnlockDevice(pDevice);
1702 ALCdevice_DecRef(pDevice);
1704 return ALC_TRUE;
1707 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1709 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1711 alcSetError(device, ALC_INVALID_DEVICE);
1712 if(device) ALCdevice_DecRef(device);
1713 return;
1715 LockDevice(device);
1716 if(device->Connected)
1717 ALCdevice_StartCapture(device);
1718 UnlockDevice(device);
1720 ALCdevice_DecRef(device);
1723 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1725 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1727 alcSetError(device, ALC_INVALID_DEVICE);
1728 if(device) ALCdevice_DecRef(device);
1729 return;
1731 LockDevice(device);
1732 if(device->Connected)
1733 ALCdevice_StopCapture(device);
1734 UnlockDevice(device);
1736 ALCdevice_DecRef(device);
1739 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1741 ALCenum err = ALC_INVALID_DEVICE;
1742 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1744 err = ALC_INVALID_VALUE;
1745 LockDevice(device);
1746 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1747 err = ALCdevice_CaptureSamples(device, buffer, samples);
1748 UnlockDevice(device);
1750 if(err != ALC_NO_ERROR)
1751 alcSetError(device, err);
1752 if(device) ALCdevice_DecRef(device);
1756 alcGetError
1758 Return last ALC generated error code
1760 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1762 ALCenum errorCode;
1764 if(VerifyDevice(device))
1766 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1767 ALCdevice_DecRef(device);
1769 else
1770 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1772 return errorCode;
1776 /* alcSuspendContext
1778 * Not functional
1780 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1782 (void)Context;
1785 /* alcProcessContext
1787 * Not functional
1789 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1791 (void)Context;
1795 /* alcGetString
1797 * Returns information about the Device, and error strings
1799 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1801 const ALCchar *value = NULL;
1803 switch(param)
1805 case ALC_NO_ERROR:
1806 value = alcNoError;
1807 break;
1809 case ALC_INVALID_ENUM:
1810 value = alcErrInvalidEnum;
1811 break;
1813 case ALC_INVALID_VALUE:
1814 value = alcErrInvalidValue;
1815 break;
1817 case ALC_INVALID_DEVICE:
1818 value = alcErrInvalidDevice;
1819 break;
1821 case ALC_INVALID_CONTEXT:
1822 value = alcErrInvalidContext;
1823 break;
1825 case ALC_OUT_OF_MEMORY:
1826 value = alcErrOutOfMemory;
1827 break;
1829 case ALC_DEVICE_SPECIFIER:
1830 if(VerifyDevice(pDevice))
1832 value = pDevice->szDeviceName;
1833 ALCdevice_DecRef(pDevice);
1835 else
1837 ProbeDeviceList();
1838 value = alcDeviceList;
1840 break;
1842 case ALC_ALL_DEVICES_SPECIFIER:
1843 ProbeAllDeviceList();
1844 value = alcAllDeviceList;
1845 break;
1847 case ALC_CAPTURE_DEVICE_SPECIFIER:
1848 if(VerifyDevice(pDevice))
1850 value = pDevice->szDeviceName;
1851 ALCdevice_DecRef(pDevice);
1853 else
1855 ProbeCaptureDeviceList();
1856 value = alcCaptureDeviceList;
1858 break;
1860 /* Default devices are always first in the list */
1861 case ALC_DEFAULT_DEVICE_SPECIFIER:
1862 if(!alcDeviceList)
1863 ProbeDeviceList();
1865 pDevice = VerifyDevice(pDevice);
1867 free(alcDefaultDeviceSpecifier);
1868 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1869 if(!alcDefaultDeviceSpecifier)
1870 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1872 value = alcDefaultDeviceSpecifier;
1873 if(pDevice) ALCdevice_DecRef(pDevice);
1874 break;
1876 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1877 if(!alcAllDeviceList)
1878 ProbeAllDeviceList();
1880 pDevice = VerifyDevice(pDevice);
1882 free(alcDefaultAllDeviceSpecifier);
1883 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1884 alcAllDeviceList : "");
1885 if(!alcDefaultAllDeviceSpecifier)
1886 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1888 value = alcDefaultAllDeviceSpecifier;
1889 if(pDevice) ALCdevice_DecRef(pDevice);
1890 break;
1892 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1893 if(!alcCaptureDeviceList)
1894 ProbeCaptureDeviceList();
1896 pDevice = VerifyDevice(pDevice);
1898 free(alcCaptureDefaultDeviceSpecifier);
1899 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1900 alcCaptureDeviceList : "");
1901 if(!alcCaptureDefaultDeviceSpecifier)
1902 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1904 value = alcCaptureDefaultDeviceSpecifier;
1905 if(pDevice) ALCdevice_DecRef(pDevice);
1906 break;
1908 case ALC_EXTENSIONS:
1909 if(!VerifyDevice(pDevice))
1910 value = alcNoDeviceExtList;
1911 else
1913 value = alcExtensionList;
1914 ALCdevice_DecRef(pDevice);
1916 break;
1918 default:
1919 pDevice = VerifyDevice(pDevice);
1920 alcSetError(pDevice, ALC_INVALID_ENUM);
1921 if(pDevice) ALCdevice_DecRef(pDevice);
1922 break;
1925 return value;
1929 /* alcGetIntegerv
1931 * Returns information about the Device and the version of Open AL
1933 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1935 device = VerifyDevice(device);
1937 if(size == 0 || data == NULL)
1939 alcSetError(device, ALC_INVALID_VALUE);
1940 if(device) ALCdevice_DecRef(device);
1941 return;
1944 if(!device)
1946 switch(param)
1948 case ALC_MAJOR_VERSION:
1949 *data = alcMajorVersion;
1950 break;
1951 case ALC_MINOR_VERSION:
1952 *data = alcMinorVersion;
1953 break;
1955 case ALC_ATTRIBUTES_SIZE:
1956 case ALC_ALL_ATTRIBUTES:
1957 case ALC_FREQUENCY:
1958 case ALC_REFRESH:
1959 case ALC_SYNC:
1960 case ALC_MONO_SOURCES:
1961 case ALC_STEREO_SOURCES:
1962 case ALC_CAPTURE_SAMPLES:
1963 case ALC_FORMAT_CHANNELS_SOFT:
1964 case ALC_FORMAT_TYPE_SOFT:
1965 alcSetError(NULL, ALC_INVALID_DEVICE);
1966 break;
1968 default:
1969 alcSetError(NULL, ALC_INVALID_ENUM);
1970 break;
1973 else if(device->IsCaptureDevice)
1975 switch(param)
1977 case ALC_CAPTURE_SAMPLES:
1978 LockDevice(device);
1979 *data = ALCdevice_AvailableSamples(device);
1980 UnlockDevice(device);
1981 break;
1983 case ALC_CONNECTED:
1984 *data = device->Connected;
1985 break;
1987 default:
1988 alcSetError(device, ALC_INVALID_ENUM);
1989 break;
1992 else /* render device */
1994 switch(param)
1996 case ALC_MAJOR_VERSION:
1997 *data = alcMajorVersion;
1998 break;
2000 case ALC_MINOR_VERSION:
2001 *data = alcMinorVersion;
2002 break;
2004 case ALC_EFX_MAJOR_VERSION:
2005 *data = alcEFXMajorVersion;
2006 break;
2008 case ALC_EFX_MINOR_VERSION:
2009 *data = alcEFXMinorVersion;
2010 break;
2012 case ALC_ATTRIBUTES_SIZE:
2013 *data = 13;
2014 break;
2016 case ALC_ALL_ATTRIBUTES:
2017 if(size < 13)
2018 alcSetError(device, ALC_INVALID_VALUE);
2019 else
2021 int i = 0;
2023 data[i++] = ALC_FREQUENCY;
2024 data[i++] = device->Frequency;
2026 if(!device->IsLoopbackDevice)
2028 data[i++] = ALC_REFRESH;
2029 data[i++] = device->Frequency / device->UpdateSize;
2031 data[i++] = ALC_SYNC;
2032 data[i++] = ALC_FALSE;
2034 else
2036 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2037 data[i++] = device->FmtChans;
2039 data[i++] = ALC_FORMAT_TYPE_SOFT;
2040 data[i++] = device->FmtType;
2043 data[i++] = ALC_MONO_SOURCES;
2044 data[i++] = device->NumMonoSources;
2046 data[i++] = ALC_STEREO_SOURCES;
2047 data[i++] = device->NumStereoSources;
2049 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2050 data[i++] = device->NumAuxSends;
2052 data[i++] = 0;
2054 break;
2056 case ALC_FREQUENCY:
2057 *data = device->Frequency;
2058 break;
2060 case ALC_REFRESH:
2061 if(device->IsLoopbackDevice)
2062 alcSetError(device, ALC_INVALID_DEVICE);
2063 else
2064 *data = device->Frequency / device->UpdateSize;
2065 break;
2067 case ALC_SYNC:
2068 if(device->IsLoopbackDevice)
2069 alcSetError(device, ALC_INVALID_DEVICE);
2070 else
2071 *data = ALC_FALSE;
2072 break;
2074 case ALC_FORMAT_CHANNELS_SOFT:
2075 if(!device->IsLoopbackDevice)
2076 alcSetError(device, ALC_INVALID_DEVICE);
2077 else
2078 *data = device->FmtChans;
2079 break;
2081 case ALC_FORMAT_TYPE_SOFT:
2082 if(!device->IsLoopbackDevice)
2083 alcSetError(device, ALC_INVALID_DEVICE);
2084 else
2085 *data = device->FmtType;
2086 break;
2088 case ALC_MONO_SOURCES:
2089 *data = device->NumMonoSources;
2090 break;
2092 case ALC_STEREO_SOURCES:
2093 *data = device->NumStereoSources;
2094 break;
2096 case ALC_MAX_AUXILIARY_SENDS:
2097 *data = device->NumAuxSends;
2098 break;
2100 case ALC_CONNECTED:
2101 *data = device->Connected;
2102 break;
2104 default:
2105 alcSetError(device, ALC_INVALID_ENUM);
2106 break;
2109 if(device)
2110 ALCdevice_DecRef(device);
2114 /* alcIsExtensionPresent
2116 * Determines if there is support for a particular extension
2118 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2120 ALCboolean bResult = ALC_FALSE;
2122 device = VerifyDevice(device);
2124 if(!extName)
2125 alcSetError(device, ALC_INVALID_VALUE);
2126 else
2128 size_t len = strlen(extName);
2129 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2130 while(ptr && *ptr)
2132 if(strncasecmp(ptr, extName, len) == 0 &&
2133 (ptr[len] == '\0' || isspace(ptr[len])))
2135 bResult = ALC_TRUE;
2136 break;
2138 if((ptr=strchr(ptr, ' ')) != NULL)
2140 do {
2141 ++ptr;
2142 } while(isspace(*ptr));
2146 if(device)
2147 ALCdevice_DecRef(device);
2148 return bResult;
2152 /* alcGetProcAddress
2154 * Retrieves the function address for a particular extension function
2156 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2158 ALCvoid *ptr = NULL;
2160 device = VerifyDevice(device);
2162 if(!funcName)
2163 alcSetError(device, ALC_INVALID_VALUE);
2164 else
2166 ALsizei i = 0;
2167 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2168 i++;
2169 ptr = alcFunctions[i].address;
2171 if(device)
2172 ALCdevice_DecRef(device);
2173 return ptr;
2177 /* alcGetEnumValue
2179 * Get the value for a particular ALC Enumerated Value
2181 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2183 ALCenum val = 0;
2185 device = VerifyDevice(device);
2187 if(!enumName)
2188 alcSetError(device, ALC_INVALID_VALUE);
2189 else
2191 ALsizei i = 0;
2192 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2193 i++;
2194 val = enumeration[i].value;
2196 if(device)
2197 ALCdevice_DecRef(device);
2198 return val;
2202 /* alcCreateContext
2204 * Create and attach a Context to a particular Device.
2206 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2208 ALCcontext *ALContext;
2209 ALCenum err;
2211 LockLists();
2212 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2214 UnlockLists();
2215 alcSetError(device, ALC_INVALID_DEVICE);
2216 if(device) ALCdevice_DecRef(device);
2217 return NULL;
2220 /* Reset Context Last Error code */
2221 device->LastError = ALC_NO_ERROR;
2223 if((err=UpdateDeviceParams(device, attrList)) != ALC_NO_ERROR)
2225 UnlockLists();
2226 alcSetError(device, err);
2227 if(err == ALC_INVALID_DEVICE)
2228 aluHandleDisconnect(device);
2229 ALCdevice_DecRef(device);
2230 return NULL;
2233 ALContext = calloc(1, sizeof(ALCcontext));
2234 if(ALContext)
2236 ALContext->ref = 1;
2238 ALContext->MaxActiveSources = 256;
2239 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2240 ALContext->MaxActiveSources);
2242 if(!ALContext || !ALContext->ActiveSources)
2244 if(!device->ContextList)
2246 ALCdevice_StopPlayback(device);
2247 device->Flags &= ~DEVICE_RUNNING;
2249 UnlockLists();
2251 free(ALContext);
2252 ALContext = NULL;
2254 alcSetError(device, ALC_OUT_OF_MEMORY);
2255 ALCdevice_DecRef(device);
2256 return NULL;
2259 ALContext->Device = device;
2260 ALCdevice_IncRef(device);
2261 InitContext(ALContext);
2263 do {
2264 ALContext->next = device->ContextList;
2265 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2266 UnlockLists();
2268 if(device->DefaultSlot)
2269 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2270 ALContext->LastError = AL_NO_ERROR;
2272 ALCdevice_DecRef(device);
2274 TRACE("Created context %p\n", ALContext);
2275 return ALContext;
2278 /* alcDestroyContext
2280 * Remove a Context
2282 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2284 ALCdevice *Device;
2286 LockLists();
2287 /* alcGetContextsDevice sets an error for invalid contexts */
2288 Device = alcGetContextsDevice(context);
2289 if(Device)
2291 ReleaseContext(context, Device);
2292 if(!Device->ContextList)
2294 ALCdevice_StopPlayback(Device);
2295 Device->Flags &= ~DEVICE_RUNNING;
2298 UnlockLists();
2302 /* alcGetCurrentContext
2304 * Returns the currently active Context
2306 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2308 ALCcontext *Context;
2310 Context = pthread_getspecific(LocalContext);
2311 if(!Context) Context = GlobalContext;
2313 return Context;
2316 /* alcGetThreadContext
2318 * Returns the currently active thread-local Context
2320 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2322 ALCcontext *Context;
2323 Context = pthread_getspecific(LocalContext);
2324 return Context;
2328 /* alcMakeContextCurrent
2330 * Makes the given Context the active Context
2332 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2334 /* context must be a valid Context or NULL */
2335 if(context && !(context=VerifyContext(context)))
2337 alcSetError(NULL, ALC_INVALID_CONTEXT);
2338 return ALC_FALSE;
2340 /* context's reference count is already incremented */
2341 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2342 if(context) ALCcontext_DecRef(context);
2344 if((context=pthread_getspecific(LocalContext)) != NULL)
2346 pthread_setspecific(LocalContext, NULL);
2347 ALCcontext_DecRef(context);
2350 return ALC_TRUE;
2353 /* alcSetThreadContext
2355 * Makes the given Context the active Context for the current thread
2357 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2359 ALCcontext *old;
2361 /* context must be a valid Context or NULL */
2362 if(context && !(context=VerifyContext(context)))
2364 alcSetError(NULL, ALC_INVALID_CONTEXT);
2365 return ALC_FALSE;
2367 /* context's reference count is already incremented */
2368 old = pthread_getspecific(LocalContext);
2369 pthread_setspecific(LocalContext, context);
2370 if(old) ALCcontext_DecRef(old);
2372 return ALC_TRUE;
2376 /* alcGetContextsDevice
2378 * Returns the Device that a particular Context is attached to
2380 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2382 ALCdevice *Device;
2384 if(!(Context=VerifyContext(Context)))
2386 alcSetError(NULL, ALC_INVALID_CONTEXT);
2387 return NULL;
2389 Device = Context->Device;
2390 ALCcontext_DecRef(Context);
2392 return Device;
2396 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2398 static const struct {
2399 const char name[32];
2400 enum DevFmtChannels channels;
2401 enum DevFmtType type;
2402 } formats[] = {
2403 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2404 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2405 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2406 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2407 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2408 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2410 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2411 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2412 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2413 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2414 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2415 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2417 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2418 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2419 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2420 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2421 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2422 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2424 size_t i;
2426 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2428 if(strcasecmp(str, formats[i].name) == 0)
2430 *chans = formats[i].channels;
2431 *type = formats[i].type;
2432 return;
2436 ERR("Unknown format: \"%s\"\n", str);
2437 *chans = DevFmtStereo;
2438 *type = DevFmtShort;
2441 /* alcOpenDevice
2443 * Open the Device specified.
2445 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2447 const ALCchar *fmt;
2448 ALCdevice *device;
2449 ALCenum err;
2451 DO_INITCONFIG();
2453 if(!PlaybackBackend.name)
2455 alcSetError(NULL, ALC_INVALID_VALUE);
2456 return NULL;
2459 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2460 deviceName = NULL;
2462 device = calloc(1, sizeof(ALCdevice)+sizeof(ALeffectslot));
2463 if(!device)
2465 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2466 return NULL;
2469 //Validate device
2470 device->Funcs = &PlaybackBackend.Funcs;
2471 device->ref = 1;
2472 device->Connected = ALC_TRUE;
2473 device->IsCaptureDevice = AL_FALSE;
2474 device->IsLoopbackDevice = AL_FALSE;
2475 InitializeCriticalSection(&device->Mutex);
2476 device->LastError = ALC_NO_ERROR;
2478 device->Flags = 0;
2479 device->Bs2b = NULL;
2480 device->Bs2bLevel = 0;
2481 device->szDeviceName = NULL;
2483 device->ContextList = NULL;
2485 device->MaxNoOfSources = 256;
2486 device->AuxiliaryEffectSlotMax = 4;
2487 device->NumAuxSends = MAX_SENDS;
2489 InitUIntMap(&device->BufferMap, ~0);
2490 InitUIntMap(&device->EffectMap, ~0);
2491 InitUIntMap(&device->FilterMap, ~0);
2493 //Set output format
2494 device->NumUpdates = 4;
2495 device->UpdateSize = 1024;
2497 device->Frequency = DEFAULT_OUTPUT_RATE;
2498 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2499 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2500 device->Frequency = maxu(device->Frequency, 8000);
2502 fmt = "AL_FORMAT_STEREO32";
2503 if(ConfigValueStr(NULL, "format", &fmt))
2504 device->Flags |= DEVICE_CHANNELS_REQUEST;
2505 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2507 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2508 if(device->NumUpdates < 2) device->NumUpdates = 4;
2510 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2511 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2513 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2514 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2516 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2517 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2519 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2520 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2522 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2524 device->NumStereoSources = 1;
2525 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2527 device->DefaultSlot = (ALeffectslot*)(device+1);
2528 if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR)
2529 device->DefaultSlot = NULL;
2531 // Find a playback device to open
2532 LockLists();
2533 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2535 UnlockLists();
2536 DeleteCriticalSection(&device->Mutex);
2537 free(device);
2538 alcSetError(NULL, err);
2539 return NULL;
2541 UnlockLists();
2543 do {
2544 device->next = DeviceList;
2545 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2547 TRACE("Created device %p\n", device);
2548 return device;
2551 /* alcCloseDevice
2553 * Close the specified Device
2555 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2557 ALCdevice *volatile*list;
2558 ALCcontext *ctx;
2560 LockLists();
2561 list = &DeviceList;
2562 while(*list && *list != pDevice)
2563 list = &(*list)->next;
2565 if(!*list || (*list)->IsCaptureDevice)
2567 alcSetError(*list, ALC_INVALID_DEVICE);
2568 UnlockLists();
2569 return ALC_FALSE;
2572 *list = (*list)->next;
2573 UnlockLists();
2575 if((ctx=pDevice->ContextList) != NULL)
2577 do {
2578 WARN("Releasing context %p\n", ctx);
2579 ReleaseContext(ctx, pDevice);
2580 } while((ctx=pDevice->ContextList) != NULL);
2581 ALCdevice_StopPlayback(pDevice);
2582 pDevice->Flags &= ~DEVICE_RUNNING;
2584 ALCdevice_ClosePlayback(pDevice);
2586 ALCdevice_DecRef(pDevice);
2588 return ALC_TRUE;
2592 /* alcLoopbackOpenDeviceSOFT
2594 * Open a loopback device, for manual rendering.
2596 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2598 ALCdevice *device;
2600 DO_INITCONFIG();
2602 device = calloc(1, sizeof(ALCdevice));
2603 if(!device)
2605 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2606 return NULL;
2609 //Validate device
2610 device->Funcs = &BackendLoopback.Funcs;
2611 device->ref = 1;
2612 device->Connected = ALC_TRUE;
2613 device->IsCaptureDevice = AL_FALSE;
2614 device->IsLoopbackDevice = AL_TRUE;
2615 InitializeCriticalSection(&device->Mutex);
2616 device->LastError = ALC_NO_ERROR;
2618 device->Flags = 0;
2619 device->Bs2b = NULL;
2620 device->Bs2bLevel = 0;
2621 device->szDeviceName = NULL;
2623 device->ContextList = NULL;
2625 device->MaxNoOfSources = 256;
2626 device->AuxiliaryEffectSlotMax = 4;
2627 device->NumAuxSends = MAX_SENDS;
2629 InitUIntMap(&device->BufferMap, ~0);
2630 InitUIntMap(&device->EffectMap, ~0);
2631 InitUIntMap(&device->FilterMap, ~0);
2633 //Set output format
2634 device->NumUpdates = 0;
2635 device->UpdateSize = 0;
2637 device->Frequency = 44100;
2638 device->FmtChans = DevFmtStereo;
2639 device->FmtType = DevFmtShort;
2641 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2642 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2644 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2645 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2647 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2648 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2650 device->NumStereoSources = 1;
2651 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2653 // Open the "backend"
2654 ALCdevice_OpenPlayback(device, "Loopback");
2655 do {
2656 device->next = DeviceList;
2657 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2659 TRACE("Created device %p\n", device);
2660 return device;
2663 /* alcIsRenderFormatSupportedSOFT
2665 * Determines if the loopback device supports the given format for rendering.
2667 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2669 ALCboolean ret = ALC_FALSE;
2671 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2672 alcSetError(device, ALC_INVALID_DEVICE);
2673 else if(freq <= 0)
2674 alcSetError(device, ALC_INVALID_VALUE);
2675 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2676 alcSetError(device, ALC_INVALID_ENUM);
2677 else
2679 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2680 freq >= 8000)
2681 ret = ALC_TRUE;
2683 if(device) ALCdevice_DecRef(device);
2685 return ret;
2688 /* alcRenderSamplesSOFT
2690 * Renders some samples into a buffer, using the format last set by the
2691 * attributes given to alcCreateContext.
2693 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2695 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2696 alcSetError(device, ALC_INVALID_DEVICE);
2697 else if(samples < 0 || (samples > 0 && buffer == NULL))
2698 alcSetError(device, ALC_INVALID_VALUE);
2699 else
2700 aluMixData(device, buffer, samples);
2701 if(device) ALCdevice_DecRef(device);
2705 static void ReleaseALC(void)
2707 ALCdevice *dev;
2709 free(alcDeviceList); alcDeviceList = NULL;
2710 alcDeviceListSize = 0;
2711 free(alcAllDeviceList); alcAllDeviceList = NULL;
2712 alcAllDeviceListSize = 0;
2713 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2714 alcCaptureDeviceListSize = 0;
2716 free(alcDefaultDeviceSpecifier);
2717 alcDefaultDeviceSpecifier = NULL;
2718 free(alcDefaultAllDeviceSpecifier);
2719 alcDefaultAllDeviceSpecifier = NULL;
2720 free(alcCaptureDefaultDeviceSpecifier);
2721 alcCaptureDefaultDeviceSpecifier = NULL;
2723 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2725 ALCuint num = 0;
2726 do {
2727 num++;
2728 } while((dev=dev->next) != NULL);
2729 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2733 ///////////////////////////////////////////////////////