Move ConeScale and ZScale to ALu.c and alu.h, and make them floats
[openal-soft/openal-hmr.git] / Alc / ALc.c
blobe7872d0074857ea75c9d1fa27c5ce4b413fda0fb
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 /* Flag to trap ALC device errors */
397 static ALCboolean TrapALCError = ALC_FALSE;
399 /* One-time configuration init control */
400 static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT;
402 ///////////////////////////////////////////////////////
405 ///////////////////////////////////////////////////////
406 // ALC Related helper functions
407 static void ReleaseALC(ALCboolean doclose);
408 static void ReleaseThreadCtx(void *ptr);
410 static void alc_initconfig(void);
411 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
413 #if defined(_WIN32)
414 static void alc_init(void);
415 static void alc_deinit(void);
416 static void alc_deinit_safe(void);
418 #ifndef AL_LIBTYPE_STATIC
419 UIntMap TlsDestructor;
421 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
423 ALsizei i;
424 (void)hModule;
426 // Perform actions based on the reason for calling.
427 switch(ul_reason_for_call)
429 case DLL_PROCESS_ATTACH:
430 InitUIntMap(&TlsDestructor, ~0);
431 alc_init();
432 break;
434 case DLL_THREAD_DETACH:
435 LockUIntMapRead(&TlsDestructor);
436 for(i = 0;i < TlsDestructor.size;i++)
438 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
439 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
440 if(ptr && callback)
441 callback(ptr);
443 UnlockUIntMapRead(&TlsDestructor);
444 break;
446 case DLL_PROCESS_DETACH:
447 if(!lpReserved)
448 alc_deinit();
449 else
450 alc_deinit_safe();
451 ResetUIntMap(&TlsDestructor);
452 break;
454 return TRUE;
456 #elif defined(_MSC_VER)
457 #pragma section(".CRT$XCU",read)
458 static void alc_constructor(void);
459 static void alc_destructor(void);
460 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
462 static void alc_constructor(void)
464 atexit(alc_destructor);
465 alc_init();
468 static void alc_destructor(void)
470 alc_deinit();
472 #elif defined(HAVE_GCC_DESTRUCTOR)
473 static void alc_init(void) __attribute__((constructor));
474 static void alc_deinit(void) __attribute__((destructor));
475 #else
476 #error "No static initialization available on this platform!"
477 #endif
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 global initialization available on this platform!"
483 #endif
485 static void alc_init(void)
487 const char *str;
489 LogFile = stderr;
491 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
492 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
493 ConeScale = 1.0f;
495 str = getenv("__ALSOFT_REVERSE_Z");
496 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
497 ZScale = -1.0f;
499 str = getenv("__ALSOFT_TRAP_ERROR");
500 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
502 TrapALError = AL_TRUE;
503 TrapALCError = AL_TRUE;
505 else
507 str = getenv("__ALSOFT_TRAP_AL_ERROR");
508 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
509 TrapALError = AL_TRUE;
511 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
512 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
513 TrapALCError = ALC_TRUE;
516 pthread_key_create(&LocalContext, ReleaseThreadCtx);
517 InitializeCriticalSection(&ListLock);
518 ThunkInit();
521 static void alc_deinit_safe(void)
523 ReleaseALC(ALC_FALSE);
525 FreeHrtf();
526 FreeALConfig();
528 ThunkExit();
529 DeleteCriticalSection(&ListLock);
530 pthread_key_delete(LocalContext);
532 if(LogFile != stderr)
533 fclose(LogFile);
534 LogFile = NULL;
537 static void alc_deinit(void)
539 int i;
541 ReleaseALC(ALC_TRUE);
543 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
544 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
546 for(i = 0;BackendList[i].Deinit;i++)
547 BackendList[i].Deinit();
548 BackendLoopback.Deinit();
550 alc_deinit_safe();
553 static void alc_initconfig(void)
555 const char *devs, *str;
556 float valf;
557 int i, n;
559 str = getenv("ALSOFT_LOGLEVEL");
560 if(str)
562 long lvl = strtol(str, NULL, 0);
563 if(lvl >= NoLog && lvl <= LogRef)
564 LogLevel = lvl;
567 str = getenv("ALSOFT_LOGFILE");
568 if(str && str[0])
570 FILE *logfile = fopen(str, "wat");
571 if(logfile) LogFile = logfile;
572 else ERR("Failed to open log file '%s'\n", str);
575 ReadALConfig();
577 InitHrtf();
579 #ifdef _WIN32
580 RTPrioLevel = 1;
581 #else
582 RTPrioLevel = 0;
583 #endif
584 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
586 if(ConfigValueInt(NULL, "resampler", &n))
588 if(n < RESAMPLER_MAX && n > RESAMPLER_MIN)
589 DefaultResampler = n;
592 if(!TrapALCError)
593 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
595 if(!TrapALError)
596 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
598 if(ConfigValueFloat("reverb", "boost", &valf))
599 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
601 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
603 if(ConfigValueStr(NULL, "drivers", &devs))
605 int n;
606 size_t len;
607 const char *next = devs;
608 int endlist, delitem;
610 i = 0;
611 do {
612 devs = next;
613 next = strchr(devs, ',');
615 delitem = (devs[0] == '-');
616 if(devs[0] == '-') devs++;
618 if(!devs[0] || devs[0] == ',')
620 endlist = 0;
621 continue;
623 endlist = 1;
625 len = (next ? ((size_t)(next-devs)) : strlen(devs));
626 for(n = i;BackendList[n].Init;n++)
628 if(len == strlen(BackendList[n].name) &&
629 strncmp(BackendList[n].name, devs, len) == 0)
631 if(delitem)
633 do {
634 BackendList[n] = BackendList[n+1];
635 ++n;
636 } while(BackendList[n].Init);
638 else
640 struct BackendInfo Bkp = BackendList[n];
641 while(n > i)
643 BackendList[n] = BackendList[n-1];
644 --n;
646 BackendList[n] = Bkp;
648 i++;
650 break;
653 } while(next++);
655 if(endlist)
657 BackendList[i].name = NULL;
658 BackendList[i].Init = NULL;
659 BackendList[i].Deinit = NULL;
660 BackendList[i].Probe = NULL;
664 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
666 if(!BackendList[i].Init(&BackendList[i].Funcs))
668 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
669 continue;
672 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
673 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
675 PlaybackBackend = BackendList[i];
676 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
678 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
680 CaptureBackend = BackendList[i];
681 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
684 BackendLoopback.Init(&BackendLoopback.Funcs);
686 if(ConfigValueStr(NULL, "excludefx", &str))
688 size_t len;
689 const char *next = str;
691 do {
692 str = next;
693 next = strchr(str, ',');
695 if(!str[0] || next == str)
696 continue;
698 len = (next ? ((size_t)(next-str)) : strlen(str));
699 for(n = 0;EffectList[n].name;n++)
701 if(len == strlen(EffectList[n].name) &&
702 strncmp(EffectList[n].name, str, len) == 0)
703 DisabledEffects[EffectList[n].type] = AL_TRUE;
705 } while(next++);
710 static void LockLists(void)
712 EnterCriticalSection(&ListLock);
715 static void UnlockLists(void)
717 LeaveCriticalSection(&ListLock);
721 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
723 DO_INITCONFIG();
725 LockLists();
726 free(*list);
727 *list = NULL;
728 *listsize = 0;
730 if(type == CAPTURE_DEVICE_PROBE)
731 CaptureBackend.Probe(type);
732 else
733 PlaybackBackend.Probe(type);
734 UnlockLists();
737 static void ProbeDeviceList(void)
738 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
739 static void ProbeAllDeviceList(void)
740 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
741 static void ProbeCaptureDeviceList(void)
742 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
745 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
747 size_t len = strlen(name);
748 void *temp;
750 if(len == 0)
751 return;
753 temp = realloc(*List, (*ListSize) + len + 2);
754 if(!temp)
756 ERR("Realloc failed to add %s!\n", name);
757 return;
759 *List = temp;
761 memcpy((*List)+(*ListSize), name, len+1);
762 *ListSize += len+1;
763 (*List)[*ListSize] = 0;
766 #define DECL_APPEND_LIST_FUNC(type) \
767 void Append##type##List(const ALCchar *name) \
768 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
770 DECL_APPEND_LIST_FUNC(Device)
771 DECL_APPEND_LIST_FUNC(AllDevice)
772 DECL_APPEND_LIST_FUNC(CaptureDevice)
774 #undef DECL_APPEND_LIST_FUNC
777 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
778 void SetDefaultChannelOrder(ALCdevice *device)
780 switch(device->FmtChans)
782 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
783 device->DevChannels[1] = FRONT_RIGHT;
784 device->DevChannels[2] = BACK_LEFT;
785 device->DevChannels[3] = BACK_RIGHT;
786 device->DevChannels[4] = FRONT_CENTER;
787 device->DevChannels[5] = LFE;
788 return;
790 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
791 device->DevChannels[1] = FRONT_RIGHT;
792 device->DevChannels[2] = BACK_LEFT;
793 device->DevChannels[3] = BACK_RIGHT;
794 device->DevChannels[4] = FRONT_CENTER;
795 device->DevChannels[5] = LFE;
796 device->DevChannels[6] = SIDE_LEFT;
797 device->DevChannels[7] = SIDE_RIGHT;
798 return;
800 /* Same as WFX order */
801 case DevFmtMono:
802 case DevFmtStereo:
803 case DevFmtQuad:
804 case DevFmtX51Side:
805 case DevFmtX61:
806 break;
808 SetDefaultWFXChannelOrder(device);
810 /* Sets the default order used by WaveFormatEx */
811 void SetDefaultWFXChannelOrder(ALCdevice *device)
813 switch(device->FmtChans)
815 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
817 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
818 device->DevChannels[1] = FRONT_RIGHT; break;
820 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
821 device->DevChannels[1] = FRONT_RIGHT;
822 device->DevChannels[2] = BACK_LEFT;
823 device->DevChannels[3] = BACK_RIGHT; break;
825 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
826 device->DevChannels[1] = FRONT_RIGHT;
827 device->DevChannels[2] = FRONT_CENTER;
828 device->DevChannels[3] = LFE;
829 device->DevChannels[4] = BACK_LEFT;
830 device->DevChannels[5] = BACK_RIGHT; break;
832 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
833 device->DevChannels[1] = FRONT_RIGHT;
834 device->DevChannels[2] = FRONT_CENTER;
835 device->DevChannels[3] = LFE;
836 device->DevChannels[4] = SIDE_LEFT;
837 device->DevChannels[5] = SIDE_RIGHT; break;
839 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
840 device->DevChannels[1] = FRONT_RIGHT;
841 device->DevChannels[2] = FRONT_CENTER;
842 device->DevChannels[3] = LFE;
843 device->DevChannels[4] = BACK_CENTER;
844 device->DevChannels[5] = SIDE_LEFT;
845 device->DevChannels[6] = SIDE_RIGHT; break;
847 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
848 device->DevChannels[1] = FRONT_RIGHT;
849 device->DevChannels[2] = FRONT_CENTER;
850 device->DevChannels[3] = LFE;
851 device->DevChannels[4] = BACK_LEFT;
852 device->DevChannels[5] = BACK_RIGHT;
853 device->DevChannels[6] = SIDE_LEFT;
854 device->DevChannels[7] = SIDE_RIGHT; break;
859 const ALCchar *DevFmtTypeString(enum DevFmtType type)
861 switch(type)
863 case DevFmtByte: return "Signed Byte";
864 case DevFmtUByte: return "Unsigned Byte";
865 case DevFmtShort: return "Signed Short";
866 case DevFmtUShort: return "Unsigned Short";
867 case DevFmtFloat: return "Float";
869 return "(unknown type)";
871 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
873 switch(chans)
875 case DevFmtMono: return "Mono";
876 case DevFmtStereo: return "Stereo";
877 case DevFmtQuad: return "Quadraphonic";
878 case DevFmtX51: return "5.1 Surround";
879 case DevFmtX51Side: return "5.1 Side";
880 case DevFmtX61: return "6.1 Surround";
881 case DevFmtX71: return "7.1 Surround";
883 return "(unknown channels)";
886 ALuint BytesFromDevFmt(enum DevFmtType type)
888 switch(type)
890 case DevFmtByte: return sizeof(ALbyte);
891 case DevFmtUByte: return sizeof(ALubyte);
892 case DevFmtShort: return sizeof(ALshort);
893 case DevFmtUShort: return sizeof(ALushort);
894 case DevFmtFloat: return sizeof(ALfloat);
896 return 0;
898 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
900 switch(chans)
902 case DevFmtMono: return 1;
903 case DevFmtStereo: return 2;
904 case DevFmtQuad: return 4;
905 case DevFmtX51: return 6;
906 case DevFmtX51Side: return 6;
907 case DevFmtX61: return 7;
908 case DevFmtX71: return 8;
910 return 0;
912 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
913 enum DevFmtType *type)
915 static const struct {
916 ALenum format;
917 enum DevFmtChannels channels;
918 enum DevFmtType type;
919 } list[] = {
920 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
921 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
922 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
924 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
925 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
926 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
928 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
929 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
930 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
932 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
933 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
934 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
936 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
937 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
938 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
940 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
941 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
942 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
944 ALuint i;
946 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
948 if(list[i].format == format)
950 *chans = list[i].channels;
951 *type = list[i].type;
952 return AL_TRUE;
956 return AL_FALSE;
959 static ALCboolean IsValidALCType(ALCenum type)
961 switch(type)
963 case ALC_BYTE:
964 case ALC_UNSIGNED_BYTE:
965 case ALC_SHORT:
966 case ALC_UNSIGNED_SHORT:
967 case ALC_INT:
968 case ALC_UNSIGNED_INT:
969 case ALC_FLOAT:
970 return ALC_TRUE;
972 return ALC_FALSE;
975 static ALCboolean IsValidALCChannels(ALCenum channels)
977 switch(channels)
979 case ALC_MONO:
980 case ALC_STEREO:
981 case ALC_QUAD:
982 case ALC_5POINT1:
983 case ALC_6POINT1:
984 case ALC_7POINT1:
985 return ALC_TRUE;
987 return ALC_FALSE;
991 /* alcSetError
993 * Stores the latest ALC Error
995 static void alcSetError(ALCdevice *device, ALCenum errorCode)
997 if(TrapALCError)
999 #ifdef _WIN32
1000 /* DebugBreak() will cause an exception if there is no debugger */
1001 if(IsDebuggerPresent())
1002 DebugBreak();
1003 #elif defined(SIGTRAP)
1004 kill(getpid(), SIGTRAP);
1005 #endif
1008 if(device)
1009 device->LastError = errorCode;
1010 else
1011 g_eLastNullDeviceError = errorCode;
1015 /* UpdateDeviceParams
1017 * Updates device parameters according to the attribute list (caller is
1018 * responsible for holding the list lock).
1020 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1022 ALCcontext *context;
1023 ALuint i;
1025 // Check for attributes
1026 if(attrList && attrList[0])
1028 ALCuint freq, numMono, numStereo, numSends;
1029 enum DevFmtChannels schans;
1030 enum DevFmtType stype;
1031 ALuint attrIdx;
1033 // If a context is already running on the device, stop playback so the
1034 // device attributes can be updated
1035 if((device->Flags&DEVICE_RUNNING))
1036 ALCdevice_StopPlayback(device);
1037 device->Flags &= ~DEVICE_RUNNING;
1039 freq = device->Frequency;
1040 schans = device->FmtChans;
1041 stype = device->FmtType;
1042 numMono = device->NumMonoSources;
1043 numStereo = device->NumStereoSources;
1044 numSends = device->NumAuxSends;
1046 attrIdx = 0;
1047 while(attrList[attrIdx])
1049 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1050 device->IsLoopbackDevice)
1052 ALCint val = attrList[attrIdx + 1];
1053 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1055 alcSetError(device, ALC_INVALID_VALUE);
1056 return ALC_FALSE;
1058 schans = val;
1061 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1062 device->IsLoopbackDevice)
1064 ALCint val = attrList[attrIdx + 1];
1065 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1067 alcSetError(device, ALC_INVALID_VALUE);
1068 return ALC_FALSE;
1070 stype = val;
1073 if(attrList[attrIdx] == ALC_FREQUENCY)
1075 if(device->IsLoopbackDevice)
1077 freq = attrList[attrIdx + 1];
1078 if(freq < 8000)
1080 alcSetError(device, ALC_INVALID_VALUE);
1081 return ALC_FALSE;
1084 else
1086 freq = attrList[attrIdx + 1];
1087 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1091 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1093 numStereo = attrList[attrIdx + 1];
1094 if(numStereo > device->MaxNoOfSources)
1095 numStereo = device->MaxNoOfSources;
1097 numMono = device->MaxNoOfSources - numStereo;
1100 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1101 numSends = attrList[attrIdx + 1];
1103 attrIdx += 2;
1106 if(!device->IsLoopbackDevice)
1108 ConfigValueUInt(NULL, "frequency", &freq);
1109 freq = maxu(freq, 8000);
1111 ConfigValueUInt(NULL, "sends", &numSends);
1112 numSends = minu(MAX_SENDS, numSends);
1114 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1115 device->Frequency;
1117 device->Frequency = freq;
1118 device->FmtChans = schans;
1119 device->FmtType = stype;
1120 device->NumMonoSources = numMono;
1121 device->NumStereoSources = numStereo;
1122 device->NumAuxSends = numSends;
1125 if((device->Flags&DEVICE_RUNNING))
1126 return ALC_TRUE;
1128 LockDevice(device);
1129 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1130 DevFmtChannelsString(device->FmtChans),
1131 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1132 DevFmtTypeString(device->FmtType), device->Frequency,
1133 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1134 device->UpdateSize, device->NumUpdates);
1135 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1137 UnlockDevice(device);
1138 return ALC_FALSE;
1140 device->Flags |= DEVICE_RUNNING;
1141 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1142 DevFmtChannelsString(device->FmtChans),
1143 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1144 DevFmtTypeString(device->FmtType), device->Frequency,
1145 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1146 device->UpdateSize, device->NumUpdates);
1148 aluInitPanning(device);
1150 for(i = 0;i < MAXCHANNELS;i++)
1152 device->ClickRemoval[i] = 0.0f;
1153 device->PendingClicks[i] = 0.0f;
1156 device->Hrtf = NULL;
1157 device->Flags &= ~DEVICE_USE_HRTF;
1158 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1159 device->Flags |= DEVICE_USE_HRTF;
1160 if((device->Flags&DEVICE_USE_HRTF) && !(device->Hrtf=GetHrtf(device)))
1161 device->Flags &= ~DEVICE_USE_HRTF;
1162 TRACE("HRTF %s\n", (device->Flags&DEVICE_USE_HRTF)?"enabled":"disabled");
1164 if(!(device->Flags&DEVICE_USE_HRTF) && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1166 if(!device->Bs2b)
1168 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1169 bs2b_clear(device->Bs2b);
1171 bs2b_set_srate(device->Bs2b, device->Frequency);
1172 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1173 TRACE("BS2B level %d\n", device->Bs2bLevel);
1175 else
1177 free(device->Bs2b);
1178 device->Bs2b = NULL;
1179 TRACE("BS2B disabled\n");
1182 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1183 switch(device->FmtChans)
1185 case DevFmtMono:
1186 case DevFmtStereo:
1187 break;
1188 case DevFmtQuad:
1189 case DevFmtX51:
1190 case DevFmtX51Side:
1191 case DevFmtX61:
1192 case DevFmtX71:
1193 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1194 device->Flags |= DEVICE_DUPLICATE_STEREO;
1195 break;
1197 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1199 context = device->ContextList;
1200 while(context)
1202 ALsizei pos;
1204 context->UpdateSources = AL_FALSE;
1205 LockUIntMapRead(&context->EffectSlotMap);
1206 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1208 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1210 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1212 UnlockUIntMapRead(&context->EffectSlotMap);
1213 UnlockDevice(device);
1214 ALCdevice_StopPlayback(device);
1215 device->Flags &= ~DEVICE_RUNNING;
1216 return ALC_FALSE;
1218 slot->NeedsUpdate = AL_FALSE;
1219 ALeffectState_Update(slot->EffectState, context, slot);
1221 UnlockUIntMapRead(&context->EffectSlotMap);
1223 LockUIntMapRead(&context->SourceMap);
1224 for(pos = 0;pos < context->SourceMap.size;pos++)
1226 ALsource *source = context->SourceMap.array[pos].value;
1227 ALuint s = device->NumAuxSends;
1228 while(s < MAX_SENDS)
1230 if(source->Send[s].Slot)
1231 DecrementRef(&source->Send[s].Slot->ref);
1232 source->Send[s].Slot = NULL;
1233 source->Send[s].WetGain = 1.0f;
1234 source->Send[s].WetGainHF = 1.0f;
1235 s++;
1237 source->NeedsUpdate = AL_FALSE;
1238 ALsource_Update(source, context);
1240 UnlockUIntMapRead(&context->SourceMap);
1242 context = context->next;
1244 UnlockDevice(device);
1246 return ALC_TRUE;
1249 /* FreeDevice
1251 * Frees the device structure, and destroys any objects the app failed to
1252 * delete. Called once there's no more references on the device.
1254 static ALCvoid FreeDevice(ALCdevice *device)
1256 TRACE("%p\n", device);
1258 if(device->BufferMap.size > 0)
1260 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1261 ReleaseALBuffers(device);
1263 ResetUIntMap(&device->BufferMap);
1265 if(device->EffectMap.size > 0)
1267 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1268 ReleaseALEffects(device);
1270 ResetUIntMap(&device->EffectMap);
1272 if(device->FilterMap.size > 0)
1274 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1275 ReleaseALFilters(device);
1277 ResetUIntMap(&device->FilterMap);
1279 free(device->Bs2b);
1280 device->Bs2b = NULL;
1282 free(device->szDeviceName);
1283 device->szDeviceName = NULL;
1285 DeleteCriticalSection(&device->Mutex);
1287 free(device);
1291 void ALCdevice_IncRef(ALCdevice *device)
1293 RefCount ref;
1294 ref = IncrementRef(&device->ref);
1295 TRACEREF("%p increasing refcount to %u\n", device, ref);
1298 void ALCdevice_DecRef(ALCdevice *device)
1300 RefCount ref;
1301 ref = DecrementRef(&device->ref);
1302 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1303 if(ref == 0) FreeDevice(device);
1306 /* VerifyDevice
1308 * Checks if the device handle is valid, and increments its ref count if so.
1310 static ALCdevice *VerifyDevice(ALCdevice *device)
1312 ALCdevice *tmpDevice;
1314 if(!device)
1315 return NULL;
1317 LockLists();
1318 tmpDevice = DeviceList;
1319 while(tmpDevice && tmpDevice != device)
1320 tmpDevice = tmpDevice->next;
1322 if(tmpDevice)
1323 ALCdevice_IncRef(tmpDevice);
1324 UnlockLists();
1325 return tmpDevice;
1329 ALCvoid LockDevice(ALCdevice *device)
1331 EnterCriticalSection(&device->Mutex);
1334 ALCvoid UnlockDevice(ALCdevice *device)
1336 LeaveCriticalSection(&device->Mutex);
1340 /* InitContext
1342 * Initializes context variables
1344 static ALvoid InitContext(ALCcontext *pContext)
1346 //Initialise listener
1347 pContext->Listener.Gain = 1.0f;
1348 pContext->Listener.MetersPerUnit = 1.0f;
1349 pContext->Listener.Position[0] = 0.0f;
1350 pContext->Listener.Position[1] = 0.0f;
1351 pContext->Listener.Position[2] = 0.0f;
1352 pContext->Listener.Velocity[0] = 0.0f;
1353 pContext->Listener.Velocity[1] = 0.0f;
1354 pContext->Listener.Velocity[2] = 0.0f;
1355 pContext->Listener.Forward[0] = 0.0f;
1356 pContext->Listener.Forward[1] = 0.0f;
1357 pContext->Listener.Forward[2] = -1.0f;
1358 pContext->Listener.Up[0] = 0.0f;
1359 pContext->Listener.Up[1] = 1.0f;
1360 pContext->Listener.Up[2] = 0.0f;
1362 //Validate pContext
1363 pContext->LastError = AL_NO_ERROR;
1364 pContext->UpdateSources = AL_FALSE;
1365 pContext->ActiveSourceCount = 0;
1366 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1367 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1369 //Set globals
1370 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1371 pContext->SourceDistanceModel = AL_FALSE;
1372 pContext->DopplerFactor = 1.0f;
1373 pContext->DopplerVelocity = 1.0f;
1374 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1375 pContext->DeferUpdates = AL_FALSE;
1377 pContext->ExtensionList = alExtList;
1381 /* FreeContext
1383 * Cleans up the context, and destroys any remaining objects the app failed to
1384 * delete. Called once there's no more references on the context.
1386 static ALCvoid FreeContext(ALCcontext *context)
1388 TRACE("%p\n", context);
1390 if(context->SourceMap.size > 0)
1392 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1393 ReleaseALSources(context);
1395 ResetUIntMap(&context->SourceMap);
1397 if(context->EffectSlotMap.size > 0)
1399 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1400 ReleaseALAuxiliaryEffectSlots(context);
1402 ResetUIntMap(&context->EffectSlotMap);
1404 context->ActiveSourceCount = 0;
1405 free(context->ActiveSources);
1406 context->ActiveSources = NULL;
1407 context->MaxActiveSources = 0;
1409 context->ActiveEffectSlotCount = 0;
1410 free(context->ActiveEffectSlots);
1411 context->ActiveEffectSlots = NULL;
1412 context->MaxActiveEffectSlots = 0;
1414 ALCdevice_DecRef(context->Device);
1415 context->Device = NULL;
1417 //Invalidate context
1418 memset(context, 0, sizeof(ALCcontext));
1419 free(context);
1422 /* ReleaseContext
1424 * Removes the context reference from the given device and removes it from
1425 * being current on the running thread or globally.
1427 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1429 ALCcontext *volatile*tmp_ctx;
1431 if(pthread_getspecific(LocalContext) == context)
1433 WARN("%p released while current on thread\n", context);
1434 pthread_setspecific(LocalContext, NULL);
1435 ALCcontext_DecRef(context);
1438 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1440 WARN("%p released while current\n", context);
1441 ALCcontext_DecRef(context);
1444 tmp_ctx = &device->ContextList;
1445 while(*tmp_ctx)
1447 if(*tmp_ctx == context)
1449 *tmp_ctx = context->next;
1450 break;
1452 tmp_ctx = &(*tmp_ctx)->next;
1455 LockDevice(device);
1456 /* Lock the device to make sure the mixer is not using the contexts in the
1457 * list before we go about deleting this one. There should be a more
1458 * efficient way of doing this. */
1459 UnlockDevice(device);
1461 ALCcontext_DecRef(context);
1464 void ALCcontext_IncRef(ALCcontext *context)
1466 RefCount ref;
1467 ref = IncrementRef(&context->ref);
1468 TRACEREF("%p increasing refcount to %u\n", context, ref);
1471 void ALCcontext_DecRef(ALCcontext *context)
1473 RefCount ref;
1474 ref = DecrementRef(&context->ref);
1475 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1476 if(ref == 0) FreeContext(context);
1479 static void ReleaseThreadCtx(void *ptr)
1481 WARN("%p current for thread being destroyed\n", ptr);
1482 ALCcontext_DecRef(ptr);
1485 /* VerifyContext
1487 * Checks that the given context is valid, and increments its reference count.
1489 static ALCcontext *VerifyContext(ALCcontext *context)
1491 ALCdevice *dev;
1493 LockLists();
1494 dev = DeviceList;
1495 while(dev)
1497 ALCcontext *tmp_ctx = dev->ContextList;
1498 while(tmp_ctx)
1500 if(tmp_ctx == context)
1502 ALCcontext_IncRef(tmp_ctx);
1503 UnlockLists();
1504 return tmp_ctx;
1506 tmp_ctx = tmp_ctx->next;
1508 dev = dev->next;
1510 UnlockLists();
1512 return NULL;
1516 ALCvoid LockContext(ALCcontext *context)
1518 EnterCriticalSection(&context->Device->Mutex);
1521 ALCvoid UnlockContext(ALCcontext *context)
1523 LeaveCriticalSection(&context->Device->Mutex);
1526 /* GetContextRef
1528 * Returns the currently active context, and adds a reference without locking
1529 * it.
1531 ALCcontext *GetContextRef(void)
1533 ALCcontext *context;
1535 context = pthread_getspecific(LocalContext);
1536 if(context)
1537 ALCcontext_IncRef(context);
1538 else
1540 LockLists();
1541 context = GlobalContext;
1542 if(context)
1543 ALCcontext_IncRef(context);
1544 UnlockLists();
1547 return context;
1550 ///////////////////////////////////////////////////////
1553 ///////////////////////////////////////////////////////
1554 // ALC Functions calls
1557 // This should probably move to another c file but for now ...
1558 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1560 ALCdevice *device = NULL;
1561 ALCenum err;
1563 DO_INITCONFIG();
1565 if(!CaptureBackend.name)
1567 alcSetError(NULL, ALC_INVALID_VALUE);
1568 return NULL;
1571 if(SampleSize <= 0)
1573 alcSetError(NULL, ALC_INVALID_VALUE);
1574 return NULL;
1577 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1578 deviceName = NULL;
1580 device = calloc(1, sizeof(ALCdevice));
1581 if(!device)
1583 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1584 return NULL;
1587 //Validate device
1588 device->Funcs = &CaptureBackend.Funcs;
1589 device->ref = 1;
1590 device->Connected = ALC_TRUE;
1591 device->IsCaptureDevice = AL_TRUE;
1592 device->IsLoopbackDevice = AL_FALSE;
1593 InitializeCriticalSection(&device->Mutex);
1595 InitUIntMap(&device->BufferMap, ~0);
1596 InitUIntMap(&device->EffectMap, ~0);
1597 InitUIntMap(&device->FilterMap, ~0);
1599 device->szDeviceName = NULL;
1601 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1602 device->Frequency = frequency;
1604 device->Flags |= DEVICE_CHANNELS_REQUEST;
1605 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1607 DeleteCriticalSection(&device->Mutex);
1608 free(device);
1609 alcSetError(NULL, ALC_INVALID_ENUM);
1610 return NULL;
1613 device->UpdateSize = SampleSize;
1614 device->NumUpdates = 1;
1616 LockLists();
1617 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1619 UnlockLists();
1620 DeleteCriticalSection(&device->Mutex);
1621 free(device);
1622 alcSetError(NULL, err);
1623 return NULL;
1625 UnlockLists();
1627 do {
1628 device->next = DeviceList;
1629 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
1631 TRACE("Created device %p\n", device);
1632 return device;
1635 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1637 ALCdevice *volatile*list;
1639 LockLists();
1640 list = &DeviceList;
1641 while(*list && *list != pDevice)
1642 list = &(*list)->next;
1644 if(!*list || !(*list)->IsCaptureDevice)
1646 alcSetError(*list, ALC_INVALID_DEVICE);
1647 UnlockLists();
1648 return ALC_FALSE;
1651 *list = (*list)->next;
1652 UnlockLists();
1654 LockDevice(pDevice);
1655 ALCdevice_CloseCapture(pDevice);
1656 UnlockDevice(pDevice);
1658 ALCdevice_DecRef(pDevice);
1660 return ALC_TRUE;
1663 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1665 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1667 alcSetError(device, ALC_INVALID_DEVICE);
1668 if(device) ALCdevice_DecRef(device);
1669 return;
1671 LockDevice(device);
1672 if(device->Connected)
1673 ALCdevice_StartCapture(device);
1674 UnlockDevice(device);
1676 ALCdevice_DecRef(device);
1679 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1681 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1683 alcSetError(device, ALC_INVALID_DEVICE);
1684 if(device) ALCdevice_DecRef(device);
1685 return;
1687 LockDevice(device);
1688 if(device->Connected)
1689 ALCdevice_StopCapture(device);
1690 UnlockDevice(device);
1692 ALCdevice_DecRef(device);
1695 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1697 ALCenum err = ALC_INVALID_DEVICE;
1698 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1700 err = ALC_INVALID_VALUE;
1701 LockDevice(device);
1702 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1703 err = ALCdevice_CaptureSamples(device, buffer, samples);
1704 UnlockDevice(device);
1706 if(err != ALC_NO_ERROR)
1707 alcSetError(device, err);
1708 if(device) ALCdevice_DecRef(device);
1712 alcGetError
1714 Return last ALC generated error code
1716 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1718 ALCenum errorCode;
1720 if(VerifyDevice(device))
1722 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1723 ALCdevice_DecRef(device);
1725 else
1726 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1728 return errorCode;
1732 /* alcSuspendContext
1734 * Not functional
1736 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1738 (void)Context;
1741 /* alcProcessContext
1743 * Not functional
1745 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1747 (void)Context;
1751 /* alcGetString
1753 * Returns information about the Device, and error strings
1755 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1757 const ALCchar *value = NULL;
1759 switch(param)
1761 case ALC_NO_ERROR:
1762 value = alcNoError;
1763 break;
1765 case ALC_INVALID_ENUM:
1766 value = alcErrInvalidEnum;
1767 break;
1769 case ALC_INVALID_VALUE:
1770 value = alcErrInvalidValue;
1771 break;
1773 case ALC_INVALID_DEVICE:
1774 value = alcErrInvalidDevice;
1775 break;
1777 case ALC_INVALID_CONTEXT:
1778 value = alcErrInvalidContext;
1779 break;
1781 case ALC_OUT_OF_MEMORY:
1782 value = alcErrOutOfMemory;
1783 break;
1785 case ALC_DEVICE_SPECIFIER:
1786 if(VerifyDevice(pDevice))
1788 value = pDevice->szDeviceName;
1789 ALCdevice_DecRef(pDevice);
1791 else
1793 ProbeDeviceList();
1794 value = alcDeviceList;
1796 break;
1798 case ALC_ALL_DEVICES_SPECIFIER:
1799 ProbeAllDeviceList();
1800 value = alcAllDeviceList;
1801 break;
1803 case ALC_CAPTURE_DEVICE_SPECIFIER:
1804 if(VerifyDevice(pDevice))
1806 value = pDevice->szDeviceName;
1807 ALCdevice_DecRef(pDevice);
1809 else
1811 ProbeCaptureDeviceList();
1812 value = alcCaptureDeviceList;
1814 break;
1816 /* Default devices are always first in the list */
1817 case ALC_DEFAULT_DEVICE_SPECIFIER:
1818 if(!alcDeviceList)
1819 ProbeDeviceList();
1821 pDevice = VerifyDevice(pDevice);
1823 free(alcDefaultDeviceSpecifier);
1824 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1825 if(!alcDefaultDeviceSpecifier)
1826 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1828 value = alcDefaultDeviceSpecifier;
1829 if(pDevice) ALCdevice_DecRef(pDevice);
1830 break;
1832 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1833 if(!alcAllDeviceList)
1834 ProbeAllDeviceList();
1836 pDevice = VerifyDevice(pDevice);
1838 free(alcDefaultAllDeviceSpecifier);
1839 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1840 alcAllDeviceList : "");
1841 if(!alcDefaultAllDeviceSpecifier)
1842 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1844 value = alcDefaultAllDeviceSpecifier;
1845 if(pDevice) ALCdevice_DecRef(pDevice);
1846 break;
1848 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1849 if(!alcCaptureDeviceList)
1850 ProbeCaptureDeviceList();
1852 pDevice = VerifyDevice(pDevice);
1854 free(alcCaptureDefaultDeviceSpecifier);
1855 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1856 alcCaptureDeviceList : "");
1857 if(!alcCaptureDefaultDeviceSpecifier)
1858 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1860 value = alcCaptureDefaultDeviceSpecifier;
1861 if(pDevice) ALCdevice_DecRef(pDevice);
1862 break;
1864 case ALC_EXTENSIONS:
1865 if(!VerifyDevice(pDevice))
1866 value = alcNoDeviceExtList;
1867 else
1869 value = alcExtensionList;
1870 ALCdevice_DecRef(pDevice);
1872 break;
1874 default:
1875 pDevice = VerifyDevice(pDevice);
1876 alcSetError(pDevice, ALC_INVALID_ENUM);
1877 if(pDevice) ALCdevice_DecRef(pDevice);
1878 break;
1881 return value;
1885 /* alcGetIntegerv
1887 * Returns information about the Device and the version of Open AL
1889 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1891 device = VerifyDevice(device);
1893 if(size == 0 || data == NULL)
1895 alcSetError(device, ALC_INVALID_VALUE);
1896 if(device) ALCdevice_DecRef(device);
1897 return;
1900 if(!device)
1902 switch(param)
1904 case ALC_MAJOR_VERSION:
1905 *data = alcMajorVersion;
1906 break;
1907 case ALC_MINOR_VERSION:
1908 *data = alcMinorVersion;
1909 break;
1911 case ALC_ATTRIBUTES_SIZE:
1912 case ALC_ALL_ATTRIBUTES:
1913 case ALC_FREQUENCY:
1914 case ALC_REFRESH:
1915 case ALC_SYNC:
1916 case ALC_MONO_SOURCES:
1917 case ALC_STEREO_SOURCES:
1918 case ALC_CAPTURE_SAMPLES:
1919 case ALC_FORMAT_CHANNELS_SOFT:
1920 case ALC_FORMAT_TYPE_SOFT:
1921 alcSetError(NULL, ALC_INVALID_DEVICE);
1922 break;
1924 default:
1925 alcSetError(NULL, ALC_INVALID_ENUM);
1926 break;
1929 else if(device->IsCaptureDevice)
1931 switch(param)
1933 case ALC_CAPTURE_SAMPLES:
1934 LockDevice(device);
1935 *data = ALCdevice_AvailableSamples(device);
1936 UnlockDevice(device);
1937 break;
1939 case ALC_CONNECTED:
1940 *data = device->Connected;
1941 break;
1943 default:
1944 alcSetError(device, ALC_INVALID_ENUM);
1945 break;
1948 else /* render device */
1950 switch(param)
1952 case ALC_MAJOR_VERSION:
1953 *data = alcMajorVersion;
1954 break;
1956 case ALC_MINOR_VERSION:
1957 *data = alcMinorVersion;
1958 break;
1960 case ALC_EFX_MAJOR_VERSION:
1961 *data = alcEFXMajorVersion;
1962 break;
1964 case ALC_EFX_MINOR_VERSION:
1965 *data = alcEFXMinorVersion;
1966 break;
1968 case ALC_ATTRIBUTES_SIZE:
1969 *data = 13;
1970 break;
1972 case ALC_ALL_ATTRIBUTES:
1973 if(size < 13)
1974 alcSetError(device, ALC_INVALID_VALUE);
1975 else
1977 int i = 0;
1979 data[i++] = ALC_FREQUENCY;
1980 data[i++] = device->Frequency;
1982 if(!device->IsLoopbackDevice)
1984 data[i++] = ALC_REFRESH;
1985 data[i++] = device->Frequency / device->UpdateSize;
1987 data[i++] = ALC_SYNC;
1988 data[i++] = ALC_FALSE;
1990 else
1992 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
1993 data[i++] = device->FmtChans;
1995 data[i++] = ALC_FORMAT_TYPE_SOFT;
1996 data[i++] = device->FmtType;
1999 data[i++] = ALC_MONO_SOURCES;
2000 data[i++] = device->NumMonoSources;
2002 data[i++] = ALC_STEREO_SOURCES;
2003 data[i++] = device->NumStereoSources;
2005 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2006 data[i++] = device->NumAuxSends;
2008 data[i++] = 0;
2010 break;
2012 case ALC_FREQUENCY:
2013 *data = device->Frequency;
2014 break;
2016 case ALC_REFRESH:
2017 if(device->IsLoopbackDevice)
2018 alcSetError(device, ALC_INVALID_DEVICE);
2019 else
2020 *data = device->Frequency / device->UpdateSize;
2021 break;
2023 case ALC_SYNC:
2024 if(device->IsLoopbackDevice)
2025 alcSetError(device, ALC_INVALID_DEVICE);
2026 else
2027 *data = ALC_FALSE;
2028 break;
2030 case ALC_FORMAT_CHANNELS_SOFT:
2031 if(!device->IsLoopbackDevice)
2032 alcSetError(device, ALC_INVALID_DEVICE);
2033 else
2034 *data = device->FmtChans;
2035 break;
2037 case ALC_FORMAT_TYPE_SOFT:
2038 if(!device->IsLoopbackDevice)
2039 alcSetError(device, ALC_INVALID_DEVICE);
2040 else
2041 *data = device->FmtType;
2042 break;
2044 case ALC_MONO_SOURCES:
2045 *data = device->NumMonoSources;
2046 break;
2048 case ALC_STEREO_SOURCES:
2049 *data = device->NumStereoSources;
2050 break;
2052 case ALC_MAX_AUXILIARY_SENDS:
2053 *data = device->NumAuxSends;
2054 break;
2056 case ALC_CONNECTED:
2057 *data = device->Connected;
2058 break;
2060 default:
2061 alcSetError(device, ALC_INVALID_ENUM);
2062 break;
2065 if(device)
2066 ALCdevice_DecRef(device);
2070 /* alcIsExtensionPresent
2072 * Determines if there is support for a particular extension
2074 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2076 ALCboolean bResult = ALC_FALSE;
2078 device = VerifyDevice(device);
2080 if(!extName)
2081 alcSetError(device, ALC_INVALID_VALUE);
2082 else
2084 size_t len = strlen(extName);
2085 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2086 while(ptr && *ptr)
2088 if(strncasecmp(ptr, extName, len) == 0 &&
2089 (ptr[len] == '\0' || isspace(ptr[len])))
2091 bResult = ALC_TRUE;
2092 break;
2094 if((ptr=strchr(ptr, ' ')) != NULL)
2096 do {
2097 ++ptr;
2098 } while(isspace(*ptr));
2102 if(device)
2103 ALCdevice_DecRef(device);
2104 return bResult;
2108 /* alcGetProcAddress
2110 * Retrieves the function address for a particular extension function
2112 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2114 ALCvoid *ptr = NULL;
2116 device = VerifyDevice(device);
2118 if(!funcName)
2119 alcSetError(device, ALC_INVALID_VALUE);
2120 else
2122 ALsizei i = 0;
2123 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2124 i++;
2125 ptr = alcFunctions[i].address;
2127 if(device)
2128 ALCdevice_DecRef(device);
2129 return ptr;
2133 /* alcGetEnumValue
2135 * Get the value for a particular ALC Enumerated Value
2137 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2139 ALCenum val = 0;
2141 device = VerifyDevice(device);
2143 if(!enumName)
2144 alcSetError(device, ALC_INVALID_VALUE);
2145 else
2147 ALsizei i = 0;
2148 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2149 i++;
2150 val = enumeration[i].value;
2152 if(device)
2153 ALCdevice_DecRef(device);
2154 return val;
2158 /* alcCreateContext
2160 * Create and attach a Context to a particular Device.
2162 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2164 ALCcontext *ALContext;
2166 LockLists();
2167 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2169 UnlockLists();
2170 alcSetError(device, ALC_INVALID_DEVICE);
2171 if(device) ALCdevice_DecRef(device);
2172 return NULL;
2175 /* Reset Context Last Error code */
2176 device->LastError = ALC_NO_ERROR;
2178 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2180 UnlockLists();
2181 alcSetError(device, ALC_INVALID_DEVICE);
2182 aluHandleDisconnect(device);
2183 ALCdevice_DecRef(device);
2184 return NULL;
2187 ALContext = calloc(1, sizeof(ALCcontext));
2188 if(ALContext)
2190 ALContext->ref = 1;
2192 ALContext->MaxActiveSources = 256;
2193 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2194 ALContext->MaxActiveSources);
2196 if(!ALContext || !ALContext->ActiveSources)
2198 if(!device->ContextList)
2200 ALCdevice_StopPlayback(device);
2201 device->Flags &= ~DEVICE_RUNNING;
2203 UnlockLists();
2205 free(ALContext);
2206 ALContext = NULL;
2208 alcSetError(device, ALC_OUT_OF_MEMORY);
2209 ALCdevice_DecRef(device);
2210 return NULL;
2213 ALContext->Device = device;
2214 ALCdevice_IncRef(device);
2215 InitContext(ALContext);
2217 ALContext->next = device->ContextList;
2218 device->ContextList = ALContext;
2219 UnlockLists();
2221 ALCdevice_DecRef(device);
2223 TRACE("Created context %p\n", ALContext);
2224 return ALContext;
2227 /* alcDestroyContext
2229 * Remove a Context
2231 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2233 ALCdevice *Device;
2235 LockLists();
2236 /* alcGetContextsDevice sets an error for invalid contexts */
2237 Device = alcGetContextsDevice(context);
2238 if(Device)
2240 ReleaseContext(context, Device);
2241 if(!Device->ContextList)
2243 ALCdevice_StopPlayback(Device);
2244 Device->Flags &= ~DEVICE_RUNNING;
2247 UnlockLists();
2251 /* alcGetCurrentContext
2253 * Returns the currently active Context
2255 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2257 ALCcontext *Context;
2259 Context = pthread_getspecific(LocalContext);
2260 if(!Context) Context = GlobalContext;
2262 return Context;
2265 /* alcGetThreadContext
2267 * Returns the currently active thread-local Context
2269 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2271 ALCcontext *Context;
2272 Context = pthread_getspecific(LocalContext);
2273 return Context;
2277 /* alcMakeContextCurrent
2279 * Makes the given Context the active Context
2281 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2283 /* context must be a valid Context or NULL */
2284 if(context && !(context=VerifyContext(context)))
2286 alcSetError(NULL, ALC_INVALID_CONTEXT);
2287 return ALC_FALSE;
2289 /* context's reference count is already incremented */
2290 context = ExchangePtr((void**)&GlobalContext, context);
2291 if(context) ALCcontext_DecRef(context);
2293 if((context=pthread_getspecific(LocalContext)) != NULL)
2295 pthread_setspecific(LocalContext, NULL);
2296 ALCcontext_DecRef(context);
2299 return ALC_TRUE;
2302 /* alcSetThreadContext
2304 * Makes the given Context the active Context for the current thread
2306 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2308 ALCcontext *old;
2310 /* context must be a valid Context or NULL */
2311 if(context && !(context=VerifyContext(context)))
2313 alcSetError(NULL, ALC_INVALID_CONTEXT);
2314 return ALC_FALSE;
2316 /* context's reference count is already incremented */
2317 old = pthread_getspecific(LocalContext);
2318 pthread_setspecific(LocalContext, context);
2319 if(old) ALCcontext_DecRef(old);
2321 return ALC_TRUE;
2325 /* alcGetContextsDevice
2327 * Returns the Device that a particular Context is attached to
2329 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2331 ALCdevice *Device;
2333 if(!(Context=VerifyContext(Context)))
2335 alcSetError(NULL, ALC_INVALID_CONTEXT);
2336 return NULL;
2338 Device = Context->Device;
2339 ALCcontext_DecRef(Context);
2341 return Device;
2345 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2347 static const struct {
2348 const char name[32];
2349 enum DevFmtChannels channels;
2350 enum DevFmtType type;
2351 } formats[] = {
2352 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2353 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2354 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2355 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2356 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2357 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2359 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2360 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2361 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2362 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2363 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2364 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2366 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2367 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2368 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2369 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2370 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2371 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2373 size_t i;
2375 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2377 if(strcasecmp(str, formats[i].name) == 0)
2379 *chans = formats[i].channels;
2380 *type = formats[i].type;
2381 return;
2385 ERR("Unknown format: \"%s\"\n", str);
2386 *chans = DevFmtStereo;
2387 *type = DevFmtShort;
2390 /* alcOpenDevice
2392 * Open the Device specified.
2394 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2396 const ALCchar *fmt;
2397 ALCdevice *device;
2398 ALCenum err;
2400 DO_INITCONFIG();
2402 if(!PlaybackBackend.name)
2404 alcSetError(NULL, ALC_INVALID_VALUE);
2405 return NULL;
2408 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2409 deviceName = NULL;
2411 device = calloc(1, sizeof(ALCdevice));
2412 if(!device)
2414 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2415 return NULL;
2418 //Validate device
2419 device->Funcs = &PlaybackBackend.Funcs;
2420 device->ref = 1;
2421 device->Connected = ALC_TRUE;
2422 device->IsCaptureDevice = AL_FALSE;
2423 device->IsLoopbackDevice = AL_FALSE;
2424 InitializeCriticalSection(&device->Mutex);
2425 device->LastError = ALC_NO_ERROR;
2427 device->Flags = 0;
2428 device->Bs2b = NULL;
2429 device->Bs2bLevel = 0;
2430 device->szDeviceName = NULL;
2432 device->ContextList = NULL;
2434 device->MaxNoOfSources = 256;
2435 device->AuxiliaryEffectSlotMax = 4;
2436 device->NumAuxSends = MAX_SENDS;
2438 InitUIntMap(&device->BufferMap, ~0);
2439 InitUIntMap(&device->EffectMap, ~0);
2440 InitUIntMap(&device->FilterMap, ~0);
2442 //Set output format
2443 device->NumUpdates = 4;
2444 device->UpdateSize = 1024;
2446 device->Frequency = DEFAULT_OUTPUT_RATE;
2447 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2448 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2449 device->Frequency = maxu(device->Frequency, 8000);
2451 fmt = "AL_FORMAT_STEREO16";
2452 if(ConfigValueStr(NULL, "format", &fmt))
2453 device->Flags |= DEVICE_CHANNELS_REQUEST;
2454 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2456 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2457 if(device->NumUpdates < 2) device->NumUpdates = 4;
2459 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2460 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2462 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2463 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2465 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2466 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2468 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2469 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2471 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2473 device->NumStereoSources = 1;
2474 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2476 // Find a playback device to open
2477 LockLists();
2478 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2480 UnlockLists();
2481 DeleteCriticalSection(&device->Mutex);
2482 free(device);
2483 alcSetError(NULL, err);
2484 return NULL;
2486 UnlockLists();
2488 do {
2489 device->next = DeviceList;
2490 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2492 TRACE("Created device %p\n", device);
2493 return device;
2496 /* alcCloseDevice
2498 * Close the specified Device
2500 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2502 ALCdevice *volatile*list;
2503 ALCcontext *ctx;
2505 LockLists();
2506 list = &DeviceList;
2507 while(*list && *list != pDevice)
2508 list = &(*list)->next;
2510 if(!*list || (*list)->IsCaptureDevice)
2512 alcSetError(*list, ALC_INVALID_DEVICE);
2513 UnlockLists();
2514 return ALC_FALSE;
2517 *list = (*list)->next;
2518 UnlockLists();
2520 if((ctx=pDevice->ContextList) != NULL)
2522 do {
2523 WARN("Releasing context %p\n", ctx);
2524 ReleaseContext(ctx, pDevice);
2525 } while((ctx=pDevice->ContextList) != NULL);
2526 ALCdevice_StopPlayback(pDevice);
2527 pDevice->Flags &= ~DEVICE_RUNNING;
2529 ALCdevice_ClosePlayback(pDevice);
2531 ALCdevice_DecRef(pDevice);
2533 return ALC_TRUE;
2537 /* alcLoopbackOpenDeviceSOFT
2539 * Open a loopback device, for manual rendering.
2541 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2543 ALCdevice *device;
2545 DO_INITCONFIG();
2547 device = calloc(1, sizeof(ALCdevice));
2548 if(!device)
2550 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2551 return NULL;
2554 //Validate device
2555 device->Funcs = &BackendLoopback.Funcs;
2556 device->ref = 1;
2557 device->Connected = ALC_TRUE;
2558 device->IsCaptureDevice = AL_FALSE;
2559 device->IsLoopbackDevice = AL_TRUE;
2560 InitializeCriticalSection(&device->Mutex);
2561 device->LastError = ALC_NO_ERROR;
2563 device->Flags = 0;
2564 device->Bs2b = NULL;
2565 device->Bs2bLevel = 0;
2566 device->szDeviceName = NULL;
2568 device->ContextList = NULL;
2570 device->MaxNoOfSources = 256;
2571 device->AuxiliaryEffectSlotMax = 4;
2572 device->NumAuxSends = MAX_SENDS;
2574 InitUIntMap(&device->BufferMap, ~0);
2575 InitUIntMap(&device->EffectMap, ~0);
2576 InitUIntMap(&device->FilterMap, ~0);
2578 //Set output format
2579 device->NumUpdates = 0;
2580 device->UpdateSize = 0;
2582 device->Frequency = 44100;
2583 device->FmtChans = DevFmtStereo;
2584 device->FmtType = DevFmtShort;
2586 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2587 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2589 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2590 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2592 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2593 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2595 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2597 device->NumStereoSources = 1;
2598 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2600 // Open the "backend"
2601 ALCdevice_OpenPlayback(device, "Loopback");
2602 do {
2603 device->next = DeviceList;
2604 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2606 TRACE("Created device %p\n", device);
2607 return device;
2610 /* alcIsRenderFormatSupportedSOFT
2612 * Determines if the loopback device supports the given format for rendering.
2614 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2616 ALCboolean ret = ALC_FALSE;
2618 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2619 alcSetError(device, ALC_INVALID_DEVICE);
2620 else if(freq <= 0)
2621 alcSetError(device, ALC_INVALID_VALUE);
2622 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2623 alcSetError(device, ALC_INVALID_ENUM);
2624 else
2626 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2627 freq >= 8000)
2628 ret = ALC_TRUE;
2630 if(device) ALCdevice_DecRef(device);
2632 return ret;
2635 /* alcRenderSamplesSOFT
2637 * Renders some samples into a buffer, using the format last set by the
2638 * attributes given to alcCreateContext.
2640 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2642 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2643 alcSetError(device, ALC_INVALID_DEVICE);
2644 else if(samples < 0 || (samples > 0 && buffer == NULL))
2645 alcSetError(device, ALC_INVALID_VALUE);
2646 else
2647 aluMixData(device, buffer, samples);
2648 if(device) ALCdevice_DecRef(device);
2652 static void ReleaseALC(ALCboolean doclose)
2654 free(alcDeviceList); alcDeviceList = NULL;
2655 alcDeviceListSize = 0;
2656 free(alcAllDeviceList); alcAllDeviceList = NULL;
2657 alcAllDeviceListSize = 0;
2658 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2659 alcCaptureDeviceListSize = 0;
2661 free(alcDefaultDeviceSpecifier);
2662 alcDefaultDeviceSpecifier = NULL;
2663 free(alcDefaultAllDeviceSpecifier);
2664 alcDefaultAllDeviceSpecifier = NULL;
2665 free(alcCaptureDefaultDeviceSpecifier);
2666 alcCaptureDefaultDeviceSpecifier = NULL;
2668 if(doclose)
2670 ALCdevice *dev;
2671 while((dev=DeviceList) != NULL)
2673 WARN("Closing device %p\n", dev);
2674 if(!dev->IsCaptureDevice) alcCloseDevice(dev);
2675 else alcCaptureCloseDevice(dev);
2678 else
2680 ALCdevice *dev;
2681 if((dev=DeviceList) != NULL)
2683 ALCuint num = 0;
2684 do {
2685 num++;
2686 } while((dev=dev->next) != NULL);
2687 WARN("%u device%s not closed\n", num, (num>1)?"s":"");
2692 ///////////////////////////////////////////////////////