Removed duplicate file in Android.mk file list.
[openal-soft/android.git] / Alc / ALc.c
blob0780ccb1dc63354dd5a846871fb36cc246fe54aa
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
78 #ifdef HAVE_ANDROID
79 { "android", alc_android_init, alc_android_deinit, alc_android_probe, EmptyFuncs },
80 #endif
82 { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs },
83 #ifdef HAVE_WAVE
84 { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs },
85 #endif
87 { NULL, NULL, NULL, NULL, EmptyFuncs }
89 static struct BackendInfo BackendLoopback = {
90 "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs
92 #undef EmptyFuncs
94 static struct BackendInfo PlaybackBackend;
95 static struct BackendInfo CaptureBackend;
97 ///////////////////////////////////////////////////////
98 // STRING and EXTENSIONS
100 typedef struct ALCfunction {
101 const ALCchar *funcName;
102 ALCvoid *address;
103 } ALCfunction;
105 typedef struct ALCenums {
106 const ALCchar *enumName;
107 ALCenum value;
108 } ALCenums;
111 static const ALCfunction alcFunctions[] = {
112 { "alcCreateContext", (ALCvoid *) alcCreateContext },
113 { "alcMakeContextCurrent", (ALCvoid *) alcMakeContextCurrent },
114 { "alcProcessContext", (ALCvoid *) alcProcessContext },
115 { "alcSuspendContext", (ALCvoid *) alcSuspendContext },
116 { "alcDestroyContext", (ALCvoid *) alcDestroyContext },
117 { "alcGetCurrentContext", (ALCvoid *) alcGetCurrentContext },
118 { "alcGetContextsDevice", (ALCvoid *) alcGetContextsDevice },
119 { "alcOpenDevice", (ALCvoid *) alcOpenDevice },
120 { "alcCloseDevice", (ALCvoid *) alcCloseDevice },
121 { "alcGetError", (ALCvoid *) alcGetError },
122 { "alcIsExtensionPresent", (ALCvoid *) alcIsExtensionPresent },
123 { "alcGetProcAddress", (ALCvoid *) alcGetProcAddress },
124 { "alcGetEnumValue", (ALCvoid *) alcGetEnumValue },
125 { "alcGetString", (ALCvoid *) alcGetString },
126 { "alcGetIntegerv", (ALCvoid *) alcGetIntegerv },
127 { "alcCaptureOpenDevice", (ALCvoid *) alcCaptureOpenDevice },
128 { "alcCaptureCloseDevice", (ALCvoid *) alcCaptureCloseDevice },
129 { "alcCaptureStart", (ALCvoid *) alcCaptureStart },
130 { "alcCaptureStop", (ALCvoid *) alcCaptureStop },
131 { "alcCaptureSamples", (ALCvoid *) alcCaptureSamples },
133 { "alcSetThreadContext", (ALCvoid *) alcSetThreadContext },
134 { "alcGetThreadContext", (ALCvoid *) alcGetThreadContext },
136 { "alcLoopbackOpenDeviceSOFT", (ALCvoid *) alcLoopbackOpenDeviceSOFT},
137 { "alcIsRenderFormatSupportedSOFT",(ALCvoid *) alcIsRenderFormatSupportedSOFT},
138 { "alcRenderSamplesSOFT", (ALCvoid *) alcRenderSamplesSOFT },
140 { "alEnable", (ALCvoid *) alEnable },
141 { "alDisable", (ALCvoid *) alDisable },
142 { "alIsEnabled", (ALCvoid *) alIsEnabled },
143 { "alGetString", (ALCvoid *) alGetString },
144 { "alGetBooleanv", (ALCvoid *) alGetBooleanv },
145 { "alGetIntegerv", (ALCvoid *) alGetIntegerv },
146 { "alGetFloatv", (ALCvoid *) alGetFloatv },
147 { "alGetDoublev", (ALCvoid *) alGetDoublev },
148 { "alGetBoolean", (ALCvoid *) alGetBoolean },
149 { "alGetInteger", (ALCvoid *) alGetInteger },
150 { "alGetFloat", (ALCvoid *) alGetFloat },
151 { "alGetDouble", (ALCvoid *) alGetDouble },
152 { "alGetError", (ALCvoid *) alGetError },
153 { "alIsExtensionPresent", (ALCvoid *) alIsExtensionPresent },
154 { "alGetProcAddress", (ALCvoid *) alGetProcAddress },
155 { "alGetEnumValue", (ALCvoid *) alGetEnumValue },
156 { "alListenerf", (ALCvoid *) alListenerf },
157 { "alListener3f", (ALCvoid *) alListener3f },
158 { "alListenerfv", (ALCvoid *) alListenerfv },
159 { "alListeneri", (ALCvoid *) alListeneri },
160 { "alListener3i", (ALCvoid *) alListener3i },
161 { "alListeneriv", (ALCvoid *) alListeneriv },
162 { "alGetListenerf", (ALCvoid *) alGetListenerf },
163 { "alGetListener3f", (ALCvoid *) alGetListener3f },
164 { "alGetListenerfv", (ALCvoid *) alGetListenerfv },
165 { "alGetListeneri", (ALCvoid *) alGetListeneri },
166 { "alGetListener3i", (ALCvoid *) alGetListener3i },
167 { "alGetListeneriv", (ALCvoid *) alGetListeneriv },
168 { "alGenSources", (ALCvoid *) alGenSources },
169 { "alDeleteSources", (ALCvoid *) alDeleteSources },
170 { "alIsSource", (ALCvoid *) alIsSource },
171 { "alSourcef", (ALCvoid *) alSourcef },
172 { "alSource3f", (ALCvoid *) alSource3f },
173 { "alSourcefv", (ALCvoid *) alSourcefv },
174 { "alSourcei", (ALCvoid *) alSourcei },
175 { "alSource3i", (ALCvoid *) alSource3i },
176 { "alSourceiv", (ALCvoid *) alSourceiv },
177 { "alGetSourcef", (ALCvoid *) alGetSourcef },
178 { "alGetSource3f", (ALCvoid *) alGetSource3f },
179 { "alGetSourcefv", (ALCvoid *) alGetSourcefv },
180 { "alGetSourcei", (ALCvoid *) alGetSourcei },
181 { "alGetSource3i", (ALCvoid *) alGetSource3i },
182 { "alGetSourceiv", (ALCvoid *) alGetSourceiv },
183 { "alSourcePlayv", (ALCvoid *) alSourcePlayv },
184 { "alSourceStopv", (ALCvoid *) alSourceStopv },
185 { "alSourceRewindv", (ALCvoid *) alSourceRewindv },
186 { "alSourcePausev", (ALCvoid *) alSourcePausev },
187 { "alSourcePlay", (ALCvoid *) alSourcePlay },
188 { "alSourceStop", (ALCvoid *) alSourceStop },
189 { "alSourceRewind", (ALCvoid *) alSourceRewind },
190 { "alSourcePause", (ALCvoid *) alSourcePause },
191 { "alSourceQueueBuffers", (ALCvoid *) alSourceQueueBuffers },
192 { "alSourceUnqueueBuffers", (ALCvoid *) alSourceUnqueueBuffers },
193 { "alGenBuffers", (ALCvoid *) alGenBuffers },
194 { "alDeleteBuffers", (ALCvoid *) alDeleteBuffers },
195 { "alIsBuffer", (ALCvoid *) alIsBuffer },
196 { "alBufferData", (ALCvoid *) alBufferData },
197 { "alBufferf", (ALCvoid *) alBufferf },
198 { "alBuffer3f", (ALCvoid *) alBuffer3f },
199 { "alBufferfv", (ALCvoid *) alBufferfv },
200 { "alBufferi", (ALCvoid *) alBufferi },
201 { "alBuffer3i", (ALCvoid *) alBuffer3i },
202 { "alBufferiv", (ALCvoid *) alBufferiv },
203 { "alGetBufferf", (ALCvoid *) alGetBufferf },
204 { "alGetBuffer3f", (ALCvoid *) alGetBuffer3f },
205 { "alGetBufferfv", (ALCvoid *) alGetBufferfv },
206 { "alGetBufferi", (ALCvoid *) alGetBufferi },
207 { "alGetBuffer3i", (ALCvoid *) alGetBuffer3i },
208 { "alGetBufferiv", (ALCvoid *) alGetBufferiv },
209 { "alDopplerFactor", (ALCvoid *) alDopplerFactor },
210 { "alDopplerVelocity", (ALCvoid *) alDopplerVelocity },
211 { "alSpeedOfSound", (ALCvoid *) alSpeedOfSound },
212 { "alDistanceModel", (ALCvoid *) alDistanceModel },
214 { "alGenFilters", (ALCvoid *) alGenFilters },
215 { "alDeleteFilters", (ALCvoid *) alDeleteFilters },
216 { "alIsFilter", (ALCvoid *) alIsFilter },
217 { "alFilteri", (ALCvoid *) alFilteri },
218 { "alFilteriv", (ALCvoid *) alFilteriv },
219 { "alFilterf", (ALCvoid *) alFilterf },
220 { "alFilterfv", (ALCvoid *) alFilterfv },
221 { "alGetFilteri", (ALCvoid *) alGetFilteri },
222 { "alGetFilteriv", (ALCvoid *) alGetFilteriv },
223 { "alGetFilterf", (ALCvoid *) alGetFilterf },
224 { "alGetFilterfv", (ALCvoid *) alGetFilterfv },
225 { "alGenEffects", (ALCvoid *) alGenEffects },
226 { "alDeleteEffects", (ALCvoid *) alDeleteEffects },
227 { "alIsEffect", (ALCvoid *) alIsEffect },
228 { "alEffecti", (ALCvoid *) alEffecti },
229 { "alEffectiv", (ALCvoid *) alEffectiv },
230 { "alEffectf", (ALCvoid *) alEffectf },
231 { "alEffectfv", (ALCvoid *) alEffectfv },
232 { "alGetEffecti", (ALCvoid *) alGetEffecti },
233 { "alGetEffectiv", (ALCvoid *) alGetEffectiv },
234 { "alGetEffectf", (ALCvoid *) alGetEffectf },
235 { "alGetEffectfv", (ALCvoid *) alGetEffectfv },
236 { "alGenAuxiliaryEffectSlots", (ALCvoid *) alGenAuxiliaryEffectSlots},
237 { "alDeleteAuxiliaryEffectSlots",(ALCvoid *) alDeleteAuxiliaryEffectSlots},
238 { "alIsAuxiliaryEffectSlot", (ALCvoid *) alIsAuxiliaryEffectSlot },
239 { "alAuxiliaryEffectSloti", (ALCvoid *) alAuxiliaryEffectSloti },
240 { "alAuxiliaryEffectSlotiv", (ALCvoid *) alAuxiliaryEffectSlotiv },
241 { "alAuxiliaryEffectSlotf", (ALCvoid *) alAuxiliaryEffectSlotf },
242 { "alAuxiliaryEffectSlotfv", (ALCvoid *) alAuxiliaryEffectSlotfv },
243 { "alGetAuxiliaryEffectSloti", (ALCvoid *) alGetAuxiliaryEffectSloti},
244 { "alGetAuxiliaryEffectSlotiv", (ALCvoid *) alGetAuxiliaryEffectSlotiv},
245 { "alGetAuxiliaryEffectSlotf", (ALCvoid *) alGetAuxiliaryEffectSlotf},
246 { "alGetAuxiliaryEffectSlotfv", (ALCvoid *) alGetAuxiliaryEffectSlotfv},
248 { "alBufferSubDataSOFT", (ALCvoid *) alBufferSubDataSOFT },
250 { "alBufferSamplesSOFT", (ALCvoid *) alBufferSamplesSOFT },
251 { "alBufferSubSamplesSOFT", (ALCvoid *) alBufferSubSamplesSOFT },
252 { "alGetBufferSamplesSOFT", (ALCvoid *) alGetBufferSamplesSOFT },
253 { "alIsBufferFormatSupportedSOFT",(ALCvoid *) alIsBufferFormatSupportedSOFT},
255 { "alDeferUpdatesSOFT", (ALCvoid *) alDeferUpdatesSOFT },
256 { "alProcessUpdatesSOFT", (ALCvoid *) alProcessUpdatesSOFT },
258 { NULL, (ALCvoid *) NULL }
261 static const ALCenums enumeration[] = {
262 // Types
263 { "ALC_INVALID", ALC_INVALID },
264 { "ALC_FALSE", ALC_FALSE },
265 { "ALC_TRUE", ALC_TRUE },
267 // ALC Properties
268 { "ALC_MAJOR_VERSION", ALC_MAJOR_VERSION },
269 { "ALC_MINOR_VERSION", ALC_MINOR_VERSION },
270 { "ALC_ATTRIBUTES_SIZE", ALC_ATTRIBUTES_SIZE },
271 { "ALC_ALL_ATTRIBUTES", ALC_ALL_ATTRIBUTES },
272 { "ALC_DEFAULT_DEVICE_SPECIFIER", ALC_DEFAULT_DEVICE_SPECIFIER },
273 { "ALC_DEVICE_SPECIFIER", ALC_DEVICE_SPECIFIER },
274 { "ALC_ALL_DEVICES_SPECIFIER", ALC_ALL_DEVICES_SPECIFIER },
275 { "ALC_DEFAULT_ALL_DEVICES_SPECIFIER", ALC_DEFAULT_ALL_DEVICES_SPECIFIER },
276 { "ALC_EXTENSIONS", ALC_EXTENSIONS },
277 { "ALC_FREQUENCY", ALC_FREQUENCY },
278 { "ALC_REFRESH", ALC_REFRESH },
279 { "ALC_SYNC", ALC_SYNC },
280 { "ALC_MONO_SOURCES", ALC_MONO_SOURCES },
281 { "ALC_STEREO_SOURCES", ALC_STEREO_SOURCES },
282 { "ALC_CAPTURE_DEVICE_SPECIFIER", ALC_CAPTURE_DEVICE_SPECIFIER },
283 { "ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER", ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER},
284 { "ALC_CAPTURE_SAMPLES", ALC_CAPTURE_SAMPLES },
285 { "ALC_CONNECTED", ALC_CONNECTED },
287 // EFX Properties
288 { "ALC_EFX_MAJOR_VERSION", ALC_EFX_MAJOR_VERSION },
289 { "ALC_EFX_MINOR_VERSION", ALC_EFX_MINOR_VERSION },
290 { "ALC_MAX_AUXILIARY_SENDS", ALC_MAX_AUXILIARY_SENDS },
292 // Loopback device Properties
293 { "ALC_FORMAT_CHANNELS_SOFT", ALC_FORMAT_CHANNELS_SOFT },
294 { "ALC_FORMAT_TYPE_SOFT", ALC_FORMAT_TYPE_SOFT },
296 // Buffer Channel Configurations
297 { "ALC_MONO_SOFT", ALC_MONO_SOFT },
298 { "ALC_STEREO_SOFT", ALC_STEREO_SOFT },
299 { "ALC_QUAD_SOFT", ALC_QUAD_SOFT },
300 { "ALC_5POINT1_SOFT", ALC_5POINT1_SOFT },
301 { "ALC_6POINT1_SOFT", ALC_6POINT1_SOFT },
302 { "ALC_7POINT1_SOFT", ALC_7POINT1_SOFT },
304 // Buffer Sample Types
305 { "ALC_BYTE_SOFT", ALC_BYTE_SOFT },
306 { "ALC_UNSIGNED_BYTE_SOFT", ALC_UNSIGNED_BYTE_SOFT },
307 { "ALC_SHORT_SOFT", ALC_SHORT_SOFT },
308 { "ALC_UNSIGNED_SHORT_SOFT", ALC_UNSIGNED_SHORT_SOFT },
309 { "ALC_INT_SOFT", ALC_INT_SOFT },
310 { "ALC_UNSIGNED_INT_SOFT", ALC_UNSIGNED_INT_SOFT },
311 { "ALC_FLOAT_SOFT", ALC_FLOAT_SOFT },
313 // ALC Error Message
314 { "ALC_NO_ERROR", ALC_NO_ERROR },
315 { "ALC_INVALID_DEVICE", ALC_INVALID_DEVICE },
316 { "ALC_INVALID_CONTEXT", ALC_INVALID_CONTEXT },
317 { "ALC_INVALID_ENUM", ALC_INVALID_ENUM },
318 { "ALC_INVALID_VALUE", ALC_INVALID_VALUE },
319 { "ALC_OUT_OF_MEMORY", ALC_OUT_OF_MEMORY },
321 { NULL, (ALCenum)0 }
323 // Error strings
324 static const ALCchar alcNoError[] = "No Error";
325 static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
326 static const ALCchar alcErrInvalidContext[] = "Invalid Context";
327 static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
328 static const ALCchar alcErrInvalidValue[] = "Invalid Value";
329 static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
331 /* Device lists. Sizes only include the first ending null character, not the
332 * second */
333 static ALCchar *alcDeviceList;
334 static size_t alcDeviceListSize;
335 static ALCchar *alcAllDeviceList;
336 static size_t alcAllDeviceListSize;
337 static ALCchar *alcCaptureDeviceList;
338 static size_t alcCaptureDeviceListSize;
339 /* Default is always the first in the list */
340 static ALCchar *alcDefaultDeviceSpecifier;
341 static ALCchar *alcDefaultAllDeviceSpecifier;
342 static ALCchar *alcCaptureDefaultDeviceSpecifier;
345 static const ALCchar alcNoDeviceExtList[] =
346 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
347 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
348 static const ALCchar alcExtensionList[] =
349 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
350 "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
351 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
352 static const ALCint alcMajorVersion = 1;
353 static const ALCint alcMinorVersion = 1;
355 static const ALCint alcEFXMajorVersion = 1;
356 static const ALCint alcEFXMinorVersion = 0;
358 ///////////////////////////////////////////////////////
361 ///////////////////////////////////////////////////////
362 // Global Variables
364 static CRITICAL_SECTION ListLock;
366 /* Device List */
367 static ALCdevice *volatile DeviceList = NULL;
369 // Thread-local current context
370 static pthread_key_t LocalContext;
371 // Process-wide current context
372 static ALCcontext *GlobalContext;
374 /* Device Error */
375 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
377 // Default context extensions
378 static const ALchar alExtList[] =
379 "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 "
380 "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
381 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
382 "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data "
383 "AL_SOFTX_deferred_updates AL_SOFT_loop_points "
384 "AL_SOFTX_non_virtual_channels";
386 // Mixing Priority Level
387 ALint RTPrioLevel;
389 // Output Log File
390 FILE *LogFile;
392 // Output Log Level
393 #ifdef _DEBUG
394 enum LogLevel LogLevel = LogWarning;
395 #else
396 enum LogLevel LogLevel = LogError;
397 #endif
399 /* Flag to trap ALC device errors */
400 static ALCboolean TrapALCError = ALC_FALSE;
402 /* One-time configuration init control */
403 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
405 /* Forced effect that applies to sources that don't have an effect on send 0 */
406 static ALeffect ForcedEffect;
408 ///////////////////////////////////////////////////////
411 ///////////////////////////////////////////////////////
412 // ALC Related helper functions
413 static void ReleaseALC(void);
414 static void ReleaseThreadCtx(void *ptr);
416 static void alc_initconfig(void);
417 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
419 #if defined(_WIN32)
420 static void alc_init(void);
421 static void alc_deinit(void);
422 static void alc_deinit_safe(void);
424 UIntMap TlsDestructor;
426 #ifndef AL_LIBTYPE_STATIC
427 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
429 ALsizei i;
430 (void)hModule;
432 // Perform actions based on the reason for calling.
433 switch(ul_reason_for_call)
435 case DLL_PROCESS_ATTACH:
436 InitUIntMap(&TlsDestructor, ~0);
437 alc_init();
438 break;
440 case DLL_THREAD_DETACH:
441 LockUIntMapRead(&TlsDestructor);
442 for(i = 0;i < TlsDestructor.size;i++)
444 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
445 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
446 if(ptr && callback)
447 callback(ptr);
449 UnlockUIntMapRead(&TlsDestructor);
450 break;
452 case DLL_PROCESS_DETACH:
453 if(!lpReserved)
454 alc_deinit();
455 else
456 alc_deinit_safe();
457 ResetUIntMap(&TlsDestructor);
458 break;
460 return TRUE;
462 #elif defined(_MSC_VER)
463 #pragma section(".CRT$XCU",read)
464 static void alc_constructor(void);
465 static void alc_destructor(void);
466 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
468 static void alc_constructor(void)
470 atexit(alc_destructor);
471 alc_init();
474 static void alc_destructor(void)
476 alc_deinit();
478 #elif defined(HAVE_GCC_DESTRUCTOR)
479 static void alc_init(void) __attribute__((constructor));
480 static void alc_deinit(void) __attribute__((destructor));
481 #else
482 #error "No static initialization available on this platform!"
483 #endif
484 #elif defined(HAVE_GCC_DESTRUCTOR)
485 static void alc_init(void) __attribute__((constructor));
486 static void alc_deinit(void) __attribute__((destructor));
487 #else
488 #error "No global initialization available on this platform!"
489 #endif
491 static void alc_init(void)
493 const char *str;
495 LogFile = stderr;
497 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
498 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
499 ConeScale = 1.0f;
501 str = getenv("__ALSOFT_REVERSE_Z");
502 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
503 ZScale = -1.0f;
505 str = getenv("__ALSOFT_TRAP_ERROR");
506 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
508 TrapALError = AL_TRUE;
509 TrapALCError = AL_TRUE;
511 else
513 str = getenv("__ALSOFT_TRAP_AL_ERROR");
514 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
515 TrapALError = AL_TRUE;
517 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
518 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
519 TrapALCError = ALC_TRUE;
522 pthread_key_create(&LocalContext, ReleaseThreadCtx);
523 InitializeCriticalSection(&ListLock);
524 ThunkInit();
527 static void alc_deinit_safe(void)
529 ReleaseALC();
531 FreeHrtf();
532 FreeALConfig();
534 ThunkExit();
535 DeleteCriticalSection(&ListLock);
536 pthread_key_delete(LocalContext);
538 if(LogFile != stderr)
539 fclose(LogFile);
540 LogFile = NULL;
543 static void alc_deinit(void)
545 int i;
547 ReleaseALC();
549 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
550 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
552 for(i = 0;BackendList[i].Deinit;i++)
553 BackendList[i].Deinit();
554 BackendLoopback.Deinit();
556 alc_deinit_safe();
559 static void alc_initconfig(void)
561 const char *devs, *str;
562 float valf;
563 int i, n;
565 str = getenv("ALSOFT_LOGLEVEL");
566 if(str)
568 long lvl = strtol(str, NULL, 0);
569 if(lvl >= NoLog && lvl <= LogRef)
570 LogLevel = lvl;
573 str = getenv("ALSOFT_LOGFILE");
574 if(str && str[0])
576 FILE *logfile = fopen(str, "wat");
577 if(logfile) LogFile = logfile;
578 else ERR("Failed to open log file '%s'\n", str);
581 ReadALConfig();
583 InitHrtf();
585 #ifdef _WIN32
586 RTPrioLevel = 1;
587 #else
588 RTPrioLevel = 0;
589 #endif
590 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
592 if(ConfigValueStr(NULL, "resampler", &str))
594 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
595 DefaultResampler = POINT_RESAMPLER;
596 else if(strcasecmp(str, "linear") == 0)
597 DefaultResampler = LINEAR_RESAMPLER;
598 else if(strcasecmp(str, "cubic") == 0)
599 DefaultResampler = CUBIC_RESAMPLER;
600 else
602 char *end;
604 n = strtol(str, &end, 0);
605 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
606 DefaultResampler = n;
607 else
608 WARN("Invalid resampler: %s\n", str);
612 if(!TrapALCError)
613 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
615 if(!TrapALError)
616 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
618 if(ConfigValueFloat("reverb", "boost", &valf))
619 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
621 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
623 if(ConfigValueStr(NULL, "drivers", &devs))
625 int n;
626 size_t len;
627 const char *next = devs;
628 int endlist, delitem;
630 i = 0;
631 do {
632 devs = next;
633 next = strchr(devs, ',');
635 delitem = (devs[0] == '-');
636 if(devs[0] == '-') devs++;
638 if(!devs[0] || devs[0] == ',')
640 endlist = 0;
641 continue;
643 endlist = 1;
645 len = (next ? ((size_t)(next-devs)) : strlen(devs));
646 for(n = i;BackendList[n].Init;n++)
648 if(len == strlen(BackendList[n].name) &&
649 strncmp(BackendList[n].name, devs, len) == 0)
651 if(delitem)
653 do {
654 BackendList[n] = BackendList[n+1];
655 ++n;
656 } while(BackendList[n].Init);
658 else
660 struct BackendInfo Bkp = BackendList[n];
661 while(n > i)
663 BackendList[n] = BackendList[n-1];
664 --n;
666 BackendList[n] = Bkp;
668 i++;
670 break;
673 } while(next++);
675 if(endlist)
677 BackendList[i].name = NULL;
678 BackendList[i].Init = NULL;
679 BackendList[i].Deinit = NULL;
680 BackendList[i].Probe = NULL;
684 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
686 if(!BackendList[i].Init(&BackendList[i].Funcs))
688 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
689 continue;
692 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
693 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
695 PlaybackBackend = BackendList[i];
696 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
698 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
700 CaptureBackend = BackendList[i];
701 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
704 BackendLoopback.Init(&BackendLoopback.Funcs);
706 if(ConfigValueStr(NULL, "excludefx", &str))
708 size_t len;
709 const char *next = str;
711 do {
712 str = next;
713 next = strchr(str, ',');
715 if(!str[0] || next == str)
716 continue;
718 len = (next ? ((size_t)(next-str)) : strlen(str));
719 for(n = 0;EffectList[n].name;n++)
721 if(len == strlen(EffectList[n].name) &&
722 strncmp(EffectList[n].name, str, len) == 0)
723 DisabledEffects[EffectList[n].type] = AL_TRUE;
725 } while(next++);
728 InitEffect(&ForcedEffect);
729 str = getenv("__ALSOFT_DEFAULT_REVERB");
730 if(str && str[0])
731 GetReverbEffect(str, &ForcedEffect);
732 else if(ConfigValueStr(NULL, "default-reverb", &str))
733 GetReverbEffect(str, &ForcedEffect);
737 static void LockLists(void)
739 EnterCriticalSection(&ListLock);
742 static void UnlockLists(void)
744 LeaveCriticalSection(&ListLock);
748 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
750 DO_INITCONFIG();
752 LockLists();
753 free(*list);
754 *list = NULL;
755 *listsize = 0;
757 if(type == CAPTURE_DEVICE_PROBE)
758 CaptureBackend.Probe(type);
759 else
760 PlaybackBackend.Probe(type);
761 UnlockLists();
764 static void ProbeDeviceList(void)
765 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
766 static void ProbeAllDeviceList(void)
767 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
768 static void ProbeCaptureDeviceList(void)
769 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
772 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
774 size_t len = strlen(name);
775 void *temp;
777 if(len == 0)
778 return;
780 temp = realloc(*List, (*ListSize) + len + 2);
781 if(!temp)
783 ERR("Realloc failed to add %s!\n", name);
784 return;
786 *List = temp;
788 memcpy((*List)+(*ListSize), name, len+1);
789 *ListSize += len+1;
790 (*List)[*ListSize] = 0;
793 #define DECL_APPEND_LIST_FUNC(type) \
794 void Append##type##List(const ALCchar *name) \
795 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
797 DECL_APPEND_LIST_FUNC(Device)
798 DECL_APPEND_LIST_FUNC(AllDevice)
799 DECL_APPEND_LIST_FUNC(CaptureDevice)
801 #undef DECL_APPEND_LIST_FUNC
804 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
805 void SetDefaultChannelOrder(ALCdevice *device)
807 switch(device->FmtChans)
809 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
810 device->DevChannels[1] = FRONT_RIGHT;
811 device->DevChannels[2] = BACK_LEFT;
812 device->DevChannels[3] = BACK_RIGHT;
813 device->DevChannels[4] = FRONT_CENTER;
814 device->DevChannels[5] = LFE;
815 return;
817 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
818 device->DevChannels[1] = FRONT_RIGHT;
819 device->DevChannels[2] = BACK_LEFT;
820 device->DevChannels[3] = BACK_RIGHT;
821 device->DevChannels[4] = FRONT_CENTER;
822 device->DevChannels[5] = LFE;
823 device->DevChannels[6] = SIDE_LEFT;
824 device->DevChannels[7] = SIDE_RIGHT;
825 return;
827 /* Same as WFX order */
828 case DevFmtMono:
829 case DevFmtStereo:
830 case DevFmtQuad:
831 case DevFmtX51Side:
832 case DevFmtX61:
833 break;
835 SetDefaultWFXChannelOrder(device);
837 /* Sets the default order used by WaveFormatEx */
838 void SetDefaultWFXChannelOrder(ALCdevice *device)
840 switch(device->FmtChans)
842 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
844 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
845 device->DevChannels[1] = FRONT_RIGHT; break;
847 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
848 device->DevChannels[1] = FRONT_RIGHT;
849 device->DevChannels[2] = BACK_LEFT;
850 device->DevChannels[3] = BACK_RIGHT; break;
852 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
853 device->DevChannels[1] = FRONT_RIGHT;
854 device->DevChannels[2] = FRONT_CENTER;
855 device->DevChannels[3] = LFE;
856 device->DevChannels[4] = BACK_LEFT;
857 device->DevChannels[5] = BACK_RIGHT; break;
859 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
860 device->DevChannels[1] = FRONT_RIGHT;
861 device->DevChannels[2] = FRONT_CENTER;
862 device->DevChannels[3] = LFE;
863 device->DevChannels[4] = SIDE_LEFT;
864 device->DevChannels[5] = SIDE_RIGHT; break;
866 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
867 device->DevChannels[1] = FRONT_RIGHT;
868 device->DevChannels[2] = FRONT_CENTER;
869 device->DevChannels[3] = LFE;
870 device->DevChannels[4] = BACK_CENTER;
871 device->DevChannels[5] = SIDE_LEFT;
872 device->DevChannels[6] = SIDE_RIGHT; break;
874 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
875 device->DevChannels[1] = FRONT_RIGHT;
876 device->DevChannels[2] = FRONT_CENTER;
877 device->DevChannels[3] = LFE;
878 device->DevChannels[4] = BACK_LEFT;
879 device->DevChannels[5] = BACK_RIGHT;
880 device->DevChannels[6] = SIDE_LEFT;
881 device->DevChannels[7] = SIDE_RIGHT; break;
886 const ALCchar *DevFmtTypeString(enum DevFmtType type)
888 switch(type)
890 case DevFmtByte: return "Signed Byte";
891 case DevFmtUByte: return "Unsigned Byte";
892 case DevFmtShort: return "Signed Short";
893 case DevFmtUShort: return "Unsigned Short";
894 case DevFmtFloat: return "Float";
896 return "(unknown type)";
898 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
900 switch(chans)
902 case DevFmtMono: return "Mono";
903 case DevFmtStereo: return "Stereo";
904 case DevFmtQuad: return "Quadraphonic";
905 case DevFmtX51: return "5.1 Surround";
906 case DevFmtX51Side: return "5.1 Side";
907 case DevFmtX61: return "6.1 Surround";
908 case DevFmtX71: return "7.1 Surround";
910 return "(unknown channels)";
913 ALuint BytesFromDevFmt(enum DevFmtType type)
915 switch(type)
917 case DevFmtByte: return sizeof(ALbyte);
918 case DevFmtUByte: return sizeof(ALubyte);
919 case DevFmtShort: return sizeof(ALshort);
920 case DevFmtUShort: return sizeof(ALushort);
921 case DevFmtFloat: return sizeof(ALfloat);
923 return 0;
925 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
927 switch(chans)
929 case DevFmtMono: return 1;
930 case DevFmtStereo: return 2;
931 case DevFmtQuad: return 4;
932 case DevFmtX51: return 6;
933 case DevFmtX51Side: return 6;
934 case DevFmtX61: return 7;
935 case DevFmtX71: return 8;
937 return 0;
939 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
940 enum DevFmtType *type)
942 static const struct {
943 ALenum format;
944 enum DevFmtChannels channels;
945 enum DevFmtType type;
946 } list[] = {
947 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
948 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
949 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
951 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
952 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
953 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
955 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
956 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
957 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
959 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
960 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
961 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
963 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
964 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
965 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
967 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
968 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
969 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
971 ALuint i;
973 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
975 if(list[i].format == format)
977 *chans = list[i].channels;
978 *type = list[i].type;
979 return AL_TRUE;
983 return AL_FALSE;
986 static ALCboolean IsValidALCType(ALCenum type)
988 switch(type)
990 case ALC_BYTE_SOFT:
991 case ALC_UNSIGNED_BYTE_SOFT:
992 case ALC_SHORT_SOFT:
993 case ALC_UNSIGNED_SHORT_SOFT:
994 case ALC_INT_SOFT:
995 case ALC_UNSIGNED_INT_SOFT:
996 case ALC_FLOAT_SOFT:
997 return ALC_TRUE;
999 return ALC_FALSE;
1002 static ALCboolean IsValidALCChannels(ALCenum channels)
1004 switch(channels)
1006 case ALC_MONO_SOFT:
1007 case ALC_STEREO_SOFT:
1008 case ALC_QUAD_SOFT:
1009 case ALC_5POINT1_SOFT:
1010 case ALC_6POINT1_SOFT:
1011 case ALC_7POINT1_SOFT:
1012 return ALC_TRUE;
1014 return ALC_FALSE;
1018 /* alcSetError
1020 * Stores the latest ALC Error
1022 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1024 if(TrapALCError)
1026 #ifdef _WIN32
1027 /* DebugBreak() will cause an exception if there is no debugger */
1028 if(IsDebuggerPresent())
1029 DebugBreak();
1030 #elif defined(SIGTRAP)
1031 raise(SIGTRAP);
1032 #endif
1035 if(device)
1036 device->LastError = errorCode;
1037 else
1038 g_eLastNullDeviceError = errorCode;
1042 /* UpdateDeviceParams
1044 * Updates device parameters according to the attribute list (caller is
1045 * responsible for holding the list lock).
1047 static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1049 ALCcontext *context;
1050 enum DevFmtChannels oldChans;
1051 enum DevFmtType oldType;
1052 ALCuint oldFreq;
1053 int oldMode;
1054 ALuint i;
1056 if(device->IsLoopbackDevice && !(attrList && attrList[0]))
1058 WARN("Missing attributes for loopback device\n");
1059 return ALC_INVALID_VALUE;
1062 // Check for attributes
1063 if(attrList && attrList[0])
1065 enum {
1066 GotFreq = 1<<0,
1067 GotChans = 1<<1,
1068 GotType = 1<<2,
1069 GotAll = GotFreq|GotChans|GotType
1071 ALCuint freq, numMono, numStereo, numSends;
1072 enum DevFmtChannels schans;
1073 enum DevFmtType stype;
1074 ALCuint attrIdx = 0;
1075 ALCint gotFmt = 0;
1077 // If a context is already running on the device, stop playback so the
1078 // device attributes can be updated
1079 if((device->Flags&DEVICE_RUNNING))
1080 ALCdevice_StopPlayback(device);
1081 device->Flags &= ~DEVICE_RUNNING;
1083 freq = device->Frequency;
1084 schans = device->FmtChans;
1085 stype = device->FmtType;
1086 numMono = device->NumMonoSources;
1087 numStereo = device->NumStereoSources;
1088 numSends = device->NumAuxSends;
1090 while(attrList[attrIdx])
1092 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1093 device->IsLoopbackDevice)
1095 ALCint val = attrList[attrIdx + 1];
1096 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1097 return ALC_INVALID_VALUE;
1098 schans = val;
1099 gotFmt |= GotChans;
1102 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1103 device->IsLoopbackDevice)
1105 ALCint val = attrList[attrIdx + 1];
1106 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1107 return ALC_INVALID_VALUE;
1108 stype = val;
1109 gotFmt |= GotType;
1112 if(attrList[attrIdx] == ALC_FREQUENCY)
1114 if(device->IsLoopbackDevice)
1116 freq = attrList[attrIdx + 1];
1117 if(freq < 8000)
1118 return ALC_INVALID_VALUE;
1119 gotFmt |= GotFreq;
1121 else
1123 freq = attrList[attrIdx + 1];
1124 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1128 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1130 numStereo = attrList[attrIdx + 1];
1131 if(numStereo > device->MaxNoOfSources)
1132 numStereo = device->MaxNoOfSources;
1134 numMono = device->MaxNoOfSources - numStereo;
1137 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1138 numSends = attrList[attrIdx + 1];
1140 attrIdx += 2;
1143 if(device->IsLoopbackDevice)
1145 if(gotFmt != GotAll)
1147 WARN("Missing format for loopback device\n");
1148 return ALC_INVALID_VALUE;
1151 else
1153 ConfigValueUInt(NULL, "frequency", &freq);
1154 freq = maxu(freq, 8000);
1156 ConfigValueUInt(NULL, "sends", &numSends);
1157 numSends = minu(MAX_SENDS, numSends);
1159 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1160 device->Frequency;
1162 device->Frequency = freq;
1163 device->FmtChans = schans;
1164 device->FmtType = stype;
1165 device->NumMonoSources = numMono;
1166 device->NumStereoSources = numStereo;
1167 device->NumAuxSends = numSends;
1170 if((device->Flags&DEVICE_RUNNING))
1171 return ALC_NO_ERROR;
1173 LockDevice(device);
1175 oldFreq = device->Frequency;
1176 oldChans = device->FmtChans;
1177 oldType = device->FmtType;
1179 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1180 DevFmtChannelsString(device->FmtChans),
1181 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1182 DevFmtTypeString(device->FmtType), device->Frequency,
1183 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1184 device->UpdateSize, device->NumUpdates);
1185 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1187 UnlockDevice(device);
1188 return ALC_INVALID_DEVICE;
1190 device->Flags |= DEVICE_RUNNING;
1192 if(device->FmtChans != oldChans)
1194 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1195 ERR("Failed to set %s, got %s instead\n",
1196 DevFmtChannelsString(oldChans),
1197 DevFmtChannelsString(device->FmtChans));
1198 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1200 if(device->Frequency != oldFreq)
1202 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1203 ERR("Failed to set %uhz, got %uhz instead\n",
1204 oldFreq, device->Frequency);
1205 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1208 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1209 DevFmtChannelsString(device->FmtChans),
1210 DevFmtTypeString(device->FmtType), device->Frequency,
1211 device->UpdateSize, device->NumUpdates);
1213 aluInitPanning(device);
1215 for(i = 0;i < MAXCHANNELS;i++)
1217 device->ClickRemoval[i] = 0.0f;
1218 device->PendingClicks[i] = 0.0f;
1221 device->Hrtf = NULL;
1222 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1223 device->Hrtf = GetHrtf(device);
1224 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1226 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1228 if(!device->Bs2b)
1230 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1231 bs2b_clear(device->Bs2b);
1233 bs2b_set_srate(device->Bs2b, device->Frequency);
1234 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1235 TRACE("BS2B level %d\n", device->Bs2bLevel);
1237 else
1239 free(device->Bs2b);
1240 device->Bs2b = NULL;
1241 TRACE("BS2B disabled\n");
1244 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1245 switch(device->FmtChans)
1247 case DevFmtMono:
1248 case DevFmtStereo:
1249 break;
1250 case DevFmtQuad:
1251 case DevFmtX51:
1252 case DevFmtX51Side:
1253 case DevFmtX61:
1254 case DevFmtX71:
1255 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1256 device->Flags |= DEVICE_DUPLICATE_STEREO;
1257 break;
1259 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1261 oldMode = SetMixerFPUMode();
1262 context = device->ContextList;
1263 while(context)
1265 ALsizei pos;
1267 context->UpdateSources = AL_FALSE;
1268 LockUIntMapRead(&context->EffectSlotMap);
1269 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1271 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1273 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1275 UnlockUIntMapRead(&context->EffectSlotMap);
1276 RestoreFPUMode(oldMode);
1277 UnlockDevice(device);
1278 ALCdevice_StopPlayback(device);
1279 device->Flags &= ~DEVICE_RUNNING;
1280 return ALC_INVALID_DEVICE;
1282 slot->NeedsUpdate = AL_FALSE;
1283 ALeffectState_Update(slot->EffectState, context, slot);
1285 UnlockUIntMapRead(&context->EffectSlotMap);
1287 LockUIntMapRead(&context->SourceMap);
1288 for(pos = 0;pos < context->SourceMap.size;pos++)
1290 ALsource *source = context->SourceMap.array[pos].value;
1291 ALuint s = device->NumAuxSends;
1292 while(s < MAX_SENDS)
1294 if(source->Send[s].Slot)
1295 DecrementRef(&source->Send[s].Slot->ref);
1296 source->Send[s].Slot = NULL;
1297 source->Send[s].WetGain = 1.0f;
1298 source->Send[s].WetGainHF = 1.0f;
1299 s++;
1301 source->NeedsUpdate = AL_FALSE;
1302 ALsource_Update(source, context);
1304 UnlockUIntMapRead(&context->SourceMap);
1306 context = context->next;
1308 RestoreFPUMode(oldMode);
1309 UnlockDevice(device);
1311 return ALC_NO_ERROR;
1314 /* FreeDevice
1316 * Frees the device structure, and destroys any objects the app failed to
1317 * delete. Called once there's no more references on the device.
1319 static ALCvoid FreeDevice(ALCdevice *device)
1321 TRACE("%p\n", device);
1323 if(device->DefaultSlot)
1325 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1326 device->DefaultSlot->EffectState = NULL;
1329 if(device->BufferMap.size > 0)
1331 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1332 ReleaseALBuffers(device);
1334 ResetUIntMap(&device->BufferMap);
1336 if(device->EffectMap.size > 0)
1338 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1339 ReleaseALEffects(device);
1341 ResetUIntMap(&device->EffectMap);
1343 if(device->FilterMap.size > 0)
1345 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1346 ReleaseALFilters(device);
1348 ResetUIntMap(&device->FilterMap);
1350 free(device->Bs2b);
1351 device->Bs2b = NULL;
1353 free(device->szDeviceName);
1354 device->szDeviceName = NULL;
1356 DeleteCriticalSection(&device->Mutex);
1358 free(device);
1362 void ALCdevice_IncRef(ALCdevice *device)
1364 RefCount ref;
1365 ref = IncrementRef(&device->ref);
1366 TRACEREF("%p increasing refcount to %u\n", device, ref);
1369 void ALCdevice_DecRef(ALCdevice *device)
1371 RefCount ref;
1372 ref = DecrementRef(&device->ref);
1373 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1374 if(ref == 0) FreeDevice(device);
1377 /* VerifyDevice
1379 * Checks if the device handle is valid, and increments its ref count if so.
1381 static ALCdevice *VerifyDevice(ALCdevice *device)
1383 ALCdevice *tmpDevice;
1385 if(!device)
1386 return NULL;
1388 LockLists();
1389 tmpDevice = DeviceList;
1390 while(tmpDevice && tmpDevice != device)
1391 tmpDevice = tmpDevice->next;
1393 if(tmpDevice)
1394 ALCdevice_IncRef(tmpDevice);
1395 UnlockLists();
1396 return tmpDevice;
1400 /* InitContext
1402 * Initializes context variables
1404 static ALvoid InitContext(ALCcontext *pContext)
1406 ALint i, j;
1408 //Initialise listener
1409 pContext->Listener.Gain = 1.0f;
1410 pContext->Listener.MetersPerUnit = 1.0f;
1411 pContext->Listener.Position[0] = 0.0f;
1412 pContext->Listener.Position[1] = 0.0f;
1413 pContext->Listener.Position[2] = 0.0f;
1414 pContext->Listener.Velocity[0] = 0.0f;
1415 pContext->Listener.Velocity[1] = 0.0f;
1416 pContext->Listener.Velocity[2] = 0.0f;
1417 pContext->Listener.Forward[0] = 0.0f;
1418 pContext->Listener.Forward[1] = 0.0f;
1419 pContext->Listener.Forward[2] = -1.0f;
1420 pContext->Listener.Up[0] = 0.0f;
1421 pContext->Listener.Up[1] = 1.0f;
1422 pContext->Listener.Up[2] = 0.0f;
1423 for(i = 0;i < 4;i++)
1425 for(j = 0;j < 4;j++)
1426 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1429 //Validate pContext
1430 pContext->LastError = AL_NO_ERROR;
1431 pContext->UpdateSources = AL_FALSE;
1432 pContext->ActiveSourceCount = 0;
1433 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1434 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1436 //Set globals
1437 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1438 pContext->SourceDistanceModel = AL_FALSE;
1439 pContext->DopplerFactor = 1.0f;
1440 pContext->DopplerVelocity = 1.0f;
1441 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1442 pContext->DeferUpdates = AL_FALSE;
1444 pContext->ExtensionList = alExtList;
1448 /* FreeContext
1450 * Cleans up the context, and destroys any remaining objects the app failed to
1451 * delete. Called once there's no more references on the context.
1453 static ALCvoid FreeContext(ALCcontext *context)
1455 TRACE("%p\n", context);
1457 if(context->SourceMap.size > 0)
1459 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1460 ReleaseALSources(context);
1462 ResetUIntMap(&context->SourceMap);
1464 if(context->EffectSlotMap.size > 0)
1466 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1467 ReleaseALAuxiliaryEffectSlots(context);
1469 ResetUIntMap(&context->EffectSlotMap);
1471 context->ActiveSourceCount = 0;
1472 free(context->ActiveSources);
1473 context->ActiveSources = NULL;
1474 context->MaxActiveSources = 0;
1476 context->ActiveEffectSlotCount = 0;
1477 free(context->ActiveEffectSlots);
1478 context->ActiveEffectSlots = NULL;
1479 context->MaxActiveEffectSlots = 0;
1481 ALCdevice_DecRef(context->Device);
1482 context->Device = NULL;
1484 //Invalidate context
1485 memset(context, 0, sizeof(ALCcontext));
1486 free(context);
1489 /* ReleaseContext
1491 * Removes the context reference from the given device and removes it from
1492 * being current on the running thread or globally.
1494 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1496 ALCcontext *volatile*tmp_ctx;
1498 if(pthread_getspecific(LocalContext) == context)
1500 WARN("%p released while current on thread\n", context);
1501 pthread_setspecific(LocalContext, NULL);
1502 ALCcontext_DecRef(context);
1505 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1506 ALCcontext_DecRef(context);
1508 LockDevice(device);
1509 tmp_ctx = &device->ContextList;
1510 while(*tmp_ctx)
1512 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1513 break;
1514 tmp_ctx = &(*tmp_ctx)->next;
1516 UnlockDevice(device);
1518 ALCcontext_DecRef(context);
1521 void ALCcontext_IncRef(ALCcontext *context)
1523 RefCount ref;
1524 ref = IncrementRef(&context->ref);
1525 TRACEREF("%p increasing refcount to %u\n", context, ref);
1528 void ALCcontext_DecRef(ALCcontext *context)
1530 RefCount ref;
1531 ref = DecrementRef(&context->ref);
1532 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1533 if(ref == 0) FreeContext(context);
1536 static void ReleaseThreadCtx(void *ptr)
1538 WARN("%p current for thread being destroyed\n", ptr);
1539 ALCcontext_DecRef(ptr);
1542 /* VerifyContext
1544 * Checks that the given context is valid, and increments its reference count.
1546 static ALCcontext *VerifyContext(ALCcontext *context)
1548 ALCdevice *dev;
1550 LockLists();
1551 dev = DeviceList;
1552 while(dev)
1554 ALCcontext *tmp_ctx = dev->ContextList;
1555 while(tmp_ctx)
1557 if(tmp_ctx == context)
1559 ALCcontext_IncRef(tmp_ctx);
1560 UnlockLists();
1561 return tmp_ctx;
1563 tmp_ctx = tmp_ctx->next;
1565 dev = dev->next;
1567 UnlockLists();
1569 return NULL;
1573 /* GetContextRef
1575 * Returns the currently active context, and adds a reference without locking
1576 * it.
1578 ALCcontext *GetContextRef(void)
1580 ALCcontext *context;
1582 context = pthread_getspecific(LocalContext);
1583 if(context)
1584 ALCcontext_IncRef(context);
1585 else
1587 LockLists();
1588 context = GlobalContext;
1589 if(context)
1590 ALCcontext_IncRef(context);
1591 UnlockLists();
1594 return context;
1597 ///////////////////////////////////////////////////////
1600 ///////////////////////////////////////////////////////
1601 // ALC Functions calls
1604 // This should probably move to another c file but for now ...
1605 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1607 ALCdevice *device = NULL;
1608 ALCenum err;
1610 DO_INITCONFIG();
1612 if(!CaptureBackend.name)
1614 alcSetError(NULL, ALC_INVALID_VALUE);
1615 return NULL;
1618 if(SampleSize <= 0)
1620 alcSetError(NULL, ALC_INVALID_VALUE);
1621 return NULL;
1624 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1625 deviceName = NULL;
1627 device = calloc(1, sizeof(ALCdevice));
1628 if(!device)
1630 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1631 return NULL;
1634 //Validate device
1635 device->Funcs = &CaptureBackend.Funcs;
1636 device->ref = 1;
1637 device->Connected = ALC_TRUE;
1638 device->IsCaptureDevice = AL_TRUE;
1639 device->IsLoopbackDevice = AL_FALSE;
1640 InitializeCriticalSection(&device->Mutex);
1642 InitUIntMap(&device->BufferMap, ~0);
1643 InitUIntMap(&device->EffectMap, ~0);
1644 InitUIntMap(&device->FilterMap, ~0);
1646 device->szDeviceName = NULL;
1648 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1649 device->Frequency = frequency;
1651 device->Flags |= DEVICE_CHANNELS_REQUEST;
1652 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1654 DeleteCriticalSection(&device->Mutex);
1655 free(device);
1656 alcSetError(NULL, ALC_INVALID_ENUM);
1657 return NULL;
1660 device->UpdateSize = SampleSize;
1661 device->NumUpdates = 1;
1663 LockLists();
1664 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1666 UnlockLists();
1667 DeleteCriticalSection(&device->Mutex);
1668 free(device);
1669 alcSetError(NULL, err);
1670 return NULL;
1672 UnlockLists();
1674 do {
1675 device->next = DeviceList;
1676 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1678 TRACE("Created device %p\n", device);
1679 return device;
1682 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1684 ALCdevice *volatile*list;
1686 LockLists();
1687 list = &DeviceList;
1688 while(*list && *list != pDevice)
1689 list = &(*list)->next;
1691 if(!*list || !(*list)->IsCaptureDevice)
1693 alcSetError(*list, ALC_INVALID_DEVICE);
1694 UnlockLists();
1695 return ALC_FALSE;
1698 *list = (*list)->next;
1699 UnlockLists();
1701 LockDevice(pDevice);
1702 ALCdevice_CloseCapture(pDevice);
1703 UnlockDevice(pDevice);
1705 ALCdevice_DecRef(pDevice);
1707 return ALC_TRUE;
1710 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1712 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1714 alcSetError(device, ALC_INVALID_DEVICE);
1715 if(device) ALCdevice_DecRef(device);
1716 return;
1718 LockDevice(device);
1719 if(device->Connected)
1720 ALCdevice_StartCapture(device);
1721 UnlockDevice(device);
1723 ALCdevice_DecRef(device);
1726 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1728 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1730 alcSetError(device, ALC_INVALID_DEVICE);
1731 if(device) ALCdevice_DecRef(device);
1732 return;
1734 LockDevice(device);
1735 if(device->Connected)
1736 ALCdevice_StopCapture(device);
1737 UnlockDevice(device);
1739 ALCdevice_DecRef(device);
1742 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1744 ALCenum err = ALC_INVALID_DEVICE;
1745 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1747 err = ALC_INVALID_VALUE;
1748 LockDevice(device);
1749 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1750 err = ALCdevice_CaptureSamples(device, buffer, samples);
1751 UnlockDevice(device);
1753 if(err != ALC_NO_ERROR)
1754 alcSetError(device, err);
1755 if(device) ALCdevice_DecRef(device);
1759 alcGetError
1761 Return last ALC generated error code
1763 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1765 ALCenum errorCode;
1767 if(VerifyDevice(device))
1769 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1770 ALCdevice_DecRef(device);
1772 else
1773 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1775 return errorCode;
1779 /* alcSuspendContext
1781 * Not functional
1783 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1785 (void)Context;
1788 /* alcProcessContext
1790 * Not functional
1792 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1794 (void)Context;
1798 /* alcGetString
1800 * Returns information about the Device, and error strings
1802 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1804 const ALCchar *value = NULL;
1806 switch(param)
1808 case ALC_NO_ERROR:
1809 value = alcNoError;
1810 break;
1812 case ALC_INVALID_ENUM:
1813 value = alcErrInvalidEnum;
1814 break;
1816 case ALC_INVALID_VALUE:
1817 value = alcErrInvalidValue;
1818 break;
1820 case ALC_INVALID_DEVICE:
1821 value = alcErrInvalidDevice;
1822 break;
1824 case ALC_INVALID_CONTEXT:
1825 value = alcErrInvalidContext;
1826 break;
1828 case ALC_OUT_OF_MEMORY:
1829 value = alcErrOutOfMemory;
1830 break;
1832 case ALC_DEVICE_SPECIFIER:
1833 if(VerifyDevice(pDevice))
1835 value = pDevice->szDeviceName;
1836 ALCdevice_DecRef(pDevice);
1838 else
1840 ProbeDeviceList();
1841 value = alcDeviceList;
1843 break;
1845 case ALC_ALL_DEVICES_SPECIFIER:
1846 ProbeAllDeviceList();
1847 value = alcAllDeviceList;
1848 break;
1850 case ALC_CAPTURE_DEVICE_SPECIFIER:
1851 if(VerifyDevice(pDevice))
1853 value = pDevice->szDeviceName;
1854 ALCdevice_DecRef(pDevice);
1856 else
1858 ProbeCaptureDeviceList();
1859 value = alcCaptureDeviceList;
1861 break;
1863 /* Default devices are always first in the list */
1864 case ALC_DEFAULT_DEVICE_SPECIFIER:
1865 if(!alcDeviceList)
1866 ProbeDeviceList();
1868 pDevice = VerifyDevice(pDevice);
1870 free(alcDefaultDeviceSpecifier);
1871 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1872 if(!alcDefaultDeviceSpecifier)
1873 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1875 value = alcDefaultDeviceSpecifier;
1876 if(pDevice) ALCdevice_DecRef(pDevice);
1877 break;
1879 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1880 if(!alcAllDeviceList)
1881 ProbeAllDeviceList();
1883 pDevice = VerifyDevice(pDevice);
1885 free(alcDefaultAllDeviceSpecifier);
1886 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1887 alcAllDeviceList : "");
1888 if(!alcDefaultAllDeviceSpecifier)
1889 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1891 value = alcDefaultAllDeviceSpecifier;
1892 if(pDevice) ALCdevice_DecRef(pDevice);
1893 break;
1895 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1896 if(!alcCaptureDeviceList)
1897 ProbeCaptureDeviceList();
1899 pDevice = VerifyDevice(pDevice);
1901 free(alcCaptureDefaultDeviceSpecifier);
1902 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1903 alcCaptureDeviceList : "");
1904 if(!alcCaptureDefaultDeviceSpecifier)
1905 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1907 value = alcCaptureDefaultDeviceSpecifier;
1908 if(pDevice) ALCdevice_DecRef(pDevice);
1909 break;
1911 case ALC_EXTENSIONS:
1912 if(!VerifyDevice(pDevice))
1913 value = alcNoDeviceExtList;
1914 else
1916 value = alcExtensionList;
1917 ALCdevice_DecRef(pDevice);
1919 break;
1921 default:
1922 pDevice = VerifyDevice(pDevice);
1923 alcSetError(pDevice, ALC_INVALID_ENUM);
1924 if(pDevice) ALCdevice_DecRef(pDevice);
1925 break;
1928 return value;
1932 /* alcGetIntegerv
1934 * Returns information about the Device and the version of Open AL
1936 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1938 device = VerifyDevice(device);
1940 if(size == 0 || data == NULL)
1942 alcSetError(device, ALC_INVALID_VALUE);
1943 if(device) ALCdevice_DecRef(device);
1944 return;
1947 if(!device)
1949 switch(param)
1951 case ALC_MAJOR_VERSION:
1952 *data = alcMajorVersion;
1953 break;
1954 case ALC_MINOR_VERSION:
1955 *data = alcMinorVersion;
1956 break;
1958 case ALC_ATTRIBUTES_SIZE:
1959 case ALC_ALL_ATTRIBUTES:
1960 case ALC_FREQUENCY:
1961 case ALC_REFRESH:
1962 case ALC_SYNC:
1963 case ALC_MONO_SOURCES:
1964 case ALC_STEREO_SOURCES:
1965 case ALC_CAPTURE_SAMPLES:
1966 case ALC_FORMAT_CHANNELS_SOFT:
1967 case ALC_FORMAT_TYPE_SOFT:
1968 alcSetError(NULL, ALC_INVALID_DEVICE);
1969 break;
1971 default:
1972 alcSetError(NULL, ALC_INVALID_ENUM);
1973 break;
1976 else if(device->IsCaptureDevice)
1978 switch(param)
1980 case ALC_CAPTURE_SAMPLES:
1981 LockDevice(device);
1982 *data = ALCdevice_AvailableSamples(device);
1983 UnlockDevice(device);
1984 break;
1986 case ALC_CONNECTED:
1987 *data = device->Connected;
1988 break;
1990 default:
1991 alcSetError(device, ALC_INVALID_ENUM);
1992 break;
1995 else /* render device */
1997 switch(param)
1999 case ALC_MAJOR_VERSION:
2000 *data = alcMajorVersion;
2001 break;
2003 case ALC_MINOR_VERSION:
2004 *data = alcMinorVersion;
2005 break;
2007 case ALC_EFX_MAJOR_VERSION:
2008 *data = alcEFXMajorVersion;
2009 break;
2011 case ALC_EFX_MINOR_VERSION:
2012 *data = alcEFXMinorVersion;
2013 break;
2015 case ALC_ATTRIBUTES_SIZE:
2016 *data = 13;
2017 break;
2019 case ALC_ALL_ATTRIBUTES:
2020 if(size < 13)
2021 alcSetError(device, ALC_INVALID_VALUE);
2022 else
2024 int i = 0;
2026 data[i++] = ALC_FREQUENCY;
2027 data[i++] = device->Frequency;
2029 if(!device->IsLoopbackDevice)
2031 data[i++] = ALC_REFRESH;
2032 data[i++] = device->Frequency / device->UpdateSize;
2034 data[i++] = ALC_SYNC;
2035 data[i++] = ALC_FALSE;
2037 else
2039 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2040 data[i++] = device->FmtChans;
2042 data[i++] = ALC_FORMAT_TYPE_SOFT;
2043 data[i++] = device->FmtType;
2046 data[i++] = ALC_MONO_SOURCES;
2047 data[i++] = device->NumMonoSources;
2049 data[i++] = ALC_STEREO_SOURCES;
2050 data[i++] = device->NumStereoSources;
2052 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2053 data[i++] = device->NumAuxSends;
2055 data[i++] = 0;
2057 break;
2059 case ALC_FREQUENCY:
2060 *data = device->Frequency;
2061 break;
2063 case ALC_REFRESH:
2064 if(device->IsLoopbackDevice)
2065 alcSetError(device, ALC_INVALID_DEVICE);
2066 else
2067 *data = device->Frequency / device->UpdateSize;
2068 break;
2070 case ALC_SYNC:
2071 if(device->IsLoopbackDevice)
2072 alcSetError(device, ALC_INVALID_DEVICE);
2073 else
2074 *data = ALC_FALSE;
2075 break;
2077 case ALC_FORMAT_CHANNELS_SOFT:
2078 if(!device->IsLoopbackDevice)
2079 alcSetError(device, ALC_INVALID_DEVICE);
2080 else
2081 *data = device->FmtChans;
2082 break;
2084 case ALC_FORMAT_TYPE_SOFT:
2085 if(!device->IsLoopbackDevice)
2086 alcSetError(device, ALC_INVALID_DEVICE);
2087 else
2088 *data = device->FmtType;
2089 break;
2091 case ALC_MONO_SOURCES:
2092 *data = device->NumMonoSources;
2093 break;
2095 case ALC_STEREO_SOURCES:
2096 *data = device->NumStereoSources;
2097 break;
2099 case ALC_MAX_AUXILIARY_SENDS:
2100 *data = device->NumAuxSends;
2101 break;
2103 case ALC_CONNECTED:
2104 *data = device->Connected;
2105 break;
2107 default:
2108 alcSetError(device, ALC_INVALID_ENUM);
2109 break;
2112 if(device)
2113 ALCdevice_DecRef(device);
2117 /* alcIsExtensionPresent
2119 * Determines if there is support for a particular extension
2121 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2123 ALCboolean bResult = ALC_FALSE;
2125 device = VerifyDevice(device);
2127 if(!extName)
2128 alcSetError(device, ALC_INVALID_VALUE);
2129 else
2131 size_t len = strlen(extName);
2132 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2133 while(ptr && *ptr)
2135 if(strncasecmp(ptr, extName, len) == 0 &&
2136 (ptr[len] == '\0' || isspace(ptr[len])))
2138 bResult = ALC_TRUE;
2139 break;
2141 if((ptr=strchr(ptr, ' ')) != NULL)
2143 do {
2144 ++ptr;
2145 } while(isspace(*ptr));
2149 if(device)
2150 ALCdevice_DecRef(device);
2151 return bResult;
2155 /* alcGetProcAddress
2157 * Retrieves the function address for a particular extension function
2159 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2161 ALCvoid *ptr = NULL;
2163 device = VerifyDevice(device);
2165 if(!funcName)
2166 alcSetError(device, ALC_INVALID_VALUE);
2167 else
2169 ALsizei i = 0;
2170 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2171 i++;
2172 ptr = alcFunctions[i].address;
2174 if(device)
2175 ALCdevice_DecRef(device);
2176 return ptr;
2180 /* alcGetEnumValue
2182 * Get the value for a particular ALC Enumerated Value
2184 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2186 ALCenum val = 0;
2188 device = VerifyDevice(device);
2190 if(!enumName)
2191 alcSetError(device, ALC_INVALID_VALUE);
2192 else
2194 ALsizei i = 0;
2195 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2196 i++;
2197 val = enumeration[i].value;
2199 if(device)
2200 ALCdevice_DecRef(device);
2201 return val;
2205 /* alcCreateContext
2207 * Create and attach a Context to a particular Device.
2209 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2211 ALCcontext *ALContext;
2212 ALCenum err;
2214 LockLists();
2215 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2217 UnlockLists();
2218 alcSetError(device, ALC_INVALID_DEVICE);
2219 if(device) ALCdevice_DecRef(device);
2220 return NULL;
2223 /* Reset Context Last Error code */
2224 device->LastError = ALC_NO_ERROR;
2226 if((err=UpdateDeviceParams(device, attrList)) != ALC_NO_ERROR)
2228 UnlockLists();
2229 alcSetError(device, err);
2230 if(err == ALC_INVALID_DEVICE)
2231 aluHandleDisconnect(device);
2232 ALCdevice_DecRef(device);
2233 return NULL;
2236 ALContext = calloc(1, sizeof(ALCcontext));
2237 if(ALContext)
2239 ALContext->ref = 1;
2241 ALContext->MaxActiveSources = 256;
2242 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2243 ALContext->MaxActiveSources);
2245 if(!ALContext || !ALContext->ActiveSources)
2247 if(!device->ContextList)
2249 ALCdevice_StopPlayback(device);
2250 device->Flags &= ~DEVICE_RUNNING;
2252 UnlockLists();
2254 free(ALContext);
2255 ALContext = NULL;
2257 alcSetError(device, ALC_OUT_OF_MEMORY);
2258 ALCdevice_DecRef(device);
2259 return NULL;
2262 ALContext->Device = device;
2263 ALCdevice_IncRef(device);
2264 InitContext(ALContext);
2266 do {
2267 ALContext->next = device->ContextList;
2268 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2269 UnlockLists();
2271 if(device->DefaultSlot)
2272 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2273 ALContext->LastError = AL_NO_ERROR;
2275 ALCdevice_DecRef(device);
2277 TRACE("Created context %p\n", ALContext);
2278 return ALContext;
2281 /* alcDestroyContext
2283 * Remove a Context
2285 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2287 ALCdevice *Device;
2289 LockLists();
2290 /* alcGetContextsDevice sets an error for invalid contexts */
2291 Device = alcGetContextsDevice(context);
2292 if(Device)
2294 ReleaseContext(context, Device);
2295 if(!Device->ContextList)
2297 ALCdevice_StopPlayback(Device);
2298 Device->Flags &= ~DEVICE_RUNNING;
2301 UnlockLists();
2305 /* alcGetCurrentContext
2307 * Returns the currently active Context
2309 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2311 ALCcontext *Context;
2313 Context = pthread_getspecific(LocalContext);
2314 if(!Context) Context = GlobalContext;
2316 return Context;
2319 /* alcGetThreadContext
2321 * Returns the currently active thread-local Context
2323 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2325 ALCcontext *Context;
2326 Context = pthread_getspecific(LocalContext);
2327 return Context;
2331 /* alcMakeContextCurrent
2333 * Makes the given Context the active Context
2335 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2337 /* context must be a valid Context or NULL */
2338 if(context && !(context=VerifyContext(context)))
2340 alcSetError(NULL, ALC_INVALID_CONTEXT);
2341 return ALC_FALSE;
2343 /* context's reference count is already incremented */
2344 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2345 if(context) ALCcontext_DecRef(context);
2347 if((context=pthread_getspecific(LocalContext)) != NULL)
2349 pthread_setspecific(LocalContext, NULL);
2350 ALCcontext_DecRef(context);
2353 return ALC_TRUE;
2356 /* alcSetThreadContext
2358 * Makes the given Context the active Context for the current thread
2360 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2362 ALCcontext *old;
2364 /* context must be a valid Context or NULL */
2365 if(context && !(context=VerifyContext(context)))
2367 alcSetError(NULL, ALC_INVALID_CONTEXT);
2368 return ALC_FALSE;
2370 /* context's reference count is already incremented */
2371 old = pthread_getspecific(LocalContext);
2372 pthread_setspecific(LocalContext, context);
2373 if(old) ALCcontext_DecRef(old);
2375 return ALC_TRUE;
2379 /* alcGetContextsDevice
2381 * Returns the Device that a particular Context is attached to
2383 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2385 ALCdevice *Device;
2387 if(!(Context=VerifyContext(Context)))
2389 alcSetError(NULL, ALC_INVALID_CONTEXT);
2390 return NULL;
2392 Device = Context->Device;
2393 ALCcontext_DecRef(Context);
2395 return Device;
2399 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2401 static const struct {
2402 const char name[32];
2403 enum DevFmtChannels channels;
2404 enum DevFmtType type;
2405 } formats[] = {
2406 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2407 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2408 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2409 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2410 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2411 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2413 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2414 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2415 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2416 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2417 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2418 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2420 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2421 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2422 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2423 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2424 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2425 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2427 size_t i;
2429 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2431 if(strcasecmp(str, formats[i].name) == 0)
2433 *chans = formats[i].channels;
2434 *type = formats[i].type;
2435 return;
2439 ERR("Unknown format: \"%s\"\n", str);
2440 *chans = DevFmtStereo;
2441 *type = DevFmtShort;
2444 /* alcOpenDevice
2446 * Open the Device specified.
2448 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2450 const ALCchar *fmt;
2451 ALCdevice *device;
2452 ALCenum err;
2454 DO_INITCONFIG();
2456 if(!PlaybackBackend.name)
2458 alcSetError(NULL, ALC_INVALID_VALUE);
2459 return NULL;
2462 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2463 deviceName = NULL;
2465 device = calloc(1, sizeof(ALCdevice)+sizeof(ALeffectslot));
2466 if(!device)
2468 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2469 return NULL;
2472 //Validate device
2473 device->Funcs = &PlaybackBackend.Funcs;
2474 device->ref = 1;
2475 device->Connected = ALC_TRUE;
2476 device->IsCaptureDevice = AL_FALSE;
2477 device->IsLoopbackDevice = AL_FALSE;
2478 InitializeCriticalSection(&device->Mutex);
2479 device->LastError = ALC_NO_ERROR;
2481 device->Flags = 0;
2482 device->Bs2b = NULL;
2483 device->Bs2bLevel = 0;
2484 device->szDeviceName = NULL;
2486 device->ContextList = NULL;
2488 device->MaxNoOfSources = 256;
2489 device->AuxiliaryEffectSlotMax = 4;
2490 device->NumAuxSends = MAX_SENDS;
2492 InitUIntMap(&device->BufferMap, ~0);
2493 InitUIntMap(&device->EffectMap, ~0);
2494 InitUIntMap(&device->FilterMap, ~0);
2496 //Set output format
2497 device->NumUpdates = 4;
2498 device->UpdateSize = 1024;
2500 device->Frequency = DEFAULT_OUTPUT_RATE;
2501 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2502 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2503 device->Frequency = maxu(device->Frequency, 8000);
2505 fmt = "AL_FORMAT_STEREO32";
2506 if(ConfigValueStr(NULL, "format", &fmt))
2507 device->Flags |= DEVICE_CHANNELS_REQUEST;
2508 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2510 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2511 if(device->NumUpdates < 2) device->NumUpdates = 4;
2513 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2514 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2516 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2517 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2519 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2520 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2522 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2523 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2525 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2527 device->NumStereoSources = 1;
2528 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2530 device->DefaultSlot = (ALeffectslot*)(device+1);
2531 if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR)
2532 device->DefaultSlot = NULL;
2534 // Find a playback device to open
2535 LockLists();
2536 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2538 UnlockLists();
2539 DeleteCriticalSection(&device->Mutex);
2540 free(device);
2541 alcSetError(NULL, err);
2542 return NULL;
2544 UnlockLists();
2546 do {
2547 device->next = DeviceList;
2548 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2550 TRACE("Created device %p\n", device);
2551 return device;
2554 /* alcCloseDevice
2556 * Close the specified Device
2558 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2560 ALCdevice *volatile*list;
2561 ALCcontext *ctx;
2563 LockLists();
2564 list = &DeviceList;
2565 while(*list && *list != pDevice)
2566 list = &(*list)->next;
2568 if(!*list || (*list)->IsCaptureDevice)
2570 alcSetError(*list, ALC_INVALID_DEVICE);
2571 UnlockLists();
2572 return ALC_FALSE;
2575 *list = (*list)->next;
2576 UnlockLists();
2578 if((ctx=pDevice->ContextList) != NULL)
2580 do {
2581 WARN("Releasing context %p\n", ctx);
2582 ReleaseContext(ctx, pDevice);
2583 } while((ctx=pDevice->ContextList) != NULL);
2584 ALCdevice_StopPlayback(pDevice);
2585 pDevice->Flags &= ~DEVICE_RUNNING;
2587 ALCdevice_ClosePlayback(pDevice);
2589 ALCdevice_DecRef(pDevice);
2591 return ALC_TRUE;
2595 /* alcLoopbackOpenDeviceSOFT
2597 * Open a loopback device, for manual rendering.
2599 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2601 ALCdevice *device;
2603 DO_INITCONFIG();
2605 device = calloc(1, sizeof(ALCdevice));
2606 if(!device)
2608 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2609 return NULL;
2612 //Validate device
2613 device->Funcs = &BackendLoopback.Funcs;
2614 device->ref = 1;
2615 device->Connected = ALC_TRUE;
2616 device->IsCaptureDevice = AL_FALSE;
2617 device->IsLoopbackDevice = AL_TRUE;
2618 InitializeCriticalSection(&device->Mutex);
2619 device->LastError = ALC_NO_ERROR;
2621 device->Flags = 0;
2622 device->Bs2b = NULL;
2623 device->Bs2bLevel = 0;
2624 device->szDeviceName = NULL;
2626 device->ContextList = NULL;
2628 device->MaxNoOfSources = 256;
2629 device->AuxiliaryEffectSlotMax = 4;
2630 device->NumAuxSends = MAX_SENDS;
2632 InitUIntMap(&device->BufferMap, ~0);
2633 InitUIntMap(&device->EffectMap, ~0);
2634 InitUIntMap(&device->FilterMap, ~0);
2636 //Set output format
2637 device->NumUpdates = 0;
2638 device->UpdateSize = 0;
2640 device->Frequency = 44100;
2641 device->FmtChans = DevFmtStereo;
2642 device->FmtType = DevFmtShort;
2644 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2645 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2647 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2648 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2650 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2651 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2653 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2655 device->NumStereoSources = 1;
2656 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2658 // Open the "backend"
2659 ALCdevice_OpenPlayback(device, "Loopback");
2660 do {
2661 device->next = DeviceList;
2662 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2664 TRACE("Created device %p\n", device);
2665 return device;
2668 /* alcIsRenderFormatSupportedSOFT
2670 * Determines if the loopback device supports the given format for rendering.
2672 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2674 ALCboolean ret = ALC_FALSE;
2676 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2677 alcSetError(device, ALC_INVALID_DEVICE);
2678 else if(freq <= 0)
2679 alcSetError(device, ALC_INVALID_VALUE);
2680 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2681 alcSetError(device, ALC_INVALID_ENUM);
2682 else
2684 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2685 freq >= 8000)
2686 ret = ALC_TRUE;
2688 if(device) ALCdevice_DecRef(device);
2690 return ret;
2693 /* alcRenderSamplesSOFT
2695 * Renders some samples into a buffer, using the format last set by the
2696 * attributes given to alcCreateContext.
2698 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2700 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2701 alcSetError(device, ALC_INVALID_DEVICE);
2702 else if(samples < 0 || (samples > 0 && buffer == NULL))
2703 alcSetError(device, ALC_INVALID_VALUE);
2704 else
2705 aluMixData(device, buffer, samples);
2706 if(device) ALCdevice_DecRef(device);
2710 static void ReleaseALC(void)
2712 ALCdevice *dev;
2714 free(alcDeviceList); alcDeviceList = NULL;
2715 alcDeviceListSize = 0;
2716 free(alcAllDeviceList); alcAllDeviceList = NULL;
2717 alcAllDeviceListSize = 0;
2718 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2719 alcCaptureDeviceListSize = 0;
2721 free(alcDefaultDeviceSpecifier);
2722 alcDefaultDeviceSpecifier = NULL;
2723 free(alcDefaultAllDeviceSpecifier);
2724 alcDefaultAllDeviceSpecifier = NULL;
2725 free(alcCaptureDefaultDeviceSpecifier);
2726 alcCaptureDefaultDeviceSpecifier = NULL;
2728 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2730 ALCuint num = 0;
2731 do {
2732 num++;
2733 } while((dev=dev->next) != NULL);
2734 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2738 ///////////////////////////////////////////////////////