Avoid size_t and ssize_t in some places
[openal-soft/android.git] / Alc / ALc.c
blob8762272e8b48bb090e7887fea7b83d82513fa1ae
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 FreeHrtf();
532 FreeALConfig();
534 ThunkExit();
535 DeleteCriticalSection(&ListLock);
536 pthread_key_delete(LocalContext);
538 if(LogFile != stderr)
539 fclose(LogFile);
540 LogFile = NULL;
543 static void alc_deinit(void)
545 int i;
547 ReleaseALC(ALC_TRUE);
549 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
550 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
552 for(i = 0;BackendList[i].Deinit;i++)
553 BackendList[i].Deinit();
554 BackendLoopback.Deinit();
556 alc_deinit_safe();
559 static void alc_initconfig(void)
561 const char *devs, *str;
562 float valf;
563 int i, n;
565 str = getenv("ALSOFT_LOGLEVEL");
566 if(str)
568 long lvl = strtol(str, NULL, 0);
569 if(lvl >= NoLog && lvl <= LogTrace)
570 LogLevel = lvl;
573 str = getenv("ALSOFT_LOGFILE");
574 if(str && str[0])
576 FILE *logfile = fopen(str, "wat");
577 if(logfile) LogFile = logfile;
578 else ERR("Failed to open log file '%s'\n", str);
581 ReadALConfig();
583 InitHrtf();
585 #ifdef _WIN32
586 RTPrioLevel = 1;
587 #else
588 RTPrioLevel = 0;
589 #endif
590 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
592 if(ConfigValueInt(NULL, "resampler", &n))
594 if(n < RESAMPLER_MAX && n > RESAMPLER_MIN)
595 DefaultResampler = n;
598 if(!TrapALCError)
599 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
601 if(!TrapALError)
602 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
604 if(ConfigValueFloat("reverb", "boost", &valf))
605 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
607 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
609 if(ConfigValueStr(NULL, "drivers", &devs))
611 int n;
612 size_t len;
613 const char *next = devs;
614 int endlist, delitem;
616 i = 0;
617 do {
618 devs = next;
619 next = strchr(devs, ',');
621 delitem = (devs[0] == '-');
622 if(devs[0] == '-') devs++;
624 if(!devs[0] || devs[0] == ',')
626 endlist = 0;
627 continue;
629 endlist = 1;
631 len = (next ? ((size_t)(next-devs)) : strlen(devs));
632 for(n = i;BackendList[n].Init;n++)
634 if(len == strlen(BackendList[n].name) &&
635 strncmp(BackendList[n].name, devs, len) == 0)
637 if(delitem)
639 do {
640 BackendList[n] = BackendList[n+1];
641 ++n;
642 } while(BackendList[n].Init);
644 else
646 struct BackendInfo Bkp = BackendList[n];
647 while(n > i)
649 BackendList[n] = BackendList[n-1];
650 --n;
652 BackendList[n] = Bkp;
654 i++;
656 break;
659 } while(next++);
661 if(endlist)
663 BackendList[i].name = NULL;
664 BackendList[i].Init = NULL;
665 BackendList[i].Deinit = NULL;
666 BackendList[i].Probe = NULL;
670 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
672 if(!BackendList[i].Init(&BackendList[i].Funcs))
674 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
675 continue;
678 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
679 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
681 PlaybackBackend = BackendList[i];
682 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
684 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
686 CaptureBackend = BackendList[i];
687 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
690 BackendLoopback.Init(&BackendLoopback.Funcs);
692 if(ConfigValueStr(NULL, "excludefx", &str))
694 size_t len;
695 const char *next = str;
697 do {
698 str = next;
699 next = strchr(str, ',');
701 if(!str[0] || next == str)
702 continue;
704 len = (next ? ((size_t)(next-str)) : strlen(str));
705 for(n = 0;EffectList[n].name;n++)
707 if(len == strlen(EffectList[n].name) &&
708 strncmp(EffectList[n].name, str, len) == 0)
709 DisabledEffects[EffectList[n].type] = AL_TRUE;
711 } while(next++);
716 static void LockLists(void)
718 EnterCriticalSection(&ListLock);
721 static void UnlockLists(void)
723 LeaveCriticalSection(&ListLock);
727 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
729 DO_INITCONFIG();
731 LockLists();
732 free(*list);
733 *list = NULL;
734 *listsize = 0;
736 if(type == CAPTURE_DEVICE_PROBE)
737 CaptureBackend.Probe(type);
738 else
739 PlaybackBackend.Probe(type);
740 UnlockLists();
743 static void ProbeDeviceList(void)
744 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
745 static void ProbeAllDeviceList(void)
746 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
747 static void ProbeCaptureDeviceList(void)
748 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
751 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
753 size_t len = strlen(name);
754 void *temp;
756 if(len == 0)
757 return;
759 temp = realloc(*List, (*ListSize) + len + 2);
760 if(!temp)
762 ERR("Realloc failed to add %s!\n", name);
763 return;
765 *List = temp;
767 memcpy((*List)+(*ListSize), name, len+1);
768 *ListSize += len+1;
769 (*List)[*ListSize] = 0;
772 #define DECL_APPEND_LIST_FUNC(type) \
773 void Append##type##List(const ALCchar *name) \
774 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
776 DECL_APPEND_LIST_FUNC(Device)
777 DECL_APPEND_LIST_FUNC(AllDevice)
778 DECL_APPEND_LIST_FUNC(CaptureDevice)
780 #undef DECL_APPEND_LIST_FUNC
783 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
784 void SetDefaultChannelOrder(ALCdevice *device)
786 switch(device->FmtChans)
788 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
789 device->DevChannels[1] = FRONT_RIGHT;
790 device->DevChannels[2] = BACK_LEFT;
791 device->DevChannels[3] = BACK_RIGHT;
792 device->DevChannels[4] = FRONT_CENTER;
793 device->DevChannels[5] = LFE;
794 return;
796 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
797 device->DevChannels[1] = FRONT_RIGHT;
798 device->DevChannels[2] = BACK_LEFT;
799 device->DevChannels[3] = BACK_RIGHT;
800 device->DevChannels[4] = FRONT_CENTER;
801 device->DevChannels[5] = LFE;
802 device->DevChannels[6] = SIDE_LEFT;
803 device->DevChannels[7] = SIDE_RIGHT;
804 return;
806 /* Same as WFX order */
807 case DevFmtMono:
808 case DevFmtStereo:
809 case DevFmtQuad:
810 case DevFmtX51Side:
811 case DevFmtX61:
812 break;
814 SetDefaultWFXChannelOrder(device);
816 /* Sets the default order used by WaveFormatEx */
817 void SetDefaultWFXChannelOrder(ALCdevice *device)
819 switch(device->FmtChans)
821 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
823 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
824 device->DevChannels[1] = FRONT_RIGHT; break;
826 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
827 device->DevChannels[1] = FRONT_RIGHT;
828 device->DevChannels[2] = BACK_LEFT;
829 device->DevChannels[3] = BACK_RIGHT; break;
831 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
832 device->DevChannels[1] = FRONT_RIGHT;
833 device->DevChannels[2] = FRONT_CENTER;
834 device->DevChannels[3] = LFE;
835 device->DevChannels[4] = BACK_LEFT;
836 device->DevChannels[5] = BACK_RIGHT; break;
838 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
839 device->DevChannels[1] = FRONT_RIGHT;
840 device->DevChannels[2] = FRONT_CENTER;
841 device->DevChannels[3] = LFE;
842 device->DevChannels[4] = SIDE_LEFT;
843 device->DevChannels[5] = SIDE_RIGHT; break;
845 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
846 device->DevChannels[1] = FRONT_RIGHT;
847 device->DevChannels[2] = FRONT_CENTER;
848 device->DevChannels[3] = LFE;
849 device->DevChannels[4] = BACK_CENTER;
850 device->DevChannels[5] = SIDE_LEFT;
851 device->DevChannels[6] = SIDE_RIGHT; break;
853 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
854 device->DevChannels[1] = FRONT_RIGHT;
855 device->DevChannels[2] = FRONT_CENTER;
856 device->DevChannels[3] = LFE;
857 device->DevChannels[4] = BACK_LEFT;
858 device->DevChannels[5] = BACK_RIGHT;
859 device->DevChannels[6] = SIDE_LEFT;
860 device->DevChannels[7] = SIDE_RIGHT; break;
865 const ALCchar *DevFmtTypeString(enum DevFmtType type)
867 switch(type)
869 case DevFmtByte: return "Signed Byte";
870 case DevFmtUByte: return "Unsigned Byte";
871 case DevFmtShort: return "Signed Short";
872 case DevFmtUShort: return "Unsigned Short";
873 case DevFmtFloat: return "Float";
875 return "(unknown type)";
877 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
879 switch(chans)
881 case DevFmtMono: return "Mono";
882 case DevFmtStereo: return "Stereo";
883 case DevFmtQuad: return "Quadraphonic";
884 case DevFmtX51: return "5.1 Surround";
885 case DevFmtX51Side: return "5.1 Side";
886 case DevFmtX61: return "6.1 Surround";
887 case DevFmtX71: return "7.1 Surround";
889 return "(unknown channels)";
892 ALuint BytesFromDevFmt(enum DevFmtType type)
894 switch(type)
896 case DevFmtByte: return sizeof(ALbyte);
897 case DevFmtUByte: return sizeof(ALubyte);
898 case DevFmtShort: return sizeof(ALshort);
899 case DevFmtUShort: return sizeof(ALushort);
900 case DevFmtFloat: return sizeof(ALfloat);
902 return 0;
904 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
906 switch(chans)
908 case DevFmtMono: return 1;
909 case DevFmtStereo: return 2;
910 case DevFmtQuad: return 4;
911 case DevFmtX51: return 6;
912 case DevFmtX51Side: return 6;
913 case DevFmtX61: return 7;
914 case DevFmtX71: return 8;
916 return 0;
918 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
919 enum DevFmtType *type)
921 static const struct {
922 ALenum format;
923 enum DevFmtChannels channels;
924 enum DevFmtType type;
925 } list[] = {
926 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
927 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
928 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
930 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
931 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
932 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
934 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
935 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
936 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
938 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
939 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
940 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
942 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
943 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
944 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
946 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
947 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
948 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
950 ALuint i;
952 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
954 if(list[i].format == format)
956 *chans = list[i].channels;
957 *type = list[i].type;
958 return AL_TRUE;
962 return AL_FALSE;
965 static ALCboolean IsValidALCType(ALCenum type)
967 switch(type)
969 case ALC_BYTE:
970 case ALC_UNSIGNED_BYTE:
971 case ALC_SHORT:
972 case ALC_UNSIGNED_SHORT:
973 case ALC_INT:
974 case ALC_UNSIGNED_INT:
975 case ALC_FLOAT:
976 return ALC_TRUE;
978 return ALC_FALSE;
981 static ALCboolean IsValidALCChannels(ALCenum channels)
983 switch(channels)
985 case ALC_MONO:
986 case ALC_STEREO:
987 case ALC_QUAD:
988 case ALC_5POINT1:
989 case ALC_6POINT1:
990 case ALC_7POINT1:
991 return ALC_TRUE;
993 return ALC_FALSE;
997 /* alcSetError
999 * Stores the latest ALC Error
1001 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1003 if(TrapALCError)
1005 #ifdef _WIN32
1006 /* DebugBreak() will cause an exception if there is no debugger */
1007 if(IsDebuggerPresent())
1008 DebugBreak();
1009 #elif defined(SIGTRAP)
1010 kill(getpid(), SIGTRAP);
1011 #endif
1014 if(device)
1015 device->LastError = errorCode;
1016 else
1017 g_eLastNullDeviceError = errorCode;
1021 /* UpdateDeviceParams
1023 * Updates device parameters according to the attribute list (caller is
1024 * responsible for holding the list lock).
1026 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1028 ALCcontext *context;
1029 ALuint i;
1031 // Check for attributes
1032 if(attrList && attrList[0])
1034 ALCuint freq, numMono, numStereo, numSends;
1035 enum DevFmtChannels schans;
1036 enum DevFmtType stype;
1037 ALuint attrIdx;
1039 // If a context is already running on the device, stop playback so the
1040 // device attributes can be updated
1041 if((device->Flags&DEVICE_RUNNING))
1042 ALCdevice_StopPlayback(device);
1043 device->Flags &= ~DEVICE_RUNNING;
1045 freq = device->Frequency;
1046 schans = device->FmtChans;
1047 stype = device->FmtType;
1048 numMono = device->NumMonoSources;
1049 numStereo = device->NumStereoSources;
1050 numSends = device->NumAuxSends;
1052 attrIdx = 0;
1053 while(attrList[attrIdx])
1055 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1056 device->IsLoopbackDevice)
1058 ALCint val = attrList[attrIdx + 1];
1059 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1061 alcSetError(device, ALC_INVALID_VALUE);
1062 return ALC_FALSE;
1064 schans = val;
1067 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1068 device->IsLoopbackDevice)
1070 ALCint val = attrList[attrIdx + 1];
1071 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1073 alcSetError(device, ALC_INVALID_VALUE);
1074 return ALC_FALSE;
1076 stype = val;
1079 if(attrList[attrIdx] == ALC_FREQUENCY)
1081 if(device->IsLoopbackDevice)
1083 freq = attrList[attrIdx + 1];
1084 if(freq < 8000)
1086 alcSetError(device, ALC_INVALID_VALUE);
1087 return ALC_FALSE;
1090 else
1092 freq = attrList[attrIdx + 1];
1093 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1097 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1099 numStereo = attrList[attrIdx + 1];
1100 if(numStereo > device->MaxNoOfSources)
1101 numStereo = device->MaxNoOfSources;
1103 numMono = device->MaxNoOfSources - numStereo;
1106 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1107 numSends = attrList[attrIdx + 1];
1109 attrIdx += 2;
1112 if(!device->IsLoopbackDevice)
1114 ConfigValueUInt(NULL, "frequency", &freq);
1115 freq = maxu(freq, 8000);
1117 ConfigValueUInt(NULL, "sends", &numSends);
1118 numSends = minu(MAX_SENDS, numSends);
1120 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1121 device->Frequency;
1123 device->Frequency = freq;
1124 device->FmtChans = schans;
1125 device->FmtType = stype;
1126 device->NumMonoSources = numMono;
1127 device->NumStereoSources = numStereo;
1128 device->NumAuxSends = numSends;
1131 if((device->Flags&DEVICE_RUNNING))
1132 return ALC_TRUE;
1134 LockDevice(device);
1135 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1136 DevFmtChannelsString(device->FmtChans),
1137 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1138 DevFmtTypeString(device->FmtType), device->Frequency,
1139 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1140 device->UpdateSize, device->NumUpdates);
1141 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1143 UnlockDevice(device);
1144 return ALC_FALSE;
1146 device->Flags |= DEVICE_RUNNING;
1147 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1148 DevFmtChannelsString(device->FmtChans),
1149 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1150 DevFmtTypeString(device->FmtType), device->Frequency,
1151 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1152 device->UpdateSize, device->NumUpdates);
1154 aluInitPanning(device);
1156 for(i = 0;i < MAXCHANNELS;i++)
1158 device->ClickRemoval[i] = 0.0f;
1159 device->PendingClicks[i] = 0.0f;
1162 device->Hrtf = NULL;
1163 device->Flags &= ~DEVICE_USE_HRTF;
1164 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1165 device->Flags |= DEVICE_USE_HRTF;
1166 if((device->Flags&DEVICE_USE_HRTF) && !(device->Hrtf=GetHrtf(device)))
1167 device->Flags &= ~DEVICE_USE_HRTF;
1168 TRACE("HRTF %s\n", (device->Flags&DEVICE_USE_HRTF)?"enabled":"disabled");
1170 if(!(device->Flags&DEVICE_USE_HRTF) && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1172 if(!device->Bs2b)
1174 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1175 bs2b_clear(device->Bs2b);
1177 bs2b_set_srate(device->Bs2b, device->Frequency);
1178 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1179 TRACE("BS2B level %d\n", device->Bs2bLevel);
1181 else
1183 free(device->Bs2b);
1184 device->Bs2b = NULL;
1185 TRACE("BS2B disabled\n");
1188 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1189 switch(device->FmtChans)
1191 case DevFmtMono:
1192 case DevFmtStereo:
1193 break;
1194 case DevFmtQuad:
1195 case DevFmtX51:
1196 case DevFmtX51Side:
1197 case DevFmtX61:
1198 case DevFmtX71:
1199 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1200 device->Flags |= DEVICE_DUPLICATE_STEREO;
1201 break;
1203 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1205 context = device->ContextList;
1206 while(context)
1208 ALsizei pos;
1210 context->UpdateSources = AL_FALSE;
1211 LockUIntMapRead(&context->EffectSlotMap);
1212 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1214 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1216 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1218 UnlockUIntMapRead(&context->EffectSlotMap);
1219 UnlockDevice(device);
1220 ALCdevice_StopPlayback(device);
1221 device->Flags &= ~DEVICE_RUNNING;
1222 return ALC_FALSE;
1224 slot->NeedsUpdate = AL_FALSE;
1225 ALeffectState_Update(slot->EffectState, context, slot);
1227 UnlockUIntMapRead(&context->EffectSlotMap);
1229 LockUIntMapRead(&context->SourceMap);
1230 for(pos = 0;pos < context->SourceMap.size;pos++)
1232 ALsource *source = context->SourceMap.array[pos].value;
1233 ALuint s = device->NumAuxSends;
1234 while(s < MAX_SENDS)
1236 if(source->Send[s].Slot)
1237 DecrementRef(&source->Send[s].Slot->ref);
1238 source->Send[s].Slot = NULL;
1239 source->Send[s].WetGain = 1.0f;
1240 source->Send[s].WetGainHF = 1.0f;
1241 s++;
1243 source->NeedsUpdate = AL_FALSE;
1244 ALsource_Update(source, context);
1246 UnlockUIntMapRead(&context->SourceMap);
1248 context = context->next;
1250 UnlockDevice(device);
1252 return ALC_TRUE;
1255 /* FreeDevice
1257 * Frees the device structure, and destroys any objects the app failed to
1258 * delete. Called once there's no more references on the device.
1260 static ALCvoid FreeDevice(ALCdevice *device)
1262 TRACE("%p\n", device);
1264 if(device->BufferMap.size > 0)
1266 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1267 ReleaseALBuffers(device);
1269 ResetUIntMap(&device->BufferMap);
1271 if(device->EffectMap.size > 0)
1273 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1274 ReleaseALEffects(device);
1276 ResetUIntMap(&device->EffectMap);
1278 if(device->FilterMap.size > 0)
1280 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1281 ReleaseALFilters(device);
1283 ResetUIntMap(&device->FilterMap);
1285 free(device->Bs2b);
1286 device->Bs2b = NULL;
1288 free(device->szDeviceName);
1289 device->szDeviceName = NULL;
1291 DeleteCriticalSection(&device->Mutex);
1293 free(device);
1297 void ALCdevice_IncRef(ALCdevice *device)
1299 RefCount ref;
1300 ref = IncrementRef(&device->ref);
1301 TRACE("%p increasing refcount to %u\n", device, ref);
1304 void ALCdevice_DecRef(ALCdevice *device)
1306 RefCount ref;
1307 ref = DecrementRef(&device->ref);
1308 TRACE("%p decreasing refcount to %u\n", device, ref);
1309 if(ref == 0) FreeDevice(device);
1312 /* VerifyDevice
1314 * Checks if the device handle is valid, and increments its ref count if so.
1316 static ALCdevice *VerifyDevice(ALCdevice *device)
1318 ALCdevice *tmpDevice;
1320 if(!device)
1321 return NULL;
1323 LockLists();
1324 tmpDevice = DeviceList;
1325 while(tmpDevice && tmpDevice != device)
1326 tmpDevice = tmpDevice->next;
1328 if(tmpDevice)
1329 ALCdevice_IncRef(tmpDevice);
1330 UnlockLists();
1331 return tmpDevice;
1335 ALCvoid LockDevice(ALCdevice *device)
1337 EnterCriticalSection(&device->Mutex);
1340 ALCvoid UnlockDevice(ALCdevice *device)
1342 LeaveCriticalSection(&device->Mutex);
1346 /* InitContext
1348 * Initializes context variables
1350 static ALvoid InitContext(ALCcontext *pContext)
1352 //Initialise listener
1353 pContext->Listener.Gain = 1.0f;
1354 pContext->Listener.MetersPerUnit = 1.0f;
1355 pContext->Listener.Position[0] = 0.0f;
1356 pContext->Listener.Position[1] = 0.0f;
1357 pContext->Listener.Position[2] = 0.0f;
1358 pContext->Listener.Velocity[0] = 0.0f;
1359 pContext->Listener.Velocity[1] = 0.0f;
1360 pContext->Listener.Velocity[2] = 0.0f;
1361 pContext->Listener.Forward[0] = 0.0f;
1362 pContext->Listener.Forward[1] = 0.0f;
1363 pContext->Listener.Forward[2] = -1.0f;
1364 pContext->Listener.Up[0] = 0.0f;
1365 pContext->Listener.Up[1] = 1.0f;
1366 pContext->Listener.Up[2] = 0.0f;
1368 //Validate pContext
1369 pContext->LastError = AL_NO_ERROR;
1370 pContext->UpdateSources = AL_FALSE;
1371 pContext->ActiveSourceCount = 0;
1372 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1373 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1375 //Set globals
1376 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1377 pContext->SourceDistanceModel = AL_FALSE;
1378 pContext->DopplerFactor = 1.0f;
1379 pContext->DopplerVelocity = 1.0f;
1380 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1381 pContext->DeferUpdates = AL_FALSE;
1383 pContext->ExtensionList = alExtList;
1387 /* FreeContext
1389 * Cleans up the context, and destroys any remaining objects the app failed to
1390 * delete. Called once there's no more references on the context.
1392 static ALCvoid FreeContext(ALCcontext *context)
1394 TRACE("%p\n", context);
1396 if(context->SourceMap.size > 0)
1398 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1399 ReleaseALSources(context);
1401 ResetUIntMap(&context->SourceMap);
1403 if(context->EffectSlotMap.size > 0)
1405 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1406 ReleaseALAuxiliaryEffectSlots(context);
1408 ResetUIntMap(&context->EffectSlotMap);
1410 context->ActiveSourceCount = 0;
1411 free(context->ActiveSources);
1412 context->ActiveSources = NULL;
1413 context->MaxActiveSources = 0;
1415 context->ActiveEffectSlotCount = 0;
1416 free(context->ActiveEffectSlots);
1417 context->ActiveEffectSlots = NULL;
1418 context->MaxActiveEffectSlots = 0;
1420 ALCdevice_DecRef(context->Device);
1421 context->Device = NULL;
1423 //Invalidate context
1424 memset(context, 0, sizeof(ALCcontext));
1425 free(context);
1428 /* ReleaseContext
1430 * Removes the context reference from the given device and removes it from
1431 * being current on the running thread or globally.
1433 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1435 ALCcontext *volatile*tmp_ctx;
1437 if(pthread_getspecific(LocalContext) == context)
1439 WARN("%p released while current on thread\n", context);
1440 pthread_setspecific(LocalContext, NULL);
1441 ALCcontext_DecRef(context);
1444 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1446 WARN("%p released while current\n", context);
1447 ALCcontext_DecRef(context);
1450 tmp_ctx = &device->ContextList;
1451 while(*tmp_ctx)
1453 if(*tmp_ctx == context)
1455 *tmp_ctx = context->next;
1456 break;
1458 tmp_ctx = &(*tmp_ctx)->next;
1461 LockDevice(device);
1462 /* Lock the device to make sure the mixer is not using the contexts in the
1463 * list before we go about deleting this one. There should be a more
1464 * efficient way of doing this. */
1465 UnlockDevice(device);
1467 ALCcontext_DecRef(context);
1470 void ALCcontext_IncRef(ALCcontext *context)
1472 RefCount ref;
1473 ref = IncrementRef(&context->ref);
1474 TRACE("%p increasing refcount to %u\n", context, ref);
1477 void ALCcontext_DecRef(ALCcontext *context)
1479 RefCount ref;
1480 ref = DecrementRef(&context->ref);
1481 TRACE("%p decreasing refcount to %u\n", context, ref);
1482 if(ref == 0) FreeContext(context);
1485 static void ReleaseThreadCtx(void *ptr)
1487 WARN("%p current for thread being destroyed\n", ptr);
1488 ALCcontext_DecRef(ptr);
1491 /* VerifyContext
1493 * Checks that the given context is valid, and increments its reference count.
1495 static ALCcontext *VerifyContext(ALCcontext *context)
1497 ALCdevice *dev;
1499 LockLists();
1500 dev = DeviceList;
1501 while(dev)
1503 ALCcontext *tmp_ctx = dev->ContextList;
1504 while(tmp_ctx)
1506 if(tmp_ctx == context)
1508 ALCcontext_IncRef(tmp_ctx);
1509 UnlockLists();
1510 return tmp_ctx;
1512 tmp_ctx = tmp_ctx->next;
1514 dev = dev->next;
1516 UnlockLists();
1518 return NULL;
1522 ALCvoid LockContext(ALCcontext *context)
1524 EnterCriticalSection(&context->Device->Mutex);
1527 ALCvoid UnlockContext(ALCcontext *context)
1529 LeaveCriticalSection(&context->Device->Mutex);
1532 /* GetContextRef
1534 * Returns the currently active context, and adds a reference without locking
1535 * it.
1537 ALCcontext *GetContextRef(void)
1539 ALCcontext *context;
1541 context = pthread_getspecific(LocalContext);
1542 if(context)
1543 ALCcontext_IncRef(context);
1544 else
1546 LockLists();
1547 context = GlobalContext;
1548 if(context)
1549 ALCcontext_IncRef(context);
1550 UnlockLists();
1553 return context;
1556 ///////////////////////////////////////////////////////
1559 ///////////////////////////////////////////////////////
1560 // ALC Functions calls
1563 // This should probably move to another c file but for now ...
1564 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1566 ALCdevice *device = NULL;
1567 ALCenum err;
1569 DO_INITCONFIG();
1571 if(!CaptureBackend.name)
1573 alcSetError(NULL, ALC_INVALID_VALUE);
1574 return NULL;
1577 if(SampleSize <= 0)
1579 alcSetError(NULL, ALC_INVALID_VALUE);
1580 return NULL;
1583 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1584 deviceName = NULL;
1586 device = calloc(1, sizeof(ALCdevice));
1587 if(!device)
1589 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1590 return NULL;
1593 //Validate device
1594 device->Funcs = &CaptureBackend.Funcs;
1595 device->ref = 1;
1596 device->Connected = ALC_TRUE;
1597 device->IsCaptureDevice = AL_TRUE;
1598 device->IsLoopbackDevice = AL_FALSE;
1599 InitializeCriticalSection(&device->Mutex);
1601 InitUIntMap(&device->BufferMap, ~0);
1602 InitUIntMap(&device->EffectMap, ~0);
1603 InitUIntMap(&device->FilterMap, ~0);
1605 device->szDeviceName = NULL;
1607 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1608 device->Frequency = frequency;
1610 device->Flags |= DEVICE_CHANNELS_REQUEST;
1611 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1613 DeleteCriticalSection(&device->Mutex);
1614 free(device);
1615 alcSetError(NULL, ALC_INVALID_ENUM);
1616 return NULL;
1619 device->UpdateSize = SampleSize;
1620 device->NumUpdates = 1;
1622 LockLists();
1623 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1625 UnlockLists();
1626 DeleteCriticalSection(&device->Mutex);
1627 free(device);
1628 alcSetError(NULL, err);
1629 return NULL;
1631 UnlockLists();
1633 do {
1634 device->next = DeviceList;
1635 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
1637 return device;
1640 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1642 ALCdevice *volatile*list;
1644 LockLists();
1645 list = &DeviceList;
1646 while(*list && *list != pDevice)
1647 list = &(*list)->next;
1649 if(!*list || !(*list)->IsCaptureDevice)
1651 alcSetError(*list, ALC_INVALID_DEVICE);
1652 UnlockLists();
1653 return ALC_FALSE;
1656 *list = (*list)->next;
1657 UnlockLists();
1659 LockDevice(pDevice);
1660 ALCdevice_CloseCapture(pDevice);
1661 UnlockDevice(pDevice);
1663 ALCdevice_DecRef(pDevice);
1665 return ALC_TRUE;
1668 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1670 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1672 alcSetError(device, ALC_INVALID_DEVICE);
1673 if(device) ALCdevice_DecRef(device);
1674 return;
1676 LockDevice(device);
1677 if(device->Connected)
1678 ALCdevice_StartCapture(device);
1679 UnlockDevice(device);
1681 ALCdevice_DecRef(device);
1684 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1686 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1688 alcSetError(device, ALC_INVALID_DEVICE);
1689 if(device) ALCdevice_DecRef(device);
1690 return;
1692 LockDevice(device);
1693 if(device->Connected)
1694 ALCdevice_StopCapture(device);
1695 UnlockDevice(device);
1697 ALCdevice_DecRef(device);
1700 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1702 ALCenum err = ALC_INVALID_DEVICE;
1703 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1705 err = ALC_INVALID_VALUE;
1706 LockDevice(device);
1707 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1708 err = ALCdevice_CaptureSamples(device, buffer, samples);
1709 UnlockDevice(device);
1711 if(err != ALC_NO_ERROR)
1712 alcSetError(device, err);
1713 if(device) ALCdevice_DecRef(device);
1717 alcGetError
1719 Return last ALC generated error code
1721 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1723 ALCenum errorCode;
1725 if(VerifyDevice(device))
1727 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1728 ALCdevice_DecRef(device);
1730 else
1731 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1733 return errorCode;
1737 /* alcSuspendContext
1739 * Not functional
1741 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1743 (void)Context;
1746 /* alcProcessContext
1748 * Not functional
1750 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1752 (void)Context;
1756 /* alcGetString
1758 * Returns information about the Device, and error strings
1760 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1762 const ALCchar *value = NULL;
1764 switch(param)
1766 case ALC_NO_ERROR:
1767 value = alcNoError;
1768 break;
1770 case ALC_INVALID_ENUM:
1771 value = alcErrInvalidEnum;
1772 break;
1774 case ALC_INVALID_VALUE:
1775 value = alcErrInvalidValue;
1776 break;
1778 case ALC_INVALID_DEVICE:
1779 value = alcErrInvalidDevice;
1780 break;
1782 case ALC_INVALID_CONTEXT:
1783 value = alcErrInvalidContext;
1784 break;
1786 case ALC_OUT_OF_MEMORY:
1787 value = alcErrOutOfMemory;
1788 break;
1790 case ALC_DEVICE_SPECIFIER:
1791 if(VerifyDevice(pDevice))
1793 value = pDevice->szDeviceName;
1794 ALCdevice_DecRef(pDevice);
1796 else
1798 ProbeDeviceList();
1799 value = alcDeviceList;
1801 break;
1803 case ALC_ALL_DEVICES_SPECIFIER:
1804 ProbeAllDeviceList();
1805 value = alcAllDeviceList;
1806 break;
1808 case ALC_CAPTURE_DEVICE_SPECIFIER:
1809 if(VerifyDevice(pDevice))
1811 value = pDevice->szDeviceName;
1812 ALCdevice_DecRef(pDevice);
1814 else
1816 ProbeCaptureDeviceList();
1817 value = alcCaptureDeviceList;
1819 break;
1821 /* Default devices are always first in the list */
1822 case ALC_DEFAULT_DEVICE_SPECIFIER:
1823 if(!alcDeviceList)
1824 ProbeDeviceList();
1826 pDevice = VerifyDevice(pDevice);
1828 free(alcDefaultDeviceSpecifier);
1829 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1830 if(!alcDefaultDeviceSpecifier)
1831 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1833 value = alcDefaultDeviceSpecifier;
1834 if(pDevice) ALCdevice_DecRef(pDevice);
1835 break;
1837 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1838 if(!alcAllDeviceList)
1839 ProbeAllDeviceList();
1841 pDevice = VerifyDevice(pDevice);
1843 free(alcDefaultAllDeviceSpecifier);
1844 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1845 alcAllDeviceList : "");
1846 if(!alcDefaultAllDeviceSpecifier)
1847 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1849 value = alcDefaultAllDeviceSpecifier;
1850 if(pDevice) ALCdevice_DecRef(pDevice);
1851 break;
1853 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1854 if(!alcCaptureDeviceList)
1855 ProbeCaptureDeviceList();
1857 pDevice = VerifyDevice(pDevice);
1859 free(alcCaptureDefaultDeviceSpecifier);
1860 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1861 alcCaptureDeviceList : "");
1862 if(!alcCaptureDefaultDeviceSpecifier)
1863 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1865 value = alcCaptureDefaultDeviceSpecifier;
1866 if(pDevice) ALCdevice_DecRef(pDevice);
1867 break;
1869 case ALC_EXTENSIONS:
1870 if(!VerifyDevice(pDevice))
1871 value = alcNoDeviceExtList;
1872 else
1874 value = alcExtensionList;
1875 ALCdevice_DecRef(pDevice);
1877 break;
1879 default:
1880 pDevice = VerifyDevice(pDevice);
1881 alcSetError(pDevice, ALC_INVALID_ENUM);
1882 if(pDevice) ALCdevice_DecRef(pDevice);
1883 break;
1886 return value;
1890 /* alcGetIntegerv
1892 * Returns information about the Device and the version of Open AL
1894 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1896 device = VerifyDevice(device);
1898 if(size == 0 || data == NULL)
1900 alcSetError(device, ALC_INVALID_VALUE);
1901 if(device) ALCdevice_DecRef(device);
1902 return;
1905 if(!device)
1907 switch(param)
1909 case ALC_MAJOR_VERSION:
1910 *data = alcMajorVersion;
1911 break;
1912 case ALC_MINOR_VERSION:
1913 *data = alcMinorVersion;
1914 break;
1916 case ALC_ATTRIBUTES_SIZE:
1917 case ALC_ALL_ATTRIBUTES:
1918 case ALC_FREQUENCY:
1919 case ALC_REFRESH:
1920 case ALC_SYNC:
1921 case ALC_MONO_SOURCES:
1922 case ALC_STEREO_SOURCES:
1923 case ALC_CAPTURE_SAMPLES:
1924 case ALC_FORMAT_CHANNELS_SOFT:
1925 case ALC_FORMAT_TYPE_SOFT:
1926 alcSetError(NULL, ALC_INVALID_DEVICE);
1927 break;
1929 default:
1930 alcSetError(NULL, ALC_INVALID_ENUM);
1931 break;
1934 else if(device->IsCaptureDevice)
1936 switch(param)
1938 case ALC_CAPTURE_SAMPLES:
1939 LockDevice(device);
1940 *data = ALCdevice_AvailableSamples(device);
1941 UnlockDevice(device);
1942 break;
1944 case ALC_CONNECTED:
1945 *data = device->Connected;
1946 break;
1948 default:
1949 alcSetError(device, ALC_INVALID_ENUM);
1950 break;
1953 else /* render device */
1955 switch(param)
1957 case ALC_MAJOR_VERSION:
1958 *data = alcMajorVersion;
1959 break;
1961 case ALC_MINOR_VERSION:
1962 *data = alcMinorVersion;
1963 break;
1965 case ALC_EFX_MAJOR_VERSION:
1966 *data = alcEFXMajorVersion;
1967 break;
1969 case ALC_EFX_MINOR_VERSION:
1970 *data = alcEFXMinorVersion;
1971 break;
1973 case ALC_ATTRIBUTES_SIZE:
1974 *data = 13;
1975 break;
1977 case ALC_ALL_ATTRIBUTES:
1978 if(size < 13)
1979 alcSetError(device, ALC_INVALID_VALUE);
1980 else
1982 int i = 0;
1984 data[i++] = ALC_FREQUENCY;
1985 data[i++] = device->Frequency;
1987 if(!device->IsLoopbackDevice)
1989 data[i++] = ALC_REFRESH;
1990 data[i++] = device->Frequency / device->UpdateSize;
1992 data[i++] = ALC_SYNC;
1993 data[i++] = ALC_FALSE;
1995 else
1997 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
1998 data[i++] = device->FmtChans;
2000 data[i++] = ALC_FORMAT_TYPE_SOFT;
2001 data[i++] = device->FmtType;
2004 data[i++] = ALC_MONO_SOURCES;
2005 data[i++] = device->NumMonoSources;
2007 data[i++] = ALC_STEREO_SOURCES;
2008 data[i++] = device->NumStereoSources;
2010 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2011 data[i++] = device->NumAuxSends;
2013 data[i++] = 0;
2015 break;
2017 case ALC_FREQUENCY:
2018 *data = device->Frequency;
2019 break;
2021 case ALC_REFRESH:
2022 if(device->IsLoopbackDevice)
2023 alcSetError(device, ALC_INVALID_DEVICE);
2024 else
2025 *data = device->Frequency / device->UpdateSize;
2026 break;
2028 case ALC_SYNC:
2029 if(device->IsLoopbackDevice)
2030 alcSetError(device, ALC_INVALID_DEVICE);
2031 else
2032 *data = ALC_FALSE;
2033 break;
2035 case ALC_FORMAT_CHANNELS_SOFT:
2036 if(!device->IsLoopbackDevice)
2037 alcSetError(device, ALC_INVALID_DEVICE);
2038 else
2039 *data = device->FmtChans;
2040 break;
2042 case ALC_FORMAT_TYPE_SOFT:
2043 if(!device->IsLoopbackDevice)
2044 alcSetError(device, ALC_INVALID_DEVICE);
2045 else
2046 *data = device->FmtType;
2047 break;
2049 case ALC_MONO_SOURCES:
2050 *data = device->NumMonoSources;
2051 break;
2053 case ALC_STEREO_SOURCES:
2054 *data = device->NumStereoSources;
2055 break;
2057 case ALC_MAX_AUXILIARY_SENDS:
2058 *data = device->NumAuxSends;
2059 break;
2061 case ALC_CONNECTED:
2062 *data = device->Connected;
2063 break;
2065 default:
2066 alcSetError(device, ALC_INVALID_ENUM);
2067 break;
2070 if(device)
2071 ALCdevice_DecRef(device);
2075 /* alcIsExtensionPresent
2077 * Determines if there is support for a particular extension
2079 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2081 ALCboolean bResult = ALC_FALSE;
2083 device = VerifyDevice(device);
2085 if(!extName)
2086 alcSetError(device, ALC_INVALID_VALUE);
2087 else
2089 size_t len = strlen(extName);
2090 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2091 while(ptr && *ptr)
2093 if(strncasecmp(ptr, extName, len) == 0 &&
2094 (ptr[len] == '\0' || isspace(ptr[len])))
2096 bResult = ALC_TRUE;
2097 break;
2099 if((ptr=strchr(ptr, ' ')) != NULL)
2101 do {
2102 ++ptr;
2103 } while(isspace(*ptr));
2107 if(device)
2108 ALCdevice_DecRef(device);
2109 return bResult;
2113 /* alcGetProcAddress
2115 * Retrieves the function address for a particular extension function
2117 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2119 ALCvoid *ptr = NULL;
2121 device = VerifyDevice(device);
2123 if(!funcName)
2124 alcSetError(device, ALC_INVALID_VALUE);
2125 else
2127 ALsizei i = 0;
2128 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2129 i++;
2130 ptr = alcFunctions[i].address;
2132 if(device)
2133 ALCdevice_DecRef(device);
2134 return ptr;
2138 /* alcGetEnumValue
2140 * Get the value for a particular ALC Enumerated Value
2142 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2144 ALCenum val = 0;
2146 device = VerifyDevice(device);
2148 if(!enumName)
2149 alcSetError(device, ALC_INVALID_VALUE);
2150 else
2152 ALsizei i = 0;
2153 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2154 i++;
2155 val = enumeration[i].value;
2157 if(device)
2158 ALCdevice_DecRef(device);
2159 return val;
2163 /* alcCreateContext
2165 * Create and attach a Context to a particular Device.
2167 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2169 ALCcontext *ALContext;
2171 LockLists();
2172 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2174 UnlockLists();
2175 alcSetError(device, ALC_INVALID_DEVICE);
2176 if(device) ALCdevice_DecRef(device);
2177 return NULL;
2180 /* Reset Context Last Error code */
2181 device->LastError = ALC_NO_ERROR;
2183 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2185 UnlockLists();
2186 alcSetError(device, ALC_INVALID_DEVICE);
2187 aluHandleDisconnect(device);
2188 ALCdevice_DecRef(device);
2189 return NULL;
2192 ALContext = calloc(1, sizeof(ALCcontext));
2193 if(ALContext)
2195 ALContext->ref = 1;
2197 ALContext->MaxActiveSources = 256;
2198 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2199 ALContext->MaxActiveSources);
2201 if(!ALContext || !ALContext->ActiveSources)
2203 if(!device->ContextList)
2205 ALCdevice_StopPlayback(device);
2206 device->Flags &= ~DEVICE_RUNNING;
2208 UnlockLists();
2210 free(ALContext);
2211 ALContext = NULL;
2213 alcSetError(device, ALC_OUT_OF_MEMORY);
2214 ALCdevice_DecRef(device);
2215 return NULL;
2218 ALContext->Device = device;
2219 ALCdevice_IncRef(device);
2220 InitContext(ALContext);
2222 ALContext->next = device->ContextList;
2223 device->ContextList = ALContext;
2224 UnlockLists();
2226 ALCdevice_DecRef(device);
2227 return ALContext;
2230 /* alcDestroyContext
2232 * Remove a Context
2234 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2236 ALCdevice *Device;
2238 LockLists();
2239 /* alcGetContextsDevice sets an error for invalid contexts */
2240 Device = alcGetContextsDevice(context);
2241 if(Device)
2243 ReleaseContext(context, Device);
2244 if(!Device->ContextList)
2246 ALCdevice_StopPlayback(Device);
2247 Device->Flags &= ~DEVICE_RUNNING;
2250 UnlockLists();
2254 /* alcGetCurrentContext
2256 * Returns the currently active Context
2258 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2260 ALCcontext *Context;
2262 Context = pthread_getspecific(LocalContext);
2263 if(!Context) Context = GlobalContext;
2265 return Context;
2268 /* alcGetThreadContext
2270 * Returns the currently active thread-local Context
2272 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2274 ALCcontext *Context;
2275 Context = pthread_getspecific(LocalContext);
2276 return Context;
2280 /* alcMakeContextCurrent
2282 * Makes the given Context the active Context
2284 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2286 /* context must be a valid Context or NULL */
2287 if(context && !(context=VerifyContext(context)))
2289 alcSetError(NULL, ALC_INVALID_CONTEXT);
2290 return ALC_FALSE;
2292 /* context's reference count is already incremented */
2293 context = ExchangePtr((void**)&GlobalContext, context);
2294 if(context) ALCcontext_DecRef(context);
2296 if((context=pthread_getspecific(LocalContext)) != NULL)
2298 pthread_setspecific(LocalContext, NULL);
2299 ALCcontext_DecRef(context);
2302 return ALC_TRUE;
2305 /* alcSetThreadContext
2307 * Makes the given Context the active Context for the current thread
2309 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2311 ALCcontext *old;
2313 /* context must be a valid Context or NULL */
2314 if(context && !(context=VerifyContext(context)))
2316 alcSetError(NULL, ALC_INVALID_CONTEXT);
2317 return ALC_FALSE;
2319 /* context's reference count is already incremented */
2320 old = pthread_getspecific(LocalContext);
2321 pthread_setspecific(LocalContext, context);
2322 if(old) ALCcontext_DecRef(old);
2324 return ALC_TRUE;
2328 /* alcGetContextsDevice
2330 * Returns the Device that a particular Context is attached to
2332 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2334 ALCdevice *Device;
2336 if(!(Context=VerifyContext(Context)))
2338 alcSetError(NULL, ALC_INVALID_CONTEXT);
2339 return NULL;
2341 Device = Context->Device;
2342 ALCcontext_DecRef(Context);
2344 return Device;
2348 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2350 static const struct {
2351 const char name[32];
2352 enum DevFmtChannels channels;
2353 enum DevFmtType type;
2354 } formats[] = {
2355 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2356 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2357 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2358 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2359 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2360 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2362 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2363 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2364 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2365 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2366 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2367 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2369 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2370 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2371 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2372 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2373 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2374 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2376 size_t i;
2378 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2380 if(strcasecmp(str, formats[i].name) == 0)
2382 *chans = formats[i].channels;
2383 *type = formats[i].type;
2384 return;
2388 ERR("Unknown format: \"%s\"\n", str);
2389 *chans = DevFmtStereo;
2390 *type = DevFmtShort;
2393 /* alcOpenDevice
2395 * Open the Device specified.
2397 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2399 const ALCchar *fmt;
2400 ALCdevice *device;
2401 ALCenum err;
2403 DO_INITCONFIG();
2405 if(!PlaybackBackend.name)
2407 alcSetError(NULL, ALC_INVALID_VALUE);
2408 return NULL;
2411 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2412 deviceName = NULL;
2414 device = calloc(1, sizeof(ALCdevice));
2415 if(!device)
2417 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2418 return NULL;
2421 //Validate device
2422 device->Funcs = &PlaybackBackend.Funcs;
2423 device->ref = 1;
2424 device->Connected = ALC_TRUE;
2425 device->IsCaptureDevice = AL_FALSE;
2426 device->IsLoopbackDevice = AL_FALSE;
2427 InitializeCriticalSection(&device->Mutex);
2428 device->LastError = ALC_NO_ERROR;
2430 device->Flags = 0;
2431 device->Bs2b = NULL;
2432 device->Bs2bLevel = 0;
2433 device->szDeviceName = NULL;
2435 device->ContextList = NULL;
2437 device->MaxNoOfSources = 256;
2438 device->AuxiliaryEffectSlotMax = 4;
2439 device->NumAuxSends = MAX_SENDS;
2441 InitUIntMap(&device->BufferMap, ~0);
2442 InitUIntMap(&device->EffectMap, ~0);
2443 InitUIntMap(&device->FilterMap, ~0);
2445 //Set output format
2446 device->NumUpdates = 4;
2447 device->UpdateSize = 1024;
2449 device->Frequency = DEFAULT_OUTPUT_RATE;
2450 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2451 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2452 device->Frequency = maxu(device->Frequency, 8000);
2454 fmt = "AL_FORMAT_STEREO16";
2455 if(ConfigValueStr(NULL, "format", &fmt))
2456 device->Flags |= DEVICE_CHANNELS_REQUEST;
2457 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2459 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2460 if(device->NumUpdates < 2) device->NumUpdates = 4;
2462 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2463 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2465 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2466 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2468 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2469 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2471 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2472 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2474 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2476 device->NumStereoSources = 1;
2477 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2479 // Find a playback device to open
2480 LockLists();
2481 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2483 UnlockLists();
2484 DeleteCriticalSection(&device->Mutex);
2485 free(device);
2486 alcSetError(NULL, err);
2487 return NULL;
2489 UnlockLists();
2491 do {
2492 device->next = DeviceList;
2493 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2495 return device;
2498 /* alcCloseDevice
2500 * Close the specified Device
2502 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2504 ALCdevice *volatile*list;
2505 ALCcontext *ctx;
2507 LockLists();
2508 list = &DeviceList;
2509 while(*list && *list != pDevice)
2510 list = &(*list)->next;
2512 if(!*list || (*list)->IsCaptureDevice)
2514 alcSetError(*list, ALC_INVALID_DEVICE);
2515 UnlockLists();
2516 return ALC_FALSE;
2519 *list = (*list)->next;
2520 UnlockLists();
2522 if((ctx=pDevice->ContextList) != NULL)
2524 do {
2525 WARN("Destroying context %p\n", ctx);
2526 ReleaseContext(ctx, pDevice);
2527 } while((ctx=pDevice->ContextList) != NULL);
2528 ALCdevice_StopPlayback(pDevice);
2529 pDevice->Flags &= ~DEVICE_RUNNING;
2531 ALCdevice_ClosePlayback(pDevice);
2533 ALCdevice_DecRef(pDevice);
2535 return ALC_TRUE;
2539 /* alcLoopbackOpenDeviceSOFT
2541 * Open a loopback device, for manual rendering.
2543 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2545 ALCdevice *device;
2547 DO_INITCONFIG();
2549 device = calloc(1, sizeof(ALCdevice));
2550 if(!device)
2552 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2553 return NULL;
2556 //Validate device
2557 device->Funcs = &BackendLoopback.Funcs;
2558 device->ref = 1;
2559 device->Connected = ALC_TRUE;
2560 device->IsCaptureDevice = AL_FALSE;
2561 device->IsLoopbackDevice = AL_TRUE;
2562 InitializeCriticalSection(&device->Mutex);
2563 device->LastError = ALC_NO_ERROR;
2565 device->Flags = 0;
2566 device->Bs2b = NULL;
2567 device->Bs2bLevel = 0;
2568 device->szDeviceName = NULL;
2570 device->ContextList = NULL;
2572 device->MaxNoOfSources = 256;
2573 device->AuxiliaryEffectSlotMax = 4;
2574 device->NumAuxSends = MAX_SENDS;
2576 InitUIntMap(&device->BufferMap, ~0);
2577 InitUIntMap(&device->EffectMap, ~0);
2578 InitUIntMap(&device->FilterMap, ~0);
2580 //Set output format
2581 device->NumUpdates = 0;
2582 device->UpdateSize = 0;
2584 device->Frequency = 44100;
2585 device->FmtChans = DevFmtStereo;
2586 device->FmtType = DevFmtShort;
2588 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2589 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2591 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2592 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2594 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2595 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2597 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2599 device->NumStereoSources = 1;
2600 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2602 // Open the "backend"
2603 ALCdevice_OpenPlayback(device, "Loopback");
2604 do {
2605 device->next = DeviceList;
2606 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2608 return device;
2611 /* alcIsRenderFormatSupportedSOFT
2613 * Determines if the loopback device supports the given format for rendering.
2615 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2617 ALCboolean ret = ALC_FALSE;
2619 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2620 alcSetError(device, ALC_INVALID_DEVICE);
2621 else if(freq <= 0)
2622 alcSetError(device, ALC_INVALID_VALUE);
2623 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2624 alcSetError(device, ALC_INVALID_ENUM);
2625 else
2627 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2628 freq >= 8000)
2629 ret = ALC_TRUE;
2631 if(device) ALCdevice_DecRef(device);
2633 return ret;
2636 /* alcRenderSamplesSOFT
2638 * Renders some samples into a buffer, using the format last set by the
2639 * attributes given to alcCreateContext.
2641 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2643 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2644 alcSetError(device, ALC_INVALID_DEVICE);
2645 else if(samples < 0 || (samples > 0 && buffer == NULL))
2646 alcSetError(device, ALC_INVALID_VALUE);
2647 else
2648 aluMixData(device, buffer, samples);
2649 if(device) ALCdevice_DecRef(device);
2653 static void ReleaseALC(ALCboolean doclose)
2655 free(alcDeviceList); alcDeviceList = NULL;
2656 alcDeviceListSize = 0;
2657 free(alcAllDeviceList); alcAllDeviceList = NULL;
2658 alcAllDeviceListSize = 0;
2659 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2660 alcCaptureDeviceListSize = 0;
2662 free(alcDefaultDeviceSpecifier);
2663 alcDefaultDeviceSpecifier = NULL;
2664 free(alcDefaultAllDeviceSpecifier);
2665 alcDefaultAllDeviceSpecifier = NULL;
2666 free(alcCaptureDefaultDeviceSpecifier);
2667 alcCaptureDefaultDeviceSpecifier = NULL;
2669 if(doclose)
2671 ALCdevice *dev;
2672 while((dev=DeviceList) != NULL)
2674 WARN("Closing device %p\n", dev);
2675 if(!dev->IsCaptureDevice) alcCloseDevice(dev);
2676 else alcCaptureCloseDevice(dev);
2679 else
2681 ALCdevice *dev;
2682 if((dev=DeviceList) != NULL)
2684 ALCuint num = 0;
2685 do {
2686 num++;
2687 } while((dev=dev->next) != NULL);
2688 WARN("%u device%s not closed\n", num, (num>1)?"s":"");
2693 ///////////////////////////////////////////////////////