Rename the ALEffect_ macros to ALeffectState_ to reflect what they work on
[openal-soft/android.git] / Alc / ALc.c
blob7d9793aafb5260dc3cf756785d57c96b8e0234a5
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", ALC_MONO },
295 { "ALC_STEREO", ALC_STEREO },
296 { "ALC_QUAD", ALC_QUAD },
297 { "ALC_5POINT1", ALC_5POINT1 },
298 { "ALC_6POINT1", ALC_6POINT1 },
299 { "ALC_7POINT1", ALC_7POINT1 },
301 // Buffer Sample Types
302 { "ALC_BYTE", ALC_BYTE },
303 { "ALC_UNSIGNED_BYTE", ALC_UNSIGNED_BYTE },
304 { "ALC_SHORT", ALC_SHORT },
305 { "ALC_UNSIGNED_SHORT", ALC_UNSIGNED_SHORT },
306 { "ALC_INT", ALC_INT },
307 { "ALC_UNSIGNED_INT", ALC_UNSIGNED_INT },
308 { "ALC_FLOAT", ALC_FLOAT },
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_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 AL_EXT_IMA4 "
377 "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_SOFTX_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 // Cone scalar
397 ALdouble ConeScale = 0.5;
399 // Localized Z scalar for mono sources
400 ALdouble ZScale = 1.0;
402 /* Flag to trap ALC device errors */
403 static ALCboolean TrapALCError = ALC_FALSE;
405 /* One-time configuration init control */
406 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
408 ///////////////////////////////////////////////////////
411 ///////////////////////////////////////////////////////
412 // ALC Related helper functions
413 static void ReleaseALC(ALCboolean doclose);
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 #ifndef AL_LIBTYPE_STATIC
425 UIntMap TlsDestructor;
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.0;
501 str = getenv("__ALSOFT_REVERSE_Z");
502 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
503 ZScale = -1.0;
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(ALC_FALSE);
531 FreeALConfig();
533 ThunkExit();
534 DeleteCriticalSection(&ListLock);
535 pthread_key_delete(LocalContext);
537 if(LogFile != stderr)
538 fclose(LogFile);
539 LogFile = NULL;
542 static void alc_deinit(void)
544 int i;
546 ReleaseALC(ALC_TRUE);
548 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
549 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
551 for(i = 0;BackendList[i].Deinit;i++)
552 BackendList[i].Deinit();
553 BackendLoopback.Deinit();
555 alc_deinit_safe();
558 static void alc_initconfig(void)
560 const char *devs, *str;
561 int i, n;
563 str = getenv("ALSOFT_LOGLEVEL");
564 if(str)
566 long lvl = strtol(str, NULL, 0);
567 if(lvl >= NoLog && lvl <= LogTrace)
568 LogLevel = lvl;
571 str = getenv("ALSOFT_LOGFILE");
572 if(str && str[0])
574 FILE *logfile = fopen(str, "wat");
575 if(logfile) LogFile = logfile;
576 else ERR("Failed to open log file '%s'\n", str);
579 ReadALConfig();
581 InitHrtf();
583 #ifdef _WIN32
584 RTPrioLevel = GetConfigValueInt(NULL, "rt-prio", 1);
585 #else
586 RTPrioLevel = GetConfigValueInt(NULL, "rt-prio", 0);
587 #endif
589 DefaultResampler = GetConfigValueInt(NULL, "resampler", RESAMPLER_DEFAULT);
590 if(DefaultResampler >= RESAMPLER_MAX || DefaultResampler <= RESAMPLER_MIN)
591 DefaultResampler = RESAMPLER_DEFAULT;
593 if(!TrapALCError)
594 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
596 if(!TrapALError)
597 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
599 ReverbBoost *= aluPow(10.0f, GetConfigValueFloat("reverb", "boost", 0.0f) /
600 20.0f);
601 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
603 devs = GetConfigValue(NULL, "drivers", "");
604 if(devs[0])
606 int n;
607 size_t len;
608 const char *next = devs;
609 int endlist, delitem;
611 i = 0;
612 do {
613 devs = next;
614 next = strchr(devs, ',');
616 delitem = (devs[0] == '-');
617 if(devs[0] == '-') devs++;
619 if(!devs[0] || devs[0] == ',')
621 endlist = 0;
622 continue;
624 endlist = 1;
626 len = (next ? ((size_t)(next-devs)) : strlen(devs));
627 for(n = i;BackendList[n].Init;n++)
629 if(len == strlen(BackendList[n].name) &&
630 strncmp(BackendList[n].name, devs, len) == 0)
632 if(delitem)
634 do {
635 BackendList[n] = BackendList[n+1];
636 ++n;
637 } while(BackendList[n].Init);
639 else
641 struct BackendInfo Bkp = BackendList[n];
642 while(n > i)
644 BackendList[n] = BackendList[n-1];
645 --n;
647 BackendList[n] = Bkp;
649 i++;
651 break;
654 } while(next++);
656 if(endlist)
658 BackendList[i].name = NULL;
659 BackendList[i].Init = NULL;
660 BackendList[i].Deinit = NULL;
661 BackendList[i].Probe = NULL;
665 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
667 if(!BackendList[i].Init(&BackendList[i].Funcs))
669 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
670 continue;
673 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
674 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
676 PlaybackBackend = BackendList[i];
677 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
679 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
681 CaptureBackend = BackendList[i];
682 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
685 BackendLoopback.Init(&BackendLoopback.Funcs);
687 str = GetConfigValue(NULL, "excludefx", "");
688 if(str[0])
690 size_t len;
691 const char *next = str;
693 do {
694 str = next;
695 next = strchr(str, ',');
697 if(!str[0] || next == str)
698 continue;
700 len = (next ? ((size_t)(next-str)) : strlen(str));
701 for(n = 0;EffectList[n].name;n++)
703 if(len == strlen(EffectList[n].name) &&
704 strncmp(EffectList[n].name, str, len) == 0)
705 DisabledEffects[EffectList[n].type] = AL_TRUE;
707 } while(next++);
712 static void LockLists(void)
714 EnterCriticalSection(&ListLock);
717 static void UnlockLists(void)
719 LeaveCriticalSection(&ListLock);
723 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
725 DO_INITCONFIG();
727 LockLists();
728 free(*list);
729 *list = NULL;
730 *listsize = 0;
732 if(type == CAPTURE_DEVICE_PROBE)
733 CaptureBackend.Probe(type);
734 else
735 PlaybackBackend.Probe(type);
736 UnlockLists();
739 static void ProbeDeviceList(void)
740 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
741 static void ProbeAllDeviceList(void)
742 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
743 static void ProbeCaptureDeviceList(void)
744 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
747 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
749 size_t len = strlen(name);
750 void *temp;
752 if(len == 0)
753 return;
755 temp = realloc(*List, (*ListSize) + len + 2);
756 if(!temp)
758 ERR("Realloc failed to add %s!\n", name);
759 return;
761 *List = temp;
763 memcpy((*List)+(*ListSize), name, len+1);
764 *ListSize += len+1;
765 (*List)[*ListSize] = 0;
768 #define DECL_APPEND_LIST_FUNC(type) \
769 void Append##type##List(const ALCchar *name) \
770 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
772 DECL_APPEND_LIST_FUNC(Device)
773 DECL_APPEND_LIST_FUNC(AllDevice)
774 DECL_APPEND_LIST_FUNC(CaptureDevice)
776 #undef DECL_APPEND_LIST_FUNC
779 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
780 void SetDefaultChannelOrder(ALCdevice *device)
782 switch(device->FmtChans)
784 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
785 device->DevChannels[1] = FRONT_RIGHT;
786 device->DevChannels[2] = BACK_LEFT;
787 device->DevChannels[3] = BACK_RIGHT;
788 device->DevChannels[4] = FRONT_CENTER;
789 device->DevChannels[5] = LFE;
790 return;
792 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
793 device->DevChannels[1] = FRONT_RIGHT;
794 device->DevChannels[2] = BACK_LEFT;
795 device->DevChannels[3] = BACK_RIGHT;
796 device->DevChannels[4] = FRONT_CENTER;
797 device->DevChannels[5] = LFE;
798 device->DevChannels[6] = SIDE_LEFT;
799 device->DevChannels[7] = SIDE_RIGHT;
800 return;
802 /* Same as WFX order */
803 case DevFmtMono:
804 case DevFmtStereo:
805 case DevFmtQuad:
806 case DevFmtX51Side:
807 case DevFmtX61:
808 break;
810 SetDefaultWFXChannelOrder(device);
812 /* Sets the default order used by WaveFormatEx */
813 void SetDefaultWFXChannelOrder(ALCdevice *device)
815 switch(device->FmtChans)
817 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
819 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
820 device->DevChannels[1] = FRONT_RIGHT; break;
822 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
823 device->DevChannels[1] = FRONT_RIGHT;
824 device->DevChannels[2] = BACK_LEFT;
825 device->DevChannels[3] = BACK_RIGHT; break;
827 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
828 device->DevChannels[1] = FRONT_RIGHT;
829 device->DevChannels[2] = FRONT_CENTER;
830 device->DevChannels[3] = LFE;
831 device->DevChannels[4] = BACK_LEFT;
832 device->DevChannels[5] = BACK_RIGHT; break;
834 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
835 device->DevChannels[1] = FRONT_RIGHT;
836 device->DevChannels[2] = FRONT_CENTER;
837 device->DevChannels[3] = LFE;
838 device->DevChannels[4] = SIDE_LEFT;
839 device->DevChannels[5] = SIDE_RIGHT; break;
841 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
842 device->DevChannels[1] = FRONT_RIGHT;
843 device->DevChannels[2] = FRONT_CENTER;
844 device->DevChannels[3] = LFE;
845 device->DevChannels[4] = BACK_CENTER;
846 device->DevChannels[5] = SIDE_LEFT;
847 device->DevChannels[6] = SIDE_RIGHT; break;
849 case DevFmtX71: 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;
855 device->DevChannels[6] = SIDE_LEFT;
856 device->DevChannels[7] = SIDE_RIGHT; break;
861 const ALCchar *DevFmtTypeString(enum DevFmtType type)
863 switch(type)
865 case DevFmtByte: return "Signed Byte";
866 case DevFmtUByte: return "Unsigned Byte";
867 case DevFmtShort: return "Signed Short";
868 case DevFmtUShort: return "Unsigned Short";
869 case DevFmtFloat: return "Float";
871 return "(unknown type)";
873 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
875 switch(chans)
877 case DevFmtMono: return "Mono";
878 case DevFmtStereo: return "Stereo";
879 case DevFmtQuad: return "Quadraphonic";
880 case DevFmtX51: return "5.1 Surround";
881 case DevFmtX51Side: return "5.1 Side";
882 case DevFmtX61: return "6.1 Surround";
883 case DevFmtX71: return "7.1 Surround";
885 return "(unknown channels)";
888 ALuint BytesFromDevFmt(enum DevFmtType type)
890 switch(type)
892 case DevFmtByte: return sizeof(ALbyte);
893 case DevFmtUByte: return sizeof(ALubyte);
894 case DevFmtShort: return sizeof(ALshort);
895 case DevFmtUShort: return sizeof(ALushort);
896 case DevFmtFloat: return sizeof(ALfloat);
898 return 0;
900 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
902 switch(chans)
904 case DevFmtMono: return 1;
905 case DevFmtStereo: return 2;
906 case DevFmtQuad: return 4;
907 case DevFmtX51: return 6;
908 case DevFmtX51Side: return 6;
909 case DevFmtX61: return 7;
910 case DevFmtX71: return 8;
912 return 0;
914 ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
915 enum DevFmtType *type)
917 switch(format)
919 case AL_FORMAT_MONO8:
920 *chans = DevFmtMono;
921 *type = DevFmtUByte;
922 return AL_TRUE;
923 case AL_FORMAT_MONO16:
924 *chans = DevFmtMono;
925 *type = DevFmtShort;
926 return AL_TRUE;
927 case AL_FORMAT_MONO_FLOAT32:
928 *chans = DevFmtMono;
929 *type = DevFmtFloat;
930 return AL_TRUE;
931 case AL_FORMAT_STEREO8:
932 *chans = DevFmtStereo;
933 *type = DevFmtUByte;
934 return AL_TRUE;
935 case AL_FORMAT_STEREO16:
936 *chans = DevFmtStereo;
937 *type = DevFmtShort;
938 return AL_TRUE;
939 case AL_FORMAT_STEREO_FLOAT32:
940 *chans = DevFmtStereo;
941 *type = DevFmtFloat;
942 return AL_TRUE;
943 case AL_FORMAT_QUAD8:
944 *chans = DevFmtQuad;
945 *type = DevFmtUByte;
946 return AL_TRUE;
947 case AL_FORMAT_QUAD16:
948 *chans = DevFmtQuad;
949 *type = DevFmtShort;
950 return AL_TRUE;
951 case AL_FORMAT_QUAD32:
952 *chans = DevFmtQuad;
953 *type = DevFmtFloat;
954 return AL_TRUE;
955 case AL_FORMAT_51CHN8:
956 *chans = DevFmtX51;
957 *type = DevFmtUByte;
958 return AL_TRUE;
959 case AL_FORMAT_51CHN16:
960 *chans = DevFmtX51;
961 *type = DevFmtShort;
962 return AL_TRUE;
963 case AL_FORMAT_51CHN32:
964 *chans = DevFmtX51;
965 *type = DevFmtFloat;
966 return AL_TRUE;
967 case AL_FORMAT_61CHN8:
968 *chans = DevFmtX61;
969 *type = DevFmtUByte;
970 return AL_TRUE;
971 case AL_FORMAT_61CHN16:
972 *chans = DevFmtX61;
973 *type = DevFmtShort;
974 return AL_TRUE;
975 case AL_FORMAT_61CHN32:
976 *chans = DevFmtX61;
977 *type = DevFmtFloat;
978 return AL_TRUE;
979 case AL_FORMAT_71CHN8:
980 *chans = DevFmtX71;
981 *type = DevFmtUByte;
982 return AL_TRUE;
983 case AL_FORMAT_71CHN16:
984 *chans = DevFmtX71;
985 *type = DevFmtShort;
986 return AL_TRUE;
987 case AL_FORMAT_71CHN32:
988 *chans = DevFmtX71;
989 *type = DevFmtFloat;
990 return AL_TRUE;
992 return AL_FALSE;
995 static ALCboolean IsValidALCType(ALCenum type)
997 switch(type)
999 case ALC_BYTE:
1000 case ALC_UNSIGNED_BYTE:
1001 case ALC_SHORT:
1002 case ALC_UNSIGNED_SHORT:
1003 case ALC_INT:
1004 case ALC_UNSIGNED_INT:
1005 case ALC_FLOAT:
1006 return ALC_TRUE;
1008 return ALC_FALSE;
1011 static ALCboolean IsValidALCChannels(ALCenum channels)
1013 switch(channels)
1015 case ALC_MONO:
1016 case ALC_STEREO:
1017 case ALC_QUAD:
1018 case ALC_5POINT1:
1019 case ALC_6POINT1:
1020 case ALC_7POINT1:
1021 return ALC_TRUE;
1023 return ALC_FALSE;
1027 /* UpdateDeviceParams
1029 * Updates device parameters according to the attribute list (caller is
1030 * responsible for holding the list lock).
1032 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1034 ALCcontext *context;
1035 ALuint i;
1037 // Check for attributes
1038 if(attrList && attrList[0])
1040 ALCuint freq, numMono, numStereo, numSends;
1041 enum DevFmtChannels schans;
1042 enum DevFmtType stype;
1043 ALuint attrIdx;
1045 // If a context is already running on the device, stop playback so the
1046 // device attributes can be updated
1047 if((device->Flags&DEVICE_RUNNING))
1048 ALCdevice_StopPlayback(device);
1049 device->Flags &= ~DEVICE_RUNNING;
1051 freq = device->Frequency;
1052 schans = device->FmtChans;
1053 stype = device->FmtType;
1054 numMono = device->NumMonoSources;
1055 numStereo = device->NumStereoSources;
1056 numSends = device->NumAuxSends;
1058 freq = GetConfigValueInt(NULL, "frequency", freq);
1059 if(freq < 8000) freq = 8000;
1061 attrIdx = 0;
1062 while(attrList[attrIdx])
1064 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1065 device->IsLoopbackDevice)
1067 ALCint val = attrList[attrIdx + 1];
1068 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1070 alcSetError(device, ALC_INVALID_VALUE);
1071 return ALC_FALSE;
1073 schans = val;
1076 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1077 device->IsLoopbackDevice)
1079 ALCint val = attrList[attrIdx + 1];
1080 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1082 alcSetError(device, ALC_INVALID_VALUE);
1083 return ALC_FALSE;
1085 stype = val;
1088 if(attrList[attrIdx] == ALC_FREQUENCY)
1090 if(device->IsLoopbackDevice)
1092 freq = attrList[attrIdx + 1];
1093 if(freq < 8000)
1095 alcSetError(device, ALC_INVALID_VALUE);
1096 return ALC_FALSE;
1099 else if(!ConfigValueExists(NULL, "frequency"))
1101 freq = attrList[attrIdx + 1];
1102 if(freq < 8000) freq = 8000;
1103 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1107 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1109 numStereo = attrList[attrIdx + 1];
1110 if(numStereo > device->MaxNoOfSources)
1111 numStereo = device->MaxNoOfSources;
1113 numMono = device->MaxNoOfSources - numStereo;
1116 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS &&
1117 !ConfigValueExists(NULL, "sends"))
1119 numSends = attrList[attrIdx + 1];
1120 if(numSends > MAX_SENDS)
1121 numSends = MAX_SENDS;
1124 attrIdx += 2;
1127 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1128 device->Frequency;
1130 device->Frequency = freq;
1131 device->FmtChans = schans;
1132 device->FmtType = stype;
1133 device->NumMonoSources = numMono;
1134 device->NumStereoSources = numStereo;
1135 device->NumAuxSends = numSends;
1138 if((device->Flags&DEVICE_RUNNING))
1139 return ALC_TRUE;
1141 LockDevice(device);
1142 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1143 DevFmtChannelsString(device->FmtChans),
1144 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1145 DevFmtTypeString(device->FmtType), device->Frequency,
1146 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1147 device->UpdateSize, device->NumUpdates);
1148 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1150 UnlockDevice(device);
1151 return ALC_FALSE;
1153 device->Flags |= DEVICE_RUNNING;
1154 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1155 DevFmtChannelsString(device->FmtChans),
1156 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1157 DevFmtTypeString(device->FmtType), device->Frequency,
1158 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1159 device->UpdateSize, device->NumUpdates);
1161 aluInitPanning(device);
1163 for(i = 0;i < MAXCHANNELS;i++)
1165 device->ClickRemoval[i] = 0.0f;
1166 device->PendingClicks[i] = 0.0f;
1169 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1170 device->Flags |= DEVICE_USE_HRTF;
1171 if((device->Flags&DEVICE_USE_HRTF) && !IsHrtfCompatible(device))
1172 device->Flags &= ~DEVICE_USE_HRTF;
1173 TRACE("HRTF %s\n", (device->Flags&DEVICE_USE_HRTF)?"enabled":"disabled");
1175 if(!(device->Flags&DEVICE_USE_HRTF) && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1177 if(!device->Bs2b)
1179 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1180 bs2b_clear(device->Bs2b);
1182 bs2b_set_srate(device->Bs2b, device->Frequency);
1183 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1184 TRACE("BS2B level %d\n", device->Bs2bLevel);
1186 else
1188 free(device->Bs2b);
1189 device->Bs2b = NULL;
1190 TRACE("BS2B disabled\n");
1193 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1194 switch(device->FmtChans)
1196 case DevFmtMono:
1197 case DevFmtStereo:
1198 break;
1199 case DevFmtQuad:
1200 case DevFmtX51:
1201 case DevFmtX51Side:
1202 case DevFmtX61:
1203 case DevFmtX71:
1204 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1205 device->Flags |= DEVICE_DUPLICATE_STEREO;
1206 break;
1208 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1210 context = device->ContextList;
1211 while(context)
1213 ALsizei pos;
1215 context->UpdateSources = AL_FALSE;
1216 LockUIntMapRead(&context->EffectSlotMap);
1217 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1219 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1221 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1223 UnlockUIntMapRead(&context->EffectSlotMap);
1224 UnlockDevice(device);
1225 ALCdevice_StopPlayback(device);
1226 device->Flags &= ~DEVICE_RUNNING;
1227 return ALC_FALSE;
1229 slot->NeedsUpdate = AL_FALSE;
1230 ALeffectState_Update(slot->EffectState, context, slot);
1232 UnlockUIntMapRead(&context->EffectSlotMap);
1234 LockUIntMapRead(&context->SourceMap);
1235 for(pos = 0;pos < context->SourceMap.size;pos++)
1237 ALsource *source = context->SourceMap.array[pos].value;
1238 ALuint s = device->NumAuxSends;
1239 while(s < MAX_SENDS)
1241 if(source->Send[s].Slot)
1242 DecrementRef(&source->Send[s].Slot->ref);
1243 source->Send[s].Slot = NULL;
1244 source->Send[s].WetGain = 1.0f;
1245 source->Send[s].WetGainHF = 1.0f;
1246 s++;
1248 source->NeedsUpdate = AL_FALSE;
1249 ALsource_Update(source, context);
1251 UnlockUIntMapRead(&context->SourceMap);
1253 context = context->next;
1255 UnlockDevice(device);
1257 return ALC_TRUE;
1260 /* FreeDevice
1262 * Frees the device structure, and destroys any objects the app failed to
1263 * delete. Called once there's no more references on the device.
1265 static ALCvoid FreeDevice(ALCdevice *device)
1267 TRACE("%p\n", device);
1269 if(device->BufferMap.size > 0)
1271 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1272 ReleaseALBuffers(device);
1274 ResetUIntMap(&device->BufferMap);
1276 if(device->EffectMap.size > 0)
1278 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1279 ReleaseALEffects(device);
1281 ResetUIntMap(&device->EffectMap);
1283 if(device->FilterMap.size > 0)
1285 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1286 ReleaseALFilters(device);
1288 ResetUIntMap(&device->FilterMap);
1290 free(device->Bs2b);
1291 device->Bs2b = NULL;
1293 free(device->szDeviceName);
1294 device->szDeviceName = NULL;
1296 DeleteCriticalSection(&device->Mutex);
1298 free(device);
1302 void ALCdevice_IncRef(ALCdevice *device)
1304 RefCount ref;
1305 ref = IncrementRef(&device->ref);
1306 TRACE("%p increasing refcount to %u\n", device, ref);
1309 void ALCdevice_DecRef(ALCdevice *device)
1311 RefCount ref;
1312 ref = DecrementRef(&device->ref);
1313 TRACE("%p decreasing refcount to %u\n", device, ref);
1314 if(ref == 0) FreeDevice(device);
1317 /* VerifyDevice
1319 * Checks if the device handle is valid, and increments its ref count if so.
1321 static ALCdevice *VerifyDevice(ALCdevice *device)
1323 ALCdevice *tmpDevice;
1325 if(!device)
1326 return NULL;
1328 LockLists();
1329 tmpDevice = DeviceList;
1330 while(tmpDevice && tmpDevice != device)
1331 tmpDevice = tmpDevice->next;
1333 if(tmpDevice)
1334 ALCdevice_IncRef(tmpDevice);
1335 UnlockLists();
1336 return tmpDevice;
1340 /* alcSetError
1342 * Stores the latest ALC Error
1344 ALCvoid alcSetError(ALCdevice *device, ALCenum errorCode)
1346 if(TrapALCError)
1348 #ifdef _WIN32
1349 /* Safely catch a breakpoint exception that wasn't caught by a debugger */
1350 __try {
1351 DebugBreak();
1352 } __except((GetExceptionCode()==EXCEPTION_BREAKPOINT) ?
1353 EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
1355 #elif defined(SIGTRAP)
1356 kill(getpid(), SIGTRAP);
1357 #endif
1360 if(device)
1361 device->LastError = errorCode;
1362 else
1363 g_eLastNullDeviceError = errorCode;
1367 ALCvoid LockDevice(ALCdevice *device)
1369 EnterCriticalSection(&device->Mutex);
1372 ALCvoid UnlockDevice(ALCdevice *device)
1374 LeaveCriticalSection(&device->Mutex);
1378 /* InitContext
1380 * Initializes context variables
1382 static ALvoid InitContext(ALCcontext *pContext)
1384 //Initialise listener
1385 pContext->Listener.Gain = 1.0f;
1386 pContext->Listener.MetersPerUnit = 1.0f;
1387 pContext->Listener.Position[0] = 0.0f;
1388 pContext->Listener.Position[1] = 0.0f;
1389 pContext->Listener.Position[2] = 0.0f;
1390 pContext->Listener.Velocity[0] = 0.0f;
1391 pContext->Listener.Velocity[1] = 0.0f;
1392 pContext->Listener.Velocity[2] = 0.0f;
1393 pContext->Listener.Forward[0] = 0.0f;
1394 pContext->Listener.Forward[1] = 0.0f;
1395 pContext->Listener.Forward[2] = -1.0f;
1396 pContext->Listener.Up[0] = 0.0f;
1397 pContext->Listener.Up[1] = 1.0f;
1398 pContext->Listener.Up[2] = 0.0f;
1400 //Validate pContext
1401 pContext->LastError = AL_NO_ERROR;
1402 pContext->UpdateSources = AL_FALSE;
1403 pContext->ActiveSourceCount = 0;
1404 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1405 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1407 //Set globals
1408 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1409 pContext->SourceDistanceModel = AL_FALSE;
1410 pContext->DopplerFactor = 1.0f;
1411 pContext->DopplerVelocity = 1.0f;
1412 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1413 pContext->DeferUpdates = AL_FALSE;
1415 pContext->ExtensionList = alExtList;
1419 /* FreeContext
1421 * Cleans up the context, and destroys any remaining objects the app failed to
1422 * delete. Called once there's no more references on the context.
1424 static ALCvoid FreeContext(ALCcontext *context)
1426 TRACE("%p\n", context);
1428 if(context->SourceMap.size > 0)
1430 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1431 ReleaseALSources(context);
1433 ResetUIntMap(&context->SourceMap);
1435 if(context->EffectSlotMap.size > 0)
1437 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1438 ReleaseALAuxiliaryEffectSlots(context);
1440 ResetUIntMap(&context->EffectSlotMap);
1442 context->ActiveSourceCount = 0;
1443 free(context->ActiveSources);
1444 context->ActiveSources = NULL;
1445 context->MaxActiveSources = 0;
1447 context->ActiveEffectSlotCount = 0;
1448 free(context->ActiveEffectSlots);
1449 context->ActiveEffectSlots = NULL;
1450 context->MaxActiveEffectSlots = 0;
1452 ALCdevice_DecRef(context->Device);
1453 context->Device = NULL;
1455 //Invalidate context
1456 memset(context, 0, sizeof(ALCcontext));
1457 free(context);
1460 /* ReleaseContext
1462 * Removes the context reference from the given device and removes it from
1463 * being current on the running thread or globally.
1465 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1467 ALCcontext *volatile*tmp_ctx;
1469 if(pthread_getspecific(LocalContext) == context)
1471 WARN("%p released while current on thread\n", context);
1472 pthread_setspecific(LocalContext, NULL);
1473 ALCcontext_DecRef(context);
1476 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1478 WARN("%p released while current\n", context);
1479 ALCcontext_DecRef(context);
1482 tmp_ctx = &device->ContextList;
1483 while(*tmp_ctx)
1485 if(*tmp_ctx == context)
1487 *tmp_ctx = context->next;
1488 break;
1490 tmp_ctx = &(*tmp_ctx)->next;
1493 LockDevice(device);
1494 /* Lock the device to make sure the mixer is not using the contexts in the
1495 * list before we go about deleting this one. There should be a more
1496 * efficient way of doing this. */
1497 UnlockDevice(device);
1499 ALCcontext_DecRef(context);
1502 void ALCcontext_IncRef(ALCcontext *context)
1504 RefCount ref;
1505 ref = IncrementRef(&context->ref);
1506 TRACE("%p increasing refcount to %u\n", context, ref);
1509 void ALCcontext_DecRef(ALCcontext *context)
1511 RefCount ref;
1512 ref = DecrementRef(&context->ref);
1513 TRACE("%p decreasing refcount to %u\n", context, ref);
1514 if(ref == 0) FreeContext(context);
1517 static void ReleaseThreadCtx(void *ptr)
1519 WARN("%p current for thread being destroyed\n", ptr);
1520 ALCcontext_DecRef(ptr);
1523 /* VerifyContext
1525 * Checks that the given context is valid, and increments its reference count.
1527 static ALCcontext *VerifyContext(ALCcontext *context)
1529 ALCdevice *dev;
1531 LockLists();
1532 dev = DeviceList;
1533 while(dev)
1535 ALCcontext *tmp_ctx = dev->ContextList;
1536 while(tmp_ctx)
1538 if(tmp_ctx == context)
1540 ALCcontext_IncRef(tmp_ctx);
1541 UnlockLists();
1542 return tmp_ctx;
1544 tmp_ctx = tmp_ctx->next;
1546 dev = dev->next;
1548 UnlockLists();
1550 return NULL;
1554 ALCvoid LockContext(ALCcontext *context)
1556 EnterCriticalSection(&context->Device->Mutex);
1559 ALCvoid UnlockContext(ALCcontext *context)
1561 LeaveCriticalSection(&context->Device->Mutex);
1564 /* GetContextRef
1566 * Returns the currently active context, and adds a reference without locking
1567 * it.
1569 ALCcontext *GetContextRef(void)
1571 ALCcontext *context;
1573 context = pthread_getspecific(LocalContext);
1574 if(context)
1575 ALCcontext_IncRef(context);
1576 else
1578 LockLists();
1579 context = GlobalContext;
1580 if(context)
1581 ALCcontext_IncRef(context);
1582 UnlockLists();
1585 return context;
1588 ///////////////////////////////////////////////////////
1591 ///////////////////////////////////////////////////////
1592 // ALC Functions calls
1595 // This should probably move to another c file but for now ...
1596 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1598 ALCdevice *device = NULL;
1599 ALCenum err;
1601 DO_INITCONFIG();
1603 if(!CaptureBackend.name)
1605 alcSetError(NULL, ALC_INVALID_VALUE);
1606 return NULL;
1609 if(SampleSize <= 0)
1611 alcSetError(NULL, ALC_INVALID_VALUE);
1612 return NULL;
1615 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1616 deviceName = NULL;
1618 device = calloc(1, sizeof(ALCdevice));
1619 if(!device)
1621 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1622 return NULL;
1625 //Validate device
1626 device->Funcs = &CaptureBackend.Funcs;
1627 device->ref = 1;
1628 device->Connected = ALC_TRUE;
1629 device->IsCaptureDevice = AL_TRUE;
1630 device->IsLoopbackDevice = AL_FALSE;
1631 InitializeCriticalSection(&device->Mutex);
1633 InitUIntMap(&device->BufferMap, ~0);
1634 InitUIntMap(&device->EffectMap, ~0);
1635 InitUIntMap(&device->FilterMap, ~0);
1637 device->szDeviceName = NULL;
1639 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1640 device->Frequency = frequency;
1642 device->Flags |= DEVICE_CHANNELS_REQUEST;
1643 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1645 free(device);
1646 alcSetError(NULL, ALC_INVALID_ENUM);
1647 return NULL;
1650 device->UpdateSize = SampleSize;
1651 device->NumUpdates = 1;
1653 LockLists();
1654 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1656 UnlockLists();
1657 DeleteCriticalSection(&device->Mutex);
1658 free(device);
1659 alcSetError(NULL, err);
1660 return NULL;
1662 UnlockLists();
1664 do {
1665 device->next = DeviceList;
1666 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
1668 return device;
1671 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1673 ALCdevice *volatile*list;
1675 LockLists();
1676 list = &DeviceList;
1677 while(*list && *list != pDevice)
1678 list = &(*list)->next;
1680 if(!*list || !(*list)->IsCaptureDevice)
1682 alcSetError(*list, ALC_INVALID_DEVICE);
1683 UnlockLists();
1684 return ALC_FALSE;
1687 *list = (*list)->next;
1688 UnlockLists();
1690 LockDevice(pDevice);
1691 ALCdevice_CloseCapture(pDevice);
1692 UnlockDevice(pDevice);
1694 ALCdevice_DecRef(pDevice);
1696 return ALC_TRUE;
1699 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1701 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1703 alcSetError(device, ALC_INVALID_DEVICE);
1704 if(device) ALCdevice_DecRef(device);
1705 return;
1707 LockDevice(device);
1708 if(device->Connected)
1709 ALCdevice_StartCapture(device);
1710 UnlockDevice(device);
1712 ALCdevice_DecRef(device);
1715 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1717 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1719 alcSetError(device, ALC_INVALID_DEVICE);
1720 if(device) ALCdevice_DecRef(device);
1721 return;
1723 LockDevice(device);
1724 if(device->Connected)
1725 ALCdevice_StopCapture(device);
1726 UnlockDevice(device);
1728 ALCdevice_DecRef(device);
1731 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1733 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1735 alcSetError(device, ALC_INVALID_DEVICE);
1736 if(device) ALCdevice_DecRef(device);
1737 return;
1739 LockDevice(device);
1740 ALCdevice_CaptureSamples(device, buffer, samples);
1741 UnlockDevice(device);
1743 ALCdevice_DecRef(device);
1747 alcGetError
1749 Return last ALC generated error code
1751 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1753 ALCenum errorCode;
1755 if(VerifyDevice(device))
1757 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1758 ALCdevice_DecRef(device);
1760 else
1761 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1763 return errorCode;
1767 /* alcSuspendContext
1769 * Not functional
1771 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1773 (void)Context;
1776 /* alcProcessContext
1778 * Not functional
1780 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1782 (void)Context;
1786 /* alcGetString
1788 * Returns information about the Device, and error strings
1790 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1792 const ALCchar *value = NULL;
1794 switch(param)
1796 case ALC_NO_ERROR:
1797 value = alcNoError;
1798 break;
1800 case ALC_INVALID_ENUM:
1801 value = alcErrInvalidEnum;
1802 break;
1804 case ALC_INVALID_VALUE:
1805 value = alcErrInvalidValue;
1806 break;
1808 case ALC_INVALID_DEVICE:
1809 value = alcErrInvalidDevice;
1810 break;
1812 case ALC_INVALID_CONTEXT:
1813 value = alcErrInvalidContext;
1814 break;
1816 case ALC_OUT_OF_MEMORY:
1817 value = alcErrOutOfMemory;
1818 break;
1820 case ALC_DEVICE_SPECIFIER:
1821 if(VerifyDevice(pDevice))
1823 value = pDevice->szDeviceName;
1824 ALCdevice_DecRef(pDevice);
1826 else
1828 ProbeDeviceList();
1829 value = alcDeviceList;
1831 break;
1833 case ALC_ALL_DEVICES_SPECIFIER:
1834 ProbeAllDeviceList();
1835 value = alcAllDeviceList;
1836 break;
1838 case ALC_CAPTURE_DEVICE_SPECIFIER:
1839 if(VerifyDevice(pDevice))
1841 value = pDevice->szDeviceName;
1842 ALCdevice_DecRef(pDevice);
1844 else
1846 ProbeCaptureDeviceList();
1847 value = alcCaptureDeviceList;
1849 break;
1851 /* Default devices are always first in the list */
1852 case ALC_DEFAULT_DEVICE_SPECIFIER:
1853 if(!alcDeviceList)
1854 ProbeDeviceList();
1856 pDevice = VerifyDevice(pDevice);
1858 free(alcDefaultDeviceSpecifier);
1859 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1860 if(!alcDefaultDeviceSpecifier)
1861 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1863 value = alcDefaultDeviceSpecifier;
1864 if(pDevice) ALCdevice_DecRef(pDevice);
1865 break;
1867 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1868 if(!alcAllDeviceList)
1869 ProbeAllDeviceList();
1871 pDevice = VerifyDevice(pDevice);
1873 free(alcDefaultAllDeviceSpecifier);
1874 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1875 alcAllDeviceList : "");
1876 if(!alcDefaultAllDeviceSpecifier)
1877 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1879 value = alcDefaultAllDeviceSpecifier;
1880 if(pDevice) ALCdevice_DecRef(pDevice);
1881 break;
1883 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1884 if(!alcCaptureDeviceList)
1885 ProbeCaptureDeviceList();
1887 pDevice = VerifyDevice(pDevice);
1889 free(alcCaptureDefaultDeviceSpecifier);
1890 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1891 alcCaptureDeviceList : "");
1892 if(!alcCaptureDefaultDeviceSpecifier)
1893 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1895 value = alcCaptureDefaultDeviceSpecifier;
1896 if(pDevice) ALCdevice_DecRef(pDevice);
1897 break;
1899 case ALC_EXTENSIONS:
1900 if(!VerifyDevice(pDevice))
1901 value = alcNoDeviceExtList;
1902 else
1904 value = alcExtensionList;
1905 ALCdevice_DecRef(pDevice);
1907 break;
1909 default:
1910 pDevice = VerifyDevice(pDevice);
1911 alcSetError(pDevice, ALC_INVALID_ENUM);
1912 if(pDevice) ALCdevice_DecRef(pDevice);
1913 break;
1916 return value;
1920 /* alcGetIntegerv
1922 * Returns information about the Device and the version of Open AL
1924 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1926 device = VerifyDevice(device);
1928 if(size == 0 || data == NULL)
1930 alcSetError(device, ALC_INVALID_VALUE);
1931 if(device) ALCdevice_DecRef(device);
1932 return;
1935 if(!device)
1937 switch(param)
1939 case ALC_MAJOR_VERSION:
1940 *data = alcMajorVersion;
1941 break;
1942 case ALC_MINOR_VERSION:
1943 *data = alcMinorVersion;
1944 break;
1946 case ALC_ATTRIBUTES_SIZE:
1947 case ALC_ALL_ATTRIBUTES:
1948 case ALC_FREQUENCY:
1949 case ALC_REFRESH:
1950 case ALC_SYNC:
1951 case ALC_MONO_SOURCES:
1952 case ALC_STEREO_SOURCES:
1953 case ALC_CAPTURE_SAMPLES:
1954 case ALC_FORMAT_CHANNELS_SOFT:
1955 case ALC_FORMAT_TYPE_SOFT:
1956 alcSetError(NULL, ALC_INVALID_DEVICE);
1957 break;
1959 default:
1960 alcSetError(NULL, ALC_INVALID_ENUM);
1961 break;
1964 else if(device->IsCaptureDevice)
1966 switch(param)
1968 case ALC_CAPTURE_SAMPLES:
1969 LockDevice(device);
1970 *data = ALCdevice_AvailableSamples(device);
1971 UnlockDevice(device);
1972 break;
1974 case ALC_CONNECTED:
1975 *data = device->Connected;
1976 break;
1978 default:
1979 alcSetError(device, ALC_INVALID_ENUM);
1980 break;
1983 else /* render device */
1985 switch(param)
1987 case ALC_MAJOR_VERSION:
1988 *data = alcMajorVersion;
1989 break;
1991 case ALC_MINOR_VERSION:
1992 *data = alcMinorVersion;
1993 break;
1995 case ALC_EFX_MAJOR_VERSION:
1996 *data = alcEFXMajorVersion;
1997 break;
1999 case ALC_EFX_MINOR_VERSION:
2000 *data = alcEFXMinorVersion;
2001 break;
2003 case ALC_ATTRIBUTES_SIZE:
2004 *data = 13;
2005 break;
2007 case ALC_ALL_ATTRIBUTES:
2008 if(size < 13)
2009 alcSetError(device, ALC_INVALID_VALUE);
2010 else
2012 int i = 0;
2014 data[i++] = ALC_FREQUENCY;
2015 data[i++] = device->Frequency;
2017 if(!device->IsLoopbackDevice)
2019 data[i++] = ALC_REFRESH;
2020 data[i++] = device->Frequency / device->UpdateSize;
2022 data[i++] = ALC_SYNC;
2023 data[i++] = ALC_FALSE;
2025 else
2027 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2028 data[i++] = device->FmtChans;
2030 data[i++] = ALC_FORMAT_TYPE_SOFT;
2031 data[i++] = device->FmtType;
2034 data[i++] = ALC_MONO_SOURCES;
2035 data[i++] = device->NumMonoSources;
2037 data[i++] = ALC_STEREO_SOURCES;
2038 data[i++] = device->NumStereoSources;
2040 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2041 data[i++] = device->NumAuxSends;
2043 data[i++] = 0;
2045 break;
2047 case ALC_FREQUENCY:
2048 *data = device->Frequency;
2049 break;
2051 case ALC_REFRESH:
2052 if(device->IsLoopbackDevice)
2053 alcSetError(device, ALC_INVALID_DEVICE);
2054 else
2055 *data = device->Frequency / device->UpdateSize;
2056 break;
2058 case ALC_SYNC:
2059 if(device->IsLoopbackDevice)
2060 alcSetError(device, ALC_INVALID_DEVICE);
2061 else
2062 *data = ALC_FALSE;
2063 break;
2065 case ALC_FORMAT_CHANNELS_SOFT:
2066 if(!device->IsLoopbackDevice)
2067 alcSetError(device, ALC_INVALID_DEVICE);
2068 else
2069 *data = device->FmtChans;
2070 break;
2072 case ALC_FORMAT_TYPE_SOFT:
2073 if(!device->IsLoopbackDevice)
2074 alcSetError(device, ALC_INVALID_DEVICE);
2075 else
2076 *data = device->FmtType;
2077 break;
2079 case ALC_MONO_SOURCES:
2080 *data = device->NumMonoSources;
2081 break;
2083 case ALC_STEREO_SOURCES:
2084 *data = device->NumStereoSources;
2085 break;
2087 case ALC_MAX_AUXILIARY_SENDS:
2088 *data = device->NumAuxSends;
2089 break;
2091 case ALC_CONNECTED:
2092 *data = device->Connected;
2093 break;
2095 default:
2096 alcSetError(device, ALC_INVALID_ENUM);
2097 break;
2100 if(device)
2101 ALCdevice_DecRef(device);
2105 /* alcIsExtensionPresent
2107 * Determines if there is support for a particular extension
2109 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2111 ALCboolean bResult = ALC_FALSE;
2113 device = VerifyDevice(device);
2115 if(!extName)
2116 alcSetError(device, ALC_INVALID_VALUE);
2117 else
2119 size_t len = strlen(extName);
2120 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2121 while(ptr && *ptr)
2123 if(strncasecmp(ptr, extName, len) == 0 &&
2124 (ptr[len] == '\0' || isspace(ptr[len])))
2126 bResult = ALC_TRUE;
2127 break;
2129 if((ptr=strchr(ptr, ' ')) != NULL)
2131 do {
2132 ++ptr;
2133 } while(isspace(*ptr));
2137 if(device)
2138 ALCdevice_DecRef(device);
2139 return bResult;
2143 /* alcGetProcAddress
2145 * Retrieves the function address for a particular extension function
2147 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2149 ALCvoid *ptr = NULL;
2151 device = VerifyDevice(device);
2153 if(!funcName)
2154 alcSetError(device, ALC_INVALID_VALUE);
2155 else
2157 ALsizei i = 0;
2158 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2159 i++;
2160 ptr = alcFunctions[i].address;
2162 if(device)
2163 ALCdevice_DecRef(device);
2164 return ptr;
2168 /* alcGetEnumValue
2170 * Get the value for a particular ALC Enumerated Value
2172 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2174 ALCenum val = 0;
2176 device = VerifyDevice(device);
2178 if(!enumName)
2179 alcSetError(device, ALC_INVALID_VALUE);
2180 else
2182 ALsizei i = 0;
2183 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2184 i++;
2185 val = enumeration[i].value;
2187 if(device)
2188 ALCdevice_DecRef(device);
2189 return val;
2193 /* alcCreateContext
2195 * Create and attach a Context to a particular Device.
2197 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2199 ALCcontext *ALContext;
2201 LockLists();
2202 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2204 UnlockLists();
2205 alcSetError(device, ALC_INVALID_DEVICE);
2206 if(device) ALCdevice_DecRef(device);
2207 return NULL;
2210 /* Reset Context Last Error code */
2211 device->LastError = ALC_NO_ERROR;
2213 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2215 UnlockLists();
2216 alcSetError(device, ALC_INVALID_DEVICE);
2217 aluHandleDisconnect(device);
2218 ALCdevice_DecRef(device);
2219 return NULL;
2222 ALContext = calloc(1, sizeof(ALCcontext));
2223 if(ALContext)
2225 ALContext->ref = 1;
2227 ALContext->MaxActiveSources = 256;
2228 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2229 ALContext->MaxActiveSources);
2231 if(!ALContext || !ALContext->ActiveSources)
2233 if(!device->ContextList)
2235 ALCdevice_StopPlayback(device);
2236 device->Flags &= ~DEVICE_RUNNING;
2238 UnlockLists();
2240 free(ALContext);
2241 ALContext = NULL;
2243 alcSetError(device, ALC_OUT_OF_MEMORY);
2244 ALCdevice_DecRef(device);
2245 return NULL;
2248 ALContext->Device = device;
2249 ALCdevice_IncRef(device);
2250 InitContext(ALContext);
2252 ALContext->next = device->ContextList;
2253 device->ContextList = ALContext;
2254 UnlockLists();
2256 ALCdevice_DecRef(device);
2257 return ALContext;
2260 /* alcDestroyContext
2262 * Remove a Context
2264 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2266 ALCdevice *Device;
2268 LockLists();
2269 /* alcGetContextsDevice sets an error for invalid contexts */
2270 Device = alcGetContextsDevice(context);
2271 if(Device)
2273 ReleaseContext(context, Device);
2274 if(!Device->ContextList)
2276 ALCdevice_StopPlayback(Device);
2277 Device->Flags &= ~DEVICE_RUNNING;
2280 UnlockLists();
2284 /* alcGetCurrentContext
2286 * Returns the currently active Context
2288 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2290 ALCcontext *Context;
2292 Context = pthread_getspecific(LocalContext);
2293 if(!Context) Context = GlobalContext;
2295 return Context;
2298 /* alcGetThreadContext
2300 * Returns the currently active thread-local Context
2302 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2304 ALCcontext *Context;
2305 Context = pthread_getspecific(LocalContext);
2306 return Context;
2310 /* alcMakeContextCurrent
2312 * Makes the given Context the active Context
2314 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2316 /* context must be a valid Context or NULL */
2317 if(context && !(context=VerifyContext(context)))
2319 alcSetError(NULL, ALC_INVALID_CONTEXT);
2320 return ALC_FALSE;
2322 /* context's reference count is already incremented */
2323 context = ExchangePtr((void**)&GlobalContext, context);
2324 if(context) ALCcontext_DecRef(context);
2326 if((context=pthread_getspecific(LocalContext)) != NULL)
2328 pthread_setspecific(LocalContext, NULL);
2329 ALCcontext_DecRef(context);
2332 return ALC_TRUE;
2335 /* alcSetThreadContext
2337 * Makes the given Context the active Context for the current thread
2339 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2341 ALCcontext *old;
2343 /* context must be a valid Context or NULL */
2344 if(context && !(context=VerifyContext(context)))
2346 alcSetError(NULL, ALC_INVALID_CONTEXT);
2347 return ALC_FALSE;
2349 /* context's reference count is already incremented */
2350 old = pthread_getspecific(LocalContext);
2351 pthread_setspecific(LocalContext, context);
2352 if(old) ALCcontext_DecRef(old);
2354 return ALC_TRUE;
2358 /* alcGetContextsDevice
2360 * Returns the Device that a particular Context is attached to
2362 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2364 ALCdevice *Device;
2366 if(!(Context=VerifyContext(Context)))
2368 alcSetError(NULL, ALC_INVALID_CONTEXT);
2369 return NULL;
2371 Device = Context->Device;
2372 ALCcontext_DecRef(Context);
2374 return Device;
2378 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2380 static const struct {
2381 const char name[32];
2382 enum DevFmtChannels channels;
2383 enum DevFmtType type;
2384 } formats[] = {
2385 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2386 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2387 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2388 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2389 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2390 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2392 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2393 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2394 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2395 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2396 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2397 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2399 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2400 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2401 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2402 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2403 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2404 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2406 size_t i;
2408 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2410 if(strcasecmp(str, formats[i].name) == 0)
2412 *chans = formats[i].channels;
2413 *type = formats[i].type;
2414 return;
2418 ERR("Unknown format: \"%s\"\n", str);
2419 *chans = DevFmtStereo;
2420 *type = DevFmtShort;
2423 /* alcOpenDevice
2425 * Open the Device specified.
2427 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2429 const ALCchar *fmt;
2430 ALCdevice *device;
2431 ALCenum err;
2433 DO_INITCONFIG();
2435 if(!PlaybackBackend.name)
2437 alcSetError(NULL, ALC_INVALID_VALUE);
2438 return NULL;
2441 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2442 deviceName = NULL;
2444 device = calloc(1, sizeof(ALCdevice));
2445 if(!device)
2447 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2448 return NULL;
2451 //Validate device
2452 device->Funcs = &PlaybackBackend.Funcs;
2453 device->ref = 1;
2454 device->Connected = ALC_TRUE;
2455 device->IsCaptureDevice = AL_FALSE;
2456 device->IsLoopbackDevice = AL_FALSE;
2457 InitializeCriticalSection(&device->Mutex);
2458 device->LastError = ALC_NO_ERROR;
2460 device->Flags = 0;
2461 device->Bs2b = NULL;
2462 device->szDeviceName = NULL;
2464 device->ContextList = NULL;
2466 InitUIntMap(&device->BufferMap, ~0);
2467 InitUIntMap(&device->EffectMap, ~0);
2468 InitUIntMap(&device->FilterMap, ~0);
2470 //Set output format
2471 if(ConfigValueExists(NULL, "frequency"))
2472 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2473 device->Frequency = GetConfigValueInt(NULL, "frequency", DEFAULT_OUTPUT_RATE);
2474 if(device->Frequency < 8000)
2475 device->Frequency = 8000;
2477 if(ConfigValueExists(NULL, "format"))
2478 device->Flags |= DEVICE_CHANNELS_REQUEST;
2479 fmt = GetConfigValue(NULL, "format", "AL_FORMAT_STEREO16");
2480 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2482 device->NumUpdates = GetConfigValueInt(NULL, "periods", 4);
2483 if(device->NumUpdates < 2)
2484 device->NumUpdates = 4;
2486 device->UpdateSize = GetConfigValueInt(NULL, "period_size", 1024);
2487 if(device->UpdateSize <= 0)
2488 device->UpdateSize = 1024;
2490 device->MaxNoOfSources = GetConfigValueInt(NULL, "sources", 256);
2491 if(device->MaxNoOfSources <= 0)
2492 device->MaxNoOfSources = 256;
2494 device->AuxiliaryEffectSlotMax = GetConfigValueInt(NULL, "slots", 4);
2495 if(device->AuxiliaryEffectSlotMax <= 0)
2496 device->AuxiliaryEffectSlotMax = 4;
2498 device->NumStereoSources = 1;
2499 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2501 device->NumAuxSends = GetConfigValueInt(NULL, "sends", MAX_SENDS);
2502 if(device->NumAuxSends > MAX_SENDS)
2503 device->NumAuxSends = MAX_SENDS;
2505 device->Bs2bLevel = GetConfigValueInt(NULL, "cf_level", 0);
2507 // Find a playback device to open
2508 LockLists();
2509 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2511 UnlockLists();
2512 DeleteCriticalSection(&device->Mutex);
2513 free(device);
2514 alcSetError(NULL, err);
2515 return NULL;
2517 UnlockLists();
2519 do {
2520 device->next = DeviceList;
2521 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2523 return device;
2526 /* alcCloseDevice
2528 * Close the specified Device
2530 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2532 ALCdevice *volatile*list;
2533 ALCcontext *ctx;
2535 LockLists();
2536 list = &DeviceList;
2537 while(*list && *list != pDevice)
2538 list = &(*list)->next;
2540 if(!*list || (*list)->IsCaptureDevice)
2542 alcSetError(*list, ALC_INVALID_DEVICE);
2543 UnlockLists();
2544 return ALC_FALSE;
2547 *list = (*list)->next;
2548 UnlockLists();
2550 if((ctx=pDevice->ContextList) != NULL)
2552 do {
2553 WARN("Destroying context %p\n", ctx);
2554 ReleaseContext(ctx, pDevice);
2555 } while((ctx=pDevice->ContextList) != NULL);
2556 ALCdevice_StopPlayback(pDevice);
2557 pDevice->Flags &= ~DEVICE_RUNNING;
2559 ALCdevice_ClosePlayback(pDevice);
2561 ALCdevice_DecRef(pDevice);
2563 return ALC_TRUE;
2567 /* alcLoopbackOpenDeviceSOFT
2569 * Open a loopback device, for manual rendering.
2571 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2573 ALCdevice *device;
2575 DO_INITCONFIG();
2577 device = calloc(1, sizeof(ALCdevice));
2578 if(!device)
2580 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2581 return NULL;
2584 //Validate device
2585 device->Funcs = &BackendLoopback.Funcs;
2586 device->ref = 1;
2587 device->Connected = ALC_TRUE;
2588 device->IsCaptureDevice = AL_FALSE;
2589 device->IsLoopbackDevice = AL_TRUE;
2590 InitializeCriticalSection(&device->Mutex);
2591 device->LastError = ALC_NO_ERROR;
2593 device->Flags = 0;
2594 device->Bs2b = NULL;
2595 device->szDeviceName = NULL;
2597 device->ContextList = NULL;
2599 InitUIntMap(&device->BufferMap, ~0);
2600 InitUIntMap(&device->EffectMap, ~0);
2601 InitUIntMap(&device->FilterMap, ~0);
2603 //Set output format
2604 device->Frequency = 44100;
2605 device->FmtChans = DevFmtStereo;
2606 device->FmtType = DevFmtShort;
2608 device->NumUpdates = 0;
2609 device->UpdateSize = 0;
2611 device->MaxNoOfSources = GetConfigValueInt(NULL, "sources", 256);
2612 if(device->MaxNoOfSources <= 0)
2613 device->MaxNoOfSources = 256;
2615 device->AuxiliaryEffectSlotMax = GetConfigValueInt(NULL, "slots", 4);
2616 if(device->AuxiliaryEffectSlotMax <= 0)
2617 device->AuxiliaryEffectSlotMax = 4;
2619 device->NumStereoSources = 1;
2620 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2622 device->NumAuxSends = GetConfigValueInt(NULL, "sends", MAX_SENDS);
2623 if(device->NumAuxSends > MAX_SENDS)
2624 device->NumAuxSends = MAX_SENDS;
2626 device->Bs2bLevel = GetConfigValueInt(NULL, "cf_level", 0);
2628 // Open the "backend"
2629 ALCdevice_OpenPlayback(device, "Loopback");
2630 do {
2631 device->next = DeviceList;
2632 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2633 return device;
2636 /* alcIsRenderFormatSupportedSOFT
2638 * Determines if the loopback device supports the given format for rendering.
2640 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2642 ALCboolean ret = ALC_FALSE;
2644 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2645 alcSetError(device, ALC_INVALID_DEVICE);
2646 else if(freq <= 0)
2647 alcSetError(device, ALC_INVALID_VALUE);
2648 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2649 alcSetError(device, ALC_INVALID_ENUM);
2650 else
2652 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2653 freq >= 8000)
2654 ret = ALC_TRUE;
2656 if(device) ALCdevice_DecRef(device);
2658 return ret;
2661 /* alcRenderSamplesSOFT
2663 * Renders some samples into a buffer, using the format last set by the
2664 * attributes given to alcCreateContext.
2666 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2668 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2669 alcSetError(device, ALC_INVALID_DEVICE);
2670 else if(samples < 0 || (samples > 0 && buffer == NULL))
2671 alcSetError(device, ALC_INVALID_VALUE);
2672 else
2673 aluMixData(device, buffer, samples);
2674 if(device) ALCdevice_DecRef(device);
2678 static void ReleaseALC(ALCboolean doclose)
2680 free(alcDeviceList); alcDeviceList = NULL;
2681 alcDeviceListSize = 0;
2682 free(alcAllDeviceList); alcAllDeviceList = NULL;
2683 alcAllDeviceListSize = 0;
2684 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2685 alcCaptureDeviceListSize = 0;
2687 free(alcDefaultDeviceSpecifier);
2688 alcDefaultDeviceSpecifier = NULL;
2689 free(alcDefaultAllDeviceSpecifier);
2690 alcDefaultAllDeviceSpecifier = NULL;
2691 free(alcCaptureDefaultDeviceSpecifier);
2692 alcCaptureDefaultDeviceSpecifier = NULL;
2694 if(doclose)
2696 ALCdevice *dev;
2697 while((dev=DeviceList) != NULL)
2699 WARN("Closing device %p\n", dev);
2700 if(!dev->IsCaptureDevice) alcCloseDevice(dev);
2701 else alcCaptureCloseDevice(dev);
2704 else
2706 ALCdevice *dev;
2707 if((dev=DeviceList) != NULL)
2709 ALCuint num = 0;
2710 do {
2711 num++;
2712 } while((dev=dev->next) != NULL);
2713 WARN("%u device%s not closed\n", num, (num>1)?"s":"");
2718 ///////////////////////////////////////////////////////