Reset the ALSA device if the number of available samples grows too large
[openal-soft/android.git] / Alc / ALc.c
blob7a53a6cb0db3407889ad27d8bb6f04bf961568a6
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <math.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <memory.h>
27 #include <ctype.h>
28 #include <signal.h>
30 #include "alMain.h"
31 #include "alSource.h"
32 #include "AL/al.h"
33 #include "AL/alc.h"
34 #include "alThunk.h"
35 #include "alSource.h"
36 #include "alBuffer.h"
37 #include "alAuxEffectSlot.h"
38 #include "alError.h"
39 #include "bs2b.h"
40 #include "alu.h"
43 #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
44 static struct BackendInfo BackendList[] = {
45 #ifdef HAVE_PULSEAUDIO
46 { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs },
47 #endif
48 #ifdef HAVE_ALSA
49 { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs },
50 #endif
51 #ifdef HAVE_COREAUDIO
52 { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs },
53 #endif
54 #ifdef HAVE_OSS
55 { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs },
56 #endif
57 #ifdef HAVE_SOLARIS
58 { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs },
59 #endif
60 #ifdef HAVE_SNDIO
61 { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs },
62 #endif
63 #ifdef HAVE_MMDEVAPI
64 { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs },
65 #endif
66 #ifdef HAVE_DSOUND
67 { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs },
68 #endif
69 #ifdef HAVE_WINMM
70 { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs },
71 #endif
72 #ifdef HAVE_PORTAUDIO
73 { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs },
74 #endif
75 #ifdef HAVE_OPENSL
76 { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs },
77 #endif
79 { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs },
80 #ifdef HAVE_WAVE
81 { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs },
82 #endif
84 { NULL, NULL, NULL, NULL, EmptyFuncs }
86 static struct BackendInfo BackendLoopback = {
87 "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs
89 #undef EmptyFuncs
91 static struct BackendInfo PlaybackBackend;
92 static struct BackendInfo CaptureBackend;
94 ///////////////////////////////////////////////////////
95 // STRING and EXTENSIONS
97 typedef struct ALCfunction {
98 const ALCchar *funcName;
99 ALCvoid *address;
100 } ALCfunction;
102 typedef struct ALCenums {
103 const ALCchar *enumName;
104 ALCenum value;
105 } ALCenums;
108 static const ALCfunction alcFunctions[] = {
109 { "alcCreateContext", (ALCvoid *) alcCreateContext },
110 { "alcMakeContextCurrent", (ALCvoid *) alcMakeContextCurrent },
111 { "alcProcessContext", (ALCvoid *) alcProcessContext },
112 { "alcSuspendContext", (ALCvoid *) alcSuspendContext },
113 { "alcDestroyContext", (ALCvoid *) alcDestroyContext },
114 { "alcGetCurrentContext", (ALCvoid *) alcGetCurrentContext },
115 { "alcGetContextsDevice", (ALCvoid *) alcGetContextsDevice },
116 { "alcOpenDevice", (ALCvoid *) alcOpenDevice },
117 { "alcCloseDevice", (ALCvoid *) alcCloseDevice },
118 { "alcGetError", (ALCvoid *) alcGetError },
119 { "alcIsExtensionPresent", (ALCvoid *) alcIsExtensionPresent },
120 { "alcGetProcAddress", (ALCvoid *) alcGetProcAddress },
121 { "alcGetEnumValue", (ALCvoid *) alcGetEnumValue },
122 { "alcGetString", (ALCvoid *) alcGetString },
123 { "alcGetIntegerv", (ALCvoid *) alcGetIntegerv },
124 { "alcCaptureOpenDevice", (ALCvoid *) alcCaptureOpenDevice },
125 { "alcCaptureCloseDevice", (ALCvoid *) alcCaptureCloseDevice },
126 { "alcCaptureStart", (ALCvoid *) alcCaptureStart },
127 { "alcCaptureStop", (ALCvoid *) alcCaptureStop },
128 { "alcCaptureSamples", (ALCvoid *) alcCaptureSamples },
130 { "alcSetThreadContext", (ALCvoid *) alcSetThreadContext },
131 { "alcGetThreadContext", (ALCvoid *) alcGetThreadContext },
133 { "alcLoopbackOpenDeviceSOFT", (ALCvoid *) alcLoopbackOpenDeviceSOFT},
134 { "alcIsRenderFormatSupportedSOFT",(ALCvoid *) alcIsRenderFormatSupportedSOFT},
135 { "alcRenderSamplesSOFT", (ALCvoid *) alcRenderSamplesSOFT },
137 { "alEnable", (ALCvoid *) alEnable },
138 { "alDisable", (ALCvoid *) alDisable },
139 { "alIsEnabled", (ALCvoid *) alIsEnabled },
140 { "alGetString", (ALCvoid *) alGetString },
141 { "alGetBooleanv", (ALCvoid *) alGetBooleanv },
142 { "alGetIntegerv", (ALCvoid *) alGetIntegerv },
143 { "alGetFloatv", (ALCvoid *) alGetFloatv },
144 { "alGetDoublev", (ALCvoid *) alGetDoublev },
145 { "alGetBoolean", (ALCvoid *) alGetBoolean },
146 { "alGetInteger", (ALCvoid *) alGetInteger },
147 { "alGetFloat", (ALCvoid *) alGetFloat },
148 { "alGetDouble", (ALCvoid *) alGetDouble },
149 { "alGetError", (ALCvoid *) alGetError },
150 { "alIsExtensionPresent", (ALCvoid *) alIsExtensionPresent },
151 { "alGetProcAddress", (ALCvoid *) alGetProcAddress },
152 { "alGetEnumValue", (ALCvoid *) alGetEnumValue },
153 { "alListenerf", (ALCvoid *) alListenerf },
154 { "alListener3f", (ALCvoid *) alListener3f },
155 { "alListenerfv", (ALCvoid *) alListenerfv },
156 { "alListeneri", (ALCvoid *) alListeneri },
157 { "alListener3i", (ALCvoid *) alListener3i },
158 { "alListeneriv", (ALCvoid *) alListeneriv },
159 { "alGetListenerf", (ALCvoid *) alGetListenerf },
160 { "alGetListener3f", (ALCvoid *) alGetListener3f },
161 { "alGetListenerfv", (ALCvoid *) alGetListenerfv },
162 { "alGetListeneri", (ALCvoid *) alGetListeneri },
163 { "alGetListener3i", (ALCvoid *) alGetListener3i },
164 { "alGetListeneriv", (ALCvoid *) alGetListeneriv },
165 { "alGenSources", (ALCvoid *) alGenSources },
166 { "alDeleteSources", (ALCvoid *) alDeleteSources },
167 { "alIsSource", (ALCvoid *) alIsSource },
168 { "alSourcef", (ALCvoid *) alSourcef },
169 { "alSource3f", (ALCvoid *) alSource3f },
170 { "alSourcefv", (ALCvoid *) alSourcefv },
171 { "alSourcei", (ALCvoid *) alSourcei },
172 { "alSource3i", (ALCvoid *) alSource3i },
173 { "alSourceiv", (ALCvoid *) alSourceiv },
174 { "alGetSourcef", (ALCvoid *) alGetSourcef },
175 { "alGetSource3f", (ALCvoid *) alGetSource3f },
176 { "alGetSourcefv", (ALCvoid *) alGetSourcefv },
177 { "alGetSourcei", (ALCvoid *) alGetSourcei },
178 { "alGetSource3i", (ALCvoid *) alGetSource3i },
179 { "alGetSourceiv", (ALCvoid *) alGetSourceiv },
180 { "alSourcePlayv", (ALCvoid *) alSourcePlayv },
181 { "alSourceStopv", (ALCvoid *) alSourceStopv },
182 { "alSourceRewindv", (ALCvoid *) alSourceRewindv },
183 { "alSourcePausev", (ALCvoid *) alSourcePausev },
184 { "alSourcePlay", (ALCvoid *) alSourcePlay },
185 { "alSourceStop", (ALCvoid *) alSourceStop },
186 { "alSourceRewind", (ALCvoid *) alSourceRewind },
187 { "alSourcePause", (ALCvoid *) alSourcePause },
188 { "alSourceQueueBuffers", (ALCvoid *) alSourceQueueBuffers },
189 { "alSourceUnqueueBuffers", (ALCvoid *) alSourceUnqueueBuffers },
190 { "alGenBuffers", (ALCvoid *) alGenBuffers },
191 { "alDeleteBuffers", (ALCvoid *) alDeleteBuffers },
192 { "alIsBuffer", (ALCvoid *) alIsBuffer },
193 { "alBufferData", (ALCvoid *) alBufferData },
194 { "alBufferf", (ALCvoid *) alBufferf },
195 { "alBuffer3f", (ALCvoid *) alBuffer3f },
196 { "alBufferfv", (ALCvoid *) alBufferfv },
197 { "alBufferi", (ALCvoid *) alBufferi },
198 { "alBuffer3i", (ALCvoid *) alBuffer3i },
199 { "alBufferiv", (ALCvoid *) alBufferiv },
200 { "alGetBufferf", (ALCvoid *) alGetBufferf },
201 { "alGetBuffer3f", (ALCvoid *) alGetBuffer3f },
202 { "alGetBufferfv", (ALCvoid *) alGetBufferfv },
203 { "alGetBufferi", (ALCvoid *) alGetBufferi },
204 { "alGetBuffer3i", (ALCvoid *) alGetBuffer3i },
205 { "alGetBufferiv", (ALCvoid *) alGetBufferiv },
206 { "alDopplerFactor", (ALCvoid *) alDopplerFactor },
207 { "alDopplerVelocity", (ALCvoid *) alDopplerVelocity },
208 { "alSpeedOfSound", (ALCvoid *) alSpeedOfSound },
209 { "alDistanceModel", (ALCvoid *) alDistanceModel },
211 { "alGenFilters", (ALCvoid *) alGenFilters },
212 { "alDeleteFilters", (ALCvoid *) alDeleteFilters },
213 { "alIsFilter", (ALCvoid *) alIsFilter },
214 { "alFilteri", (ALCvoid *) alFilteri },
215 { "alFilteriv", (ALCvoid *) alFilteriv },
216 { "alFilterf", (ALCvoid *) alFilterf },
217 { "alFilterfv", (ALCvoid *) alFilterfv },
218 { "alGetFilteri", (ALCvoid *) alGetFilteri },
219 { "alGetFilteriv", (ALCvoid *) alGetFilteriv },
220 { "alGetFilterf", (ALCvoid *) alGetFilterf },
221 { "alGetFilterfv", (ALCvoid *) alGetFilterfv },
222 { "alGenEffects", (ALCvoid *) alGenEffects },
223 { "alDeleteEffects", (ALCvoid *) alDeleteEffects },
224 { "alIsEffect", (ALCvoid *) alIsEffect },
225 { "alEffecti", (ALCvoid *) alEffecti },
226 { "alEffectiv", (ALCvoid *) alEffectiv },
227 { "alEffectf", (ALCvoid *) alEffectf },
228 { "alEffectfv", (ALCvoid *) alEffectfv },
229 { "alGetEffecti", (ALCvoid *) alGetEffecti },
230 { "alGetEffectiv", (ALCvoid *) alGetEffectiv },
231 { "alGetEffectf", (ALCvoid *) alGetEffectf },
232 { "alGetEffectfv", (ALCvoid *) alGetEffectfv },
233 { "alGenAuxiliaryEffectSlots", (ALCvoid *) alGenAuxiliaryEffectSlots},
234 { "alDeleteAuxiliaryEffectSlots",(ALCvoid *) alDeleteAuxiliaryEffectSlots},
235 { "alIsAuxiliaryEffectSlot", (ALCvoid *) alIsAuxiliaryEffectSlot },
236 { "alAuxiliaryEffectSloti", (ALCvoid *) alAuxiliaryEffectSloti },
237 { "alAuxiliaryEffectSlotiv", (ALCvoid *) alAuxiliaryEffectSlotiv },
238 { "alAuxiliaryEffectSlotf", (ALCvoid *) alAuxiliaryEffectSlotf },
239 { "alAuxiliaryEffectSlotfv", (ALCvoid *) alAuxiliaryEffectSlotfv },
240 { "alGetAuxiliaryEffectSloti", (ALCvoid *) alGetAuxiliaryEffectSloti},
241 { "alGetAuxiliaryEffectSlotiv", (ALCvoid *) alGetAuxiliaryEffectSlotiv},
242 { "alGetAuxiliaryEffectSlotf", (ALCvoid *) alGetAuxiliaryEffectSlotf},
243 { "alGetAuxiliaryEffectSlotfv", (ALCvoid *) alGetAuxiliaryEffectSlotfv},
245 { "alBufferSubDataSOFT", (ALCvoid *) alBufferSubDataSOFT },
247 { "alBufferSamplesSOFT", (ALCvoid *) alBufferSamplesSOFT },
248 { "alBufferSubSamplesSOFT", (ALCvoid *) alBufferSubSamplesSOFT },
249 { "alGetBufferSamplesSOFT", (ALCvoid *) alGetBufferSamplesSOFT },
250 { "alIsBufferFormatSupportedSOFT",(ALCvoid *) alIsBufferFormatSupportedSOFT},
252 { "alDeferUpdatesSOFT", (ALCvoid *) alDeferUpdatesSOFT },
253 { "alProcessUpdatesSOFT", (ALCvoid *) alProcessUpdatesSOFT },
255 { NULL, (ALCvoid *) NULL }
258 static const ALCenums enumeration[] = {
259 // Types
260 { "ALC_INVALID", ALC_INVALID },
261 { "ALC_FALSE", ALC_FALSE },
262 { "ALC_TRUE", ALC_TRUE },
264 // ALC Properties
265 { "ALC_MAJOR_VERSION", ALC_MAJOR_VERSION },
266 { "ALC_MINOR_VERSION", ALC_MINOR_VERSION },
267 { "ALC_ATTRIBUTES_SIZE", ALC_ATTRIBUTES_SIZE },
268 { "ALC_ALL_ATTRIBUTES", ALC_ALL_ATTRIBUTES },
269 { "ALC_DEFAULT_DEVICE_SPECIFIER", ALC_DEFAULT_DEVICE_SPECIFIER },
270 { "ALC_DEVICE_SPECIFIER", ALC_DEVICE_SPECIFIER },
271 { "ALC_ALL_DEVICES_SPECIFIER", ALC_ALL_DEVICES_SPECIFIER },
272 { "ALC_DEFAULT_ALL_DEVICES_SPECIFIER", ALC_DEFAULT_ALL_DEVICES_SPECIFIER },
273 { "ALC_EXTENSIONS", ALC_EXTENSIONS },
274 { "ALC_FREQUENCY", ALC_FREQUENCY },
275 { "ALC_REFRESH", ALC_REFRESH },
276 { "ALC_SYNC", ALC_SYNC },
277 { "ALC_MONO_SOURCES", ALC_MONO_SOURCES },
278 { "ALC_STEREO_SOURCES", ALC_STEREO_SOURCES },
279 { "ALC_CAPTURE_DEVICE_SPECIFIER", ALC_CAPTURE_DEVICE_SPECIFIER },
280 { "ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER", ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER},
281 { "ALC_CAPTURE_SAMPLES", ALC_CAPTURE_SAMPLES },
282 { "ALC_CONNECTED", ALC_CONNECTED },
284 // EFX Properties
285 { "ALC_EFX_MAJOR_VERSION", ALC_EFX_MAJOR_VERSION },
286 { "ALC_EFX_MINOR_VERSION", ALC_EFX_MINOR_VERSION },
287 { "ALC_MAX_AUXILIARY_SENDS", ALC_MAX_AUXILIARY_SENDS },
289 // Loopback device Properties
290 { "ALC_FORMAT_CHANNELS_SOFT", ALC_FORMAT_CHANNELS_SOFT },
291 { "ALC_FORMAT_TYPE_SOFT", ALC_FORMAT_TYPE_SOFT },
293 // Buffer Channel Configurations
294 { "ALC_MONO_SOFT", ALC_MONO_SOFT },
295 { "ALC_STEREO_SOFT", ALC_STEREO_SOFT },
296 { "ALC_QUAD_SOFT", ALC_QUAD_SOFT },
297 { "ALC_5POINT1_SOFT", ALC_5POINT1_SOFT },
298 { "ALC_6POINT1_SOFT", ALC_6POINT1_SOFT },
299 { "ALC_7POINT1_SOFT", ALC_7POINT1_SOFT },
301 // Buffer Sample Types
302 { "ALC_BYTE_SOFT", ALC_BYTE_SOFT },
303 { "ALC_UNSIGNED_BYTE_SOFT", ALC_UNSIGNED_BYTE_SOFT },
304 { "ALC_SHORT_SOFT", ALC_SHORT_SOFT },
305 { "ALC_UNSIGNED_SHORT_SOFT", ALC_UNSIGNED_SHORT_SOFT },
306 { "ALC_INT_SOFT", ALC_INT_SOFT },
307 { "ALC_UNSIGNED_INT_SOFT", ALC_UNSIGNED_INT_SOFT },
308 { "ALC_FLOAT_SOFT", ALC_FLOAT_SOFT },
310 // ALC Error Message
311 { "ALC_NO_ERROR", ALC_NO_ERROR },
312 { "ALC_INVALID_DEVICE", ALC_INVALID_DEVICE },
313 { "ALC_INVALID_CONTEXT", ALC_INVALID_CONTEXT },
314 { "ALC_INVALID_ENUM", ALC_INVALID_ENUM },
315 { "ALC_INVALID_VALUE", ALC_INVALID_VALUE },
316 { "ALC_OUT_OF_MEMORY", ALC_OUT_OF_MEMORY },
318 { NULL, (ALCenum)0 }
320 // Error strings
321 static const ALCchar alcNoError[] = "No Error";
322 static const ALCchar alcErrInvalidDevice[] = "Invalid Device";
323 static const ALCchar alcErrInvalidContext[] = "Invalid Context";
324 static const ALCchar alcErrInvalidEnum[] = "Invalid Enum";
325 static const ALCchar alcErrInvalidValue[] = "Invalid Value";
326 static const ALCchar alcErrOutOfMemory[] = "Out of Memory";
328 /* Device lists. Sizes only include the first ending null character, not the
329 * second */
330 static ALCchar *alcDeviceList;
331 static size_t alcDeviceListSize;
332 static ALCchar *alcAllDeviceList;
333 static size_t alcAllDeviceListSize;
334 static ALCchar *alcCaptureDeviceList;
335 static size_t alcCaptureDeviceListSize;
336 /* Default is always the first in the list */
337 static ALCchar *alcDefaultDeviceSpecifier;
338 static ALCchar *alcDefaultAllDeviceSpecifier;
339 static ALCchar *alcCaptureDefaultDeviceSpecifier;
342 static const ALCchar alcNoDeviceExtList[] =
343 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
344 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
345 static const ALCchar alcExtensionList[] =
346 "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE "
347 "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX "
348 "ALC_EXT_thread_local_context ALC_SOFTX_loopback_device";
349 static const ALCint alcMajorVersion = 1;
350 static const ALCint alcMinorVersion = 1;
352 static const ALCint alcEFXMajorVersion = 1;
353 static const ALCint alcEFXMinorVersion = 0;
355 ///////////////////////////////////////////////////////
358 ///////////////////////////////////////////////////////
359 // Global Variables
361 static CRITICAL_SECTION ListLock;
363 /* Device List */
364 static ALCdevice *volatile DeviceList = NULL;
366 // Thread-local current context
367 static pthread_key_t LocalContext;
368 // Process-wide current context
369 static ALCcontext *GlobalContext;
371 /* Device Error */
372 static volatile ALCenum g_eLastNullDeviceError = ALC_NO_ERROR;
374 // Default context extensions
375 static const ALchar alExtList[] =
376 "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 "
377 "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW "
378 "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model "
379 "AL_LOKI_quadriphonic AL_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(void);
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 UIntMap TlsDestructor;
420 #ifndef AL_LIBTYPE_STATIC
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();
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();
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_SOFT:
964 case ALC_UNSIGNED_BYTE_SOFT:
965 case ALC_SHORT_SOFT:
966 case ALC_UNSIGNED_SHORT_SOFT:
967 case ALC_INT_SOFT:
968 case ALC_UNSIGNED_INT_SOFT:
969 case ALC_FLOAT_SOFT:
970 return ALC_TRUE;
972 return ALC_FALSE;
975 static ALCboolean IsValidALCChannels(ALCenum channels)
977 switch(channels)
979 case ALC_MONO_SOFT:
980 case ALC_STEREO_SOFT:
981 case ALC_QUAD_SOFT:
982 case ALC_5POINT1_SOFT:
983 case ALC_6POINT1_SOFT:
984 case ALC_7POINT1_SOFT:
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 raise(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 int oldMode;
1024 ALuint i;
1026 // Check for attributes
1027 if(attrList && attrList[0])
1029 ALCuint freq, numMono, numStereo, numSends;
1030 enum DevFmtChannels schans;
1031 enum DevFmtType stype;
1032 ALuint attrIdx;
1034 // If a context is already running on the device, stop playback so the
1035 // device attributes can be updated
1036 if((device->Flags&DEVICE_RUNNING))
1037 ALCdevice_StopPlayback(device);
1038 device->Flags &= ~DEVICE_RUNNING;
1040 freq = device->Frequency;
1041 schans = device->FmtChans;
1042 stype = device->FmtType;
1043 numMono = device->NumMonoSources;
1044 numStereo = device->NumStereoSources;
1045 numSends = device->NumAuxSends;
1047 attrIdx = 0;
1048 while(attrList[attrIdx])
1050 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1051 device->IsLoopbackDevice)
1053 ALCint val = attrList[attrIdx + 1];
1054 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1056 alcSetError(device, ALC_INVALID_VALUE);
1057 return ALC_FALSE;
1059 schans = val;
1062 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1063 device->IsLoopbackDevice)
1065 ALCint val = attrList[attrIdx + 1];
1066 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1068 alcSetError(device, ALC_INVALID_VALUE);
1069 return ALC_FALSE;
1071 stype = val;
1074 if(attrList[attrIdx] == ALC_FREQUENCY)
1076 if(device->IsLoopbackDevice)
1078 freq = attrList[attrIdx + 1];
1079 if(freq < 8000)
1081 alcSetError(device, ALC_INVALID_VALUE);
1082 return ALC_FALSE;
1085 else
1087 freq = attrList[attrIdx + 1];
1088 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1092 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1094 numStereo = attrList[attrIdx + 1];
1095 if(numStereo > device->MaxNoOfSources)
1096 numStereo = device->MaxNoOfSources;
1098 numMono = device->MaxNoOfSources - numStereo;
1101 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1102 numSends = attrList[attrIdx + 1];
1104 attrIdx += 2;
1107 if(!device->IsLoopbackDevice)
1109 ConfigValueUInt(NULL, "frequency", &freq);
1110 freq = maxu(freq, 8000);
1112 ConfigValueUInt(NULL, "sends", &numSends);
1113 numSends = minu(MAX_SENDS, numSends);
1115 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1116 device->Frequency;
1118 device->Frequency = freq;
1119 device->FmtChans = schans;
1120 device->FmtType = stype;
1121 device->NumMonoSources = numMono;
1122 device->NumStereoSources = numStereo;
1123 device->NumAuxSends = numSends;
1126 if((device->Flags&DEVICE_RUNNING))
1127 return ALC_TRUE;
1129 LockDevice(device);
1130 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1131 DevFmtChannelsString(device->FmtChans),
1132 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1133 DevFmtTypeString(device->FmtType), device->Frequency,
1134 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1135 device->UpdateSize, device->NumUpdates);
1136 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1138 UnlockDevice(device);
1139 return ALC_FALSE;
1141 device->Flags |= DEVICE_RUNNING;
1142 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1143 DevFmtChannelsString(device->FmtChans),
1144 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1145 DevFmtTypeString(device->FmtType), device->Frequency,
1146 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1147 device->UpdateSize, device->NumUpdates);
1149 aluInitPanning(device);
1151 for(i = 0;i < MAXCHANNELS;i++)
1153 device->ClickRemoval[i] = 0.0f;
1154 device->PendingClicks[i] = 0.0f;
1157 device->Hrtf = NULL;
1158 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1159 device->Hrtf = GetHrtf(device);
1160 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1162 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1164 if(!device->Bs2b)
1166 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1167 bs2b_clear(device->Bs2b);
1169 bs2b_set_srate(device->Bs2b, device->Frequency);
1170 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1171 TRACE("BS2B level %d\n", device->Bs2bLevel);
1173 else
1175 free(device->Bs2b);
1176 device->Bs2b = NULL;
1177 TRACE("BS2B disabled\n");
1180 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1181 switch(device->FmtChans)
1183 case DevFmtMono:
1184 case DevFmtStereo:
1185 break;
1186 case DevFmtQuad:
1187 case DevFmtX51:
1188 case DevFmtX51Side:
1189 case DevFmtX61:
1190 case DevFmtX71:
1191 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1192 device->Flags |= DEVICE_DUPLICATE_STEREO;
1193 break;
1195 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1197 oldMode = SetMixerFPUMode();
1198 context = device->ContextList;
1199 while(context)
1201 ALsizei pos;
1203 context->UpdateSources = AL_FALSE;
1204 LockUIntMapRead(&context->EffectSlotMap);
1205 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1207 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1209 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1211 UnlockUIntMapRead(&context->EffectSlotMap);
1212 UnlockDevice(device);
1213 ALCdevice_StopPlayback(device);
1214 device->Flags &= ~DEVICE_RUNNING;
1215 return ALC_FALSE;
1217 slot->NeedsUpdate = AL_FALSE;
1218 ALeffectState_Update(slot->EffectState, context, slot);
1220 UnlockUIntMapRead(&context->EffectSlotMap);
1222 LockUIntMapRead(&context->SourceMap);
1223 for(pos = 0;pos < context->SourceMap.size;pos++)
1225 ALsource *source = context->SourceMap.array[pos].value;
1226 ALuint s = device->NumAuxSends;
1227 while(s < MAX_SENDS)
1229 if(source->Send[s].Slot)
1230 DecrementRef(&source->Send[s].Slot->ref);
1231 source->Send[s].Slot = NULL;
1232 source->Send[s].WetGain = 1.0f;
1233 source->Send[s].WetGainHF = 1.0f;
1234 s++;
1236 source->NeedsUpdate = AL_FALSE;
1237 ALsource_Update(source, context);
1239 UnlockUIntMapRead(&context->SourceMap);
1241 context = context->next;
1243 RestoreFPUMode(oldMode);
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 ALint i, j;
1348 //Initialise listener
1349 pContext->Listener.Gain = 1.0f;
1350 pContext->Listener.MetersPerUnit = 1.0f;
1351 pContext->Listener.Position[0] = 0.0f;
1352 pContext->Listener.Position[1] = 0.0f;
1353 pContext->Listener.Position[2] = 0.0f;
1354 pContext->Listener.Velocity[0] = 0.0f;
1355 pContext->Listener.Velocity[1] = 0.0f;
1356 pContext->Listener.Velocity[2] = 0.0f;
1357 pContext->Listener.Forward[0] = 0.0f;
1358 pContext->Listener.Forward[1] = 0.0f;
1359 pContext->Listener.Forward[2] = -1.0f;
1360 pContext->Listener.Up[0] = 0.0f;
1361 pContext->Listener.Up[1] = 1.0f;
1362 pContext->Listener.Up[2] = 0.0f;
1363 for(i = 0;i < 4;i++)
1365 for(j = 0;j < 4;j++)
1366 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1369 //Validate pContext
1370 pContext->LastError = AL_NO_ERROR;
1371 pContext->UpdateSources = AL_FALSE;
1372 pContext->ActiveSourceCount = 0;
1373 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1374 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1376 //Set globals
1377 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1378 pContext->SourceDistanceModel = AL_FALSE;
1379 pContext->DopplerFactor = 1.0f;
1380 pContext->DopplerVelocity = 1.0f;
1381 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1382 pContext->DeferUpdates = AL_FALSE;
1384 pContext->ExtensionList = alExtList;
1388 /* FreeContext
1390 * Cleans up the context, and destroys any remaining objects the app failed to
1391 * delete. Called once there's no more references on the context.
1393 static ALCvoid FreeContext(ALCcontext *context)
1395 TRACE("%p\n", context);
1397 if(context->SourceMap.size > 0)
1399 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1400 ReleaseALSources(context);
1402 ResetUIntMap(&context->SourceMap);
1404 if(context->EffectSlotMap.size > 0)
1406 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1407 ReleaseALAuxiliaryEffectSlots(context);
1409 ResetUIntMap(&context->EffectSlotMap);
1411 context->ActiveSourceCount = 0;
1412 free(context->ActiveSources);
1413 context->ActiveSources = NULL;
1414 context->MaxActiveSources = 0;
1416 context->ActiveEffectSlotCount = 0;
1417 free(context->ActiveEffectSlots);
1418 context->ActiveEffectSlots = NULL;
1419 context->MaxActiveEffectSlots = 0;
1421 ALCdevice_DecRef(context->Device);
1422 context->Device = NULL;
1424 //Invalidate context
1425 memset(context, 0, sizeof(ALCcontext));
1426 free(context);
1429 /* ReleaseContext
1431 * Removes the context reference from the given device and removes it from
1432 * being current on the running thread or globally.
1434 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1436 ALCcontext *volatile*tmp_ctx;
1438 if(pthread_getspecific(LocalContext) == context)
1440 WARN("%p released while current on thread\n", context);
1441 pthread_setspecific(LocalContext, NULL);
1442 ALCcontext_DecRef(context);
1445 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1447 WARN("%p released while current\n", context);
1448 ALCcontext_DecRef(context);
1451 tmp_ctx = &device->ContextList;
1452 while(*tmp_ctx)
1454 if(*tmp_ctx == context)
1456 *tmp_ctx = context->next;
1457 break;
1459 tmp_ctx = &(*tmp_ctx)->next;
1462 LockDevice(device);
1463 /* Lock the device to make sure the mixer is not using the contexts in the
1464 * list before we go about deleting this one. There should be a more
1465 * efficient way of doing this. */
1466 UnlockDevice(device);
1468 ALCcontext_DecRef(context);
1471 void ALCcontext_IncRef(ALCcontext *context)
1473 RefCount ref;
1474 ref = IncrementRef(&context->ref);
1475 TRACEREF("%p increasing refcount to %u\n", context, ref);
1478 void ALCcontext_DecRef(ALCcontext *context)
1480 RefCount ref;
1481 ref = DecrementRef(&context->ref);
1482 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1483 if(ref == 0) FreeContext(context);
1486 static void ReleaseThreadCtx(void *ptr)
1488 WARN("%p current for thread being destroyed\n", ptr);
1489 ALCcontext_DecRef(ptr);
1492 /* VerifyContext
1494 * Checks that the given context is valid, and increments its reference count.
1496 static ALCcontext *VerifyContext(ALCcontext *context)
1498 ALCdevice *dev;
1500 LockLists();
1501 dev = DeviceList;
1502 while(dev)
1504 ALCcontext *tmp_ctx = dev->ContextList;
1505 while(tmp_ctx)
1507 if(tmp_ctx == context)
1509 ALCcontext_IncRef(tmp_ctx);
1510 UnlockLists();
1511 return tmp_ctx;
1513 tmp_ctx = tmp_ctx->next;
1515 dev = dev->next;
1517 UnlockLists();
1519 return NULL;
1523 ALCvoid LockContext(ALCcontext *context)
1525 EnterCriticalSection(&context->Device->Mutex);
1528 ALCvoid UnlockContext(ALCcontext *context)
1530 LeaveCriticalSection(&context->Device->Mutex);
1533 /* GetContextRef
1535 * Returns the currently active context, and adds a reference without locking
1536 * it.
1538 ALCcontext *GetContextRef(void)
1540 ALCcontext *context;
1542 context = pthread_getspecific(LocalContext);
1543 if(context)
1544 ALCcontext_IncRef(context);
1545 else
1547 LockLists();
1548 context = GlobalContext;
1549 if(context)
1550 ALCcontext_IncRef(context);
1551 UnlockLists();
1554 return context;
1557 ///////////////////////////////////////////////////////
1560 ///////////////////////////////////////////////////////
1561 // ALC Functions calls
1564 // This should probably move to another c file but for now ...
1565 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1567 ALCdevice *device = NULL;
1568 ALCenum err;
1570 DO_INITCONFIG();
1572 if(!CaptureBackend.name)
1574 alcSetError(NULL, ALC_INVALID_VALUE);
1575 return NULL;
1578 if(SampleSize <= 0)
1580 alcSetError(NULL, ALC_INVALID_VALUE);
1581 return NULL;
1584 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1585 deviceName = NULL;
1587 device = calloc(1, sizeof(ALCdevice));
1588 if(!device)
1590 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1591 return NULL;
1594 //Validate device
1595 device->Funcs = &CaptureBackend.Funcs;
1596 device->ref = 1;
1597 device->Connected = ALC_TRUE;
1598 device->IsCaptureDevice = AL_TRUE;
1599 device->IsLoopbackDevice = AL_FALSE;
1600 InitializeCriticalSection(&device->Mutex);
1602 InitUIntMap(&device->BufferMap, ~0);
1603 InitUIntMap(&device->EffectMap, ~0);
1604 InitUIntMap(&device->FilterMap, ~0);
1606 device->szDeviceName = NULL;
1608 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1609 device->Frequency = frequency;
1611 device->Flags |= DEVICE_CHANNELS_REQUEST;
1612 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1614 DeleteCriticalSection(&device->Mutex);
1615 free(device);
1616 alcSetError(NULL, ALC_INVALID_ENUM);
1617 return NULL;
1620 device->UpdateSize = SampleSize;
1621 device->NumUpdates = 1;
1623 LockLists();
1624 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1626 UnlockLists();
1627 DeleteCriticalSection(&device->Mutex);
1628 free(device);
1629 alcSetError(NULL, err);
1630 return NULL;
1632 UnlockLists();
1634 do {
1635 device->next = DeviceList;
1636 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
1638 TRACE("Created device %p\n", device);
1639 return device;
1642 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1644 ALCdevice *volatile*list;
1646 LockLists();
1647 list = &DeviceList;
1648 while(*list && *list != pDevice)
1649 list = &(*list)->next;
1651 if(!*list || !(*list)->IsCaptureDevice)
1653 alcSetError(*list, ALC_INVALID_DEVICE);
1654 UnlockLists();
1655 return ALC_FALSE;
1658 *list = (*list)->next;
1659 UnlockLists();
1661 LockDevice(pDevice);
1662 ALCdevice_CloseCapture(pDevice);
1663 UnlockDevice(pDevice);
1665 ALCdevice_DecRef(pDevice);
1667 return ALC_TRUE;
1670 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1672 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1674 alcSetError(device, ALC_INVALID_DEVICE);
1675 if(device) ALCdevice_DecRef(device);
1676 return;
1678 LockDevice(device);
1679 if(device->Connected)
1680 ALCdevice_StartCapture(device);
1681 UnlockDevice(device);
1683 ALCdevice_DecRef(device);
1686 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1688 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1690 alcSetError(device, ALC_INVALID_DEVICE);
1691 if(device) ALCdevice_DecRef(device);
1692 return;
1694 LockDevice(device);
1695 if(device->Connected)
1696 ALCdevice_StopCapture(device);
1697 UnlockDevice(device);
1699 ALCdevice_DecRef(device);
1702 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1704 ALCenum err = ALC_INVALID_DEVICE;
1705 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1707 err = ALC_INVALID_VALUE;
1708 LockDevice(device);
1709 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1710 err = ALCdevice_CaptureSamples(device, buffer, samples);
1711 UnlockDevice(device);
1713 if(err != ALC_NO_ERROR)
1714 alcSetError(device, err);
1715 if(device) ALCdevice_DecRef(device);
1719 alcGetError
1721 Return last ALC generated error code
1723 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1725 ALCenum errorCode;
1727 if(VerifyDevice(device))
1729 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1730 ALCdevice_DecRef(device);
1732 else
1733 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1735 return errorCode;
1739 /* alcSuspendContext
1741 * Not functional
1743 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1745 (void)Context;
1748 /* alcProcessContext
1750 * Not functional
1752 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1754 (void)Context;
1758 /* alcGetString
1760 * Returns information about the Device, and error strings
1762 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1764 const ALCchar *value = NULL;
1766 switch(param)
1768 case ALC_NO_ERROR:
1769 value = alcNoError;
1770 break;
1772 case ALC_INVALID_ENUM:
1773 value = alcErrInvalidEnum;
1774 break;
1776 case ALC_INVALID_VALUE:
1777 value = alcErrInvalidValue;
1778 break;
1780 case ALC_INVALID_DEVICE:
1781 value = alcErrInvalidDevice;
1782 break;
1784 case ALC_INVALID_CONTEXT:
1785 value = alcErrInvalidContext;
1786 break;
1788 case ALC_OUT_OF_MEMORY:
1789 value = alcErrOutOfMemory;
1790 break;
1792 case ALC_DEVICE_SPECIFIER:
1793 if(VerifyDevice(pDevice))
1795 value = pDevice->szDeviceName;
1796 ALCdevice_DecRef(pDevice);
1798 else
1800 ProbeDeviceList();
1801 value = alcDeviceList;
1803 break;
1805 case ALC_ALL_DEVICES_SPECIFIER:
1806 ProbeAllDeviceList();
1807 value = alcAllDeviceList;
1808 break;
1810 case ALC_CAPTURE_DEVICE_SPECIFIER:
1811 if(VerifyDevice(pDevice))
1813 value = pDevice->szDeviceName;
1814 ALCdevice_DecRef(pDevice);
1816 else
1818 ProbeCaptureDeviceList();
1819 value = alcCaptureDeviceList;
1821 break;
1823 /* Default devices are always first in the list */
1824 case ALC_DEFAULT_DEVICE_SPECIFIER:
1825 if(!alcDeviceList)
1826 ProbeDeviceList();
1828 pDevice = VerifyDevice(pDevice);
1830 free(alcDefaultDeviceSpecifier);
1831 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1832 if(!alcDefaultDeviceSpecifier)
1833 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1835 value = alcDefaultDeviceSpecifier;
1836 if(pDevice) ALCdevice_DecRef(pDevice);
1837 break;
1839 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1840 if(!alcAllDeviceList)
1841 ProbeAllDeviceList();
1843 pDevice = VerifyDevice(pDevice);
1845 free(alcDefaultAllDeviceSpecifier);
1846 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1847 alcAllDeviceList : "");
1848 if(!alcDefaultAllDeviceSpecifier)
1849 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1851 value = alcDefaultAllDeviceSpecifier;
1852 if(pDevice) ALCdevice_DecRef(pDevice);
1853 break;
1855 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1856 if(!alcCaptureDeviceList)
1857 ProbeCaptureDeviceList();
1859 pDevice = VerifyDevice(pDevice);
1861 free(alcCaptureDefaultDeviceSpecifier);
1862 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1863 alcCaptureDeviceList : "");
1864 if(!alcCaptureDefaultDeviceSpecifier)
1865 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1867 value = alcCaptureDefaultDeviceSpecifier;
1868 if(pDevice) ALCdevice_DecRef(pDevice);
1869 break;
1871 case ALC_EXTENSIONS:
1872 if(!VerifyDevice(pDevice))
1873 value = alcNoDeviceExtList;
1874 else
1876 value = alcExtensionList;
1877 ALCdevice_DecRef(pDevice);
1879 break;
1881 default:
1882 pDevice = VerifyDevice(pDevice);
1883 alcSetError(pDevice, ALC_INVALID_ENUM);
1884 if(pDevice) ALCdevice_DecRef(pDevice);
1885 break;
1888 return value;
1892 /* alcGetIntegerv
1894 * Returns information about the Device and the version of Open AL
1896 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1898 device = VerifyDevice(device);
1900 if(size == 0 || data == NULL)
1902 alcSetError(device, ALC_INVALID_VALUE);
1903 if(device) ALCdevice_DecRef(device);
1904 return;
1907 if(!device)
1909 switch(param)
1911 case ALC_MAJOR_VERSION:
1912 *data = alcMajorVersion;
1913 break;
1914 case ALC_MINOR_VERSION:
1915 *data = alcMinorVersion;
1916 break;
1918 case ALC_ATTRIBUTES_SIZE:
1919 case ALC_ALL_ATTRIBUTES:
1920 case ALC_FREQUENCY:
1921 case ALC_REFRESH:
1922 case ALC_SYNC:
1923 case ALC_MONO_SOURCES:
1924 case ALC_STEREO_SOURCES:
1925 case ALC_CAPTURE_SAMPLES:
1926 case ALC_FORMAT_CHANNELS_SOFT:
1927 case ALC_FORMAT_TYPE_SOFT:
1928 alcSetError(NULL, ALC_INVALID_DEVICE);
1929 break;
1931 default:
1932 alcSetError(NULL, ALC_INVALID_ENUM);
1933 break;
1936 else if(device->IsCaptureDevice)
1938 switch(param)
1940 case ALC_CAPTURE_SAMPLES:
1941 LockDevice(device);
1942 *data = ALCdevice_AvailableSamples(device);
1943 UnlockDevice(device);
1944 break;
1946 case ALC_CONNECTED:
1947 *data = device->Connected;
1948 break;
1950 default:
1951 alcSetError(device, ALC_INVALID_ENUM);
1952 break;
1955 else /* render device */
1957 switch(param)
1959 case ALC_MAJOR_VERSION:
1960 *data = alcMajorVersion;
1961 break;
1963 case ALC_MINOR_VERSION:
1964 *data = alcMinorVersion;
1965 break;
1967 case ALC_EFX_MAJOR_VERSION:
1968 *data = alcEFXMajorVersion;
1969 break;
1971 case ALC_EFX_MINOR_VERSION:
1972 *data = alcEFXMinorVersion;
1973 break;
1975 case ALC_ATTRIBUTES_SIZE:
1976 *data = 13;
1977 break;
1979 case ALC_ALL_ATTRIBUTES:
1980 if(size < 13)
1981 alcSetError(device, ALC_INVALID_VALUE);
1982 else
1984 int i = 0;
1986 data[i++] = ALC_FREQUENCY;
1987 data[i++] = device->Frequency;
1989 if(!device->IsLoopbackDevice)
1991 data[i++] = ALC_REFRESH;
1992 data[i++] = device->Frequency / device->UpdateSize;
1994 data[i++] = ALC_SYNC;
1995 data[i++] = ALC_FALSE;
1997 else
1999 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2000 data[i++] = device->FmtChans;
2002 data[i++] = ALC_FORMAT_TYPE_SOFT;
2003 data[i++] = device->FmtType;
2006 data[i++] = ALC_MONO_SOURCES;
2007 data[i++] = device->NumMonoSources;
2009 data[i++] = ALC_STEREO_SOURCES;
2010 data[i++] = device->NumStereoSources;
2012 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2013 data[i++] = device->NumAuxSends;
2015 data[i++] = 0;
2017 break;
2019 case ALC_FREQUENCY:
2020 *data = device->Frequency;
2021 break;
2023 case ALC_REFRESH:
2024 if(device->IsLoopbackDevice)
2025 alcSetError(device, ALC_INVALID_DEVICE);
2026 else
2027 *data = device->Frequency / device->UpdateSize;
2028 break;
2030 case ALC_SYNC:
2031 if(device->IsLoopbackDevice)
2032 alcSetError(device, ALC_INVALID_DEVICE);
2033 else
2034 *data = ALC_FALSE;
2035 break;
2037 case ALC_FORMAT_CHANNELS_SOFT:
2038 if(!device->IsLoopbackDevice)
2039 alcSetError(device, ALC_INVALID_DEVICE);
2040 else
2041 *data = device->FmtChans;
2042 break;
2044 case ALC_FORMAT_TYPE_SOFT:
2045 if(!device->IsLoopbackDevice)
2046 alcSetError(device, ALC_INVALID_DEVICE);
2047 else
2048 *data = device->FmtType;
2049 break;
2051 case ALC_MONO_SOURCES:
2052 *data = device->NumMonoSources;
2053 break;
2055 case ALC_STEREO_SOURCES:
2056 *data = device->NumStereoSources;
2057 break;
2059 case ALC_MAX_AUXILIARY_SENDS:
2060 *data = device->NumAuxSends;
2061 break;
2063 case ALC_CONNECTED:
2064 *data = device->Connected;
2065 break;
2067 default:
2068 alcSetError(device, ALC_INVALID_ENUM);
2069 break;
2072 if(device)
2073 ALCdevice_DecRef(device);
2077 /* alcIsExtensionPresent
2079 * Determines if there is support for a particular extension
2081 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2083 ALCboolean bResult = ALC_FALSE;
2085 device = VerifyDevice(device);
2087 if(!extName)
2088 alcSetError(device, ALC_INVALID_VALUE);
2089 else
2091 size_t len = strlen(extName);
2092 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2093 while(ptr && *ptr)
2095 if(strncasecmp(ptr, extName, len) == 0 &&
2096 (ptr[len] == '\0' || isspace(ptr[len])))
2098 bResult = ALC_TRUE;
2099 break;
2101 if((ptr=strchr(ptr, ' ')) != NULL)
2103 do {
2104 ++ptr;
2105 } while(isspace(*ptr));
2109 if(device)
2110 ALCdevice_DecRef(device);
2111 return bResult;
2115 /* alcGetProcAddress
2117 * Retrieves the function address for a particular extension function
2119 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2121 ALCvoid *ptr = NULL;
2123 device = VerifyDevice(device);
2125 if(!funcName)
2126 alcSetError(device, ALC_INVALID_VALUE);
2127 else
2129 ALsizei i = 0;
2130 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2131 i++;
2132 ptr = alcFunctions[i].address;
2134 if(device)
2135 ALCdevice_DecRef(device);
2136 return ptr;
2140 /* alcGetEnumValue
2142 * Get the value for a particular ALC Enumerated Value
2144 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2146 ALCenum val = 0;
2148 device = VerifyDevice(device);
2150 if(!enumName)
2151 alcSetError(device, ALC_INVALID_VALUE);
2152 else
2154 ALsizei i = 0;
2155 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2156 i++;
2157 val = enumeration[i].value;
2159 if(device)
2160 ALCdevice_DecRef(device);
2161 return val;
2165 /* alcCreateContext
2167 * Create and attach a Context to a particular Device.
2169 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2171 ALCcontext *ALContext;
2173 LockLists();
2174 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2176 UnlockLists();
2177 alcSetError(device, ALC_INVALID_DEVICE);
2178 if(device) ALCdevice_DecRef(device);
2179 return NULL;
2182 /* Reset Context Last Error code */
2183 device->LastError = ALC_NO_ERROR;
2185 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2187 UnlockLists();
2188 alcSetError(device, ALC_INVALID_DEVICE);
2189 aluHandleDisconnect(device);
2190 ALCdevice_DecRef(device);
2191 return NULL;
2194 ALContext = calloc(1, sizeof(ALCcontext));
2195 if(ALContext)
2197 ALContext->ref = 1;
2199 ALContext->MaxActiveSources = 256;
2200 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2201 ALContext->MaxActiveSources);
2203 if(!ALContext || !ALContext->ActiveSources)
2205 if(!device->ContextList)
2207 ALCdevice_StopPlayback(device);
2208 device->Flags &= ~DEVICE_RUNNING;
2210 UnlockLists();
2212 free(ALContext);
2213 ALContext = NULL;
2215 alcSetError(device, ALC_OUT_OF_MEMORY);
2216 ALCdevice_DecRef(device);
2217 return NULL;
2220 ALContext->Device = device;
2221 ALCdevice_IncRef(device);
2222 InitContext(ALContext);
2224 ALContext->next = device->ContextList;
2225 device->ContextList = ALContext;
2226 UnlockLists();
2228 ALCdevice_DecRef(device);
2230 TRACE("Created context %p\n", ALContext);
2231 return ALContext;
2234 /* alcDestroyContext
2236 * Remove a Context
2238 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2240 ALCdevice *Device;
2242 LockLists();
2243 /* alcGetContextsDevice sets an error for invalid contexts */
2244 Device = alcGetContextsDevice(context);
2245 if(Device)
2247 ReleaseContext(context, Device);
2248 if(!Device->ContextList)
2250 ALCdevice_StopPlayback(Device);
2251 Device->Flags &= ~DEVICE_RUNNING;
2254 UnlockLists();
2258 /* alcGetCurrentContext
2260 * Returns the currently active Context
2262 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2264 ALCcontext *Context;
2266 Context = pthread_getspecific(LocalContext);
2267 if(!Context) Context = GlobalContext;
2269 return Context;
2272 /* alcGetThreadContext
2274 * Returns the currently active thread-local Context
2276 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2278 ALCcontext *Context;
2279 Context = pthread_getspecific(LocalContext);
2280 return Context;
2284 /* alcMakeContextCurrent
2286 * Makes the given Context the active Context
2288 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2290 /* context must be a valid Context or NULL */
2291 if(context && !(context=VerifyContext(context)))
2293 alcSetError(NULL, ALC_INVALID_CONTEXT);
2294 return ALC_FALSE;
2296 /* context's reference count is already incremented */
2297 context = ExchangePtr((void**)&GlobalContext, context);
2298 if(context) ALCcontext_DecRef(context);
2300 if((context=pthread_getspecific(LocalContext)) != NULL)
2302 pthread_setspecific(LocalContext, NULL);
2303 ALCcontext_DecRef(context);
2306 return ALC_TRUE;
2309 /* alcSetThreadContext
2311 * Makes the given Context the active Context for the current thread
2313 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2315 ALCcontext *old;
2317 /* context must be a valid Context or NULL */
2318 if(context && !(context=VerifyContext(context)))
2320 alcSetError(NULL, ALC_INVALID_CONTEXT);
2321 return ALC_FALSE;
2323 /* context's reference count is already incremented */
2324 old = pthread_getspecific(LocalContext);
2325 pthread_setspecific(LocalContext, context);
2326 if(old) ALCcontext_DecRef(old);
2328 return ALC_TRUE;
2332 /* alcGetContextsDevice
2334 * Returns the Device that a particular Context is attached to
2336 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2338 ALCdevice *Device;
2340 if(!(Context=VerifyContext(Context)))
2342 alcSetError(NULL, ALC_INVALID_CONTEXT);
2343 return NULL;
2345 Device = Context->Device;
2346 ALCcontext_DecRef(Context);
2348 return Device;
2352 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2354 static const struct {
2355 const char name[32];
2356 enum DevFmtChannels channels;
2357 enum DevFmtType type;
2358 } formats[] = {
2359 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2360 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2361 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2362 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2363 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2364 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2366 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2367 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2368 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2369 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2370 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2371 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2373 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2374 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2375 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2376 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2377 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2378 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2380 size_t i;
2382 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2384 if(strcasecmp(str, formats[i].name) == 0)
2386 *chans = formats[i].channels;
2387 *type = formats[i].type;
2388 return;
2392 ERR("Unknown format: \"%s\"\n", str);
2393 *chans = DevFmtStereo;
2394 *type = DevFmtShort;
2397 /* alcOpenDevice
2399 * Open the Device specified.
2401 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2403 const ALCchar *fmt;
2404 ALCdevice *device;
2405 ALCenum err;
2407 DO_INITCONFIG();
2409 if(!PlaybackBackend.name)
2411 alcSetError(NULL, ALC_INVALID_VALUE);
2412 return NULL;
2415 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2416 deviceName = NULL;
2418 device = calloc(1, sizeof(ALCdevice));
2419 if(!device)
2421 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2422 return NULL;
2425 //Validate device
2426 device->Funcs = &PlaybackBackend.Funcs;
2427 device->ref = 1;
2428 device->Connected = ALC_TRUE;
2429 device->IsCaptureDevice = AL_FALSE;
2430 device->IsLoopbackDevice = AL_FALSE;
2431 InitializeCriticalSection(&device->Mutex);
2432 device->LastError = ALC_NO_ERROR;
2434 device->Flags = 0;
2435 device->Bs2b = NULL;
2436 device->Bs2bLevel = 0;
2437 device->szDeviceName = NULL;
2439 device->ContextList = NULL;
2441 device->MaxNoOfSources = 256;
2442 device->AuxiliaryEffectSlotMax = 4;
2443 device->NumAuxSends = MAX_SENDS;
2445 InitUIntMap(&device->BufferMap, ~0);
2446 InitUIntMap(&device->EffectMap, ~0);
2447 InitUIntMap(&device->FilterMap, ~0);
2449 //Set output format
2450 device->NumUpdates = 4;
2451 device->UpdateSize = 1024;
2453 device->Frequency = DEFAULT_OUTPUT_RATE;
2454 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2455 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2456 device->Frequency = maxu(device->Frequency, 8000);
2458 fmt = "AL_FORMAT_STEREO16";
2459 if(ConfigValueStr(NULL, "format", &fmt))
2460 device->Flags |= DEVICE_CHANNELS_REQUEST;
2461 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2463 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2464 if(device->NumUpdates < 2) device->NumUpdates = 4;
2466 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2467 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2469 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2470 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2472 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2473 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2475 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2476 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2478 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2480 device->NumStereoSources = 1;
2481 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2483 // Find a playback device to open
2484 LockLists();
2485 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2487 UnlockLists();
2488 DeleteCriticalSection(&device->Mutex);
2489 free(device);
2490 alcSetError(NULL, err);
2491 return NULL;
2493 UnlockLists();
2495 do {
2496 device->next = DeviceList;
2497 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2499 TRACE("Created device %p\n", device);
2500 return device;
2503 /* alcCloseDevice
2505 * Close the specified Device
2507 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2509 ALCdevice *volatile*list;
2510 ALCcontext *ctx;
2512 LockLists();
2513 list = &DeviceList;
2514 while(*list && *list != pDevice)
2515 list = &(*list)->next;
2517 if(!*list || (*list)->IsCaptureDevice)
2519 alcSetError(*list, ALC_INVALID_DEVICE);
2520 UnlockLists();
2521 return ALC_FALSE;
2524 *list = (*list)->next;
2525 UnlockLists();
2527 if((ctx=pDevice->ContextList) != NULL)
2529 do {
2530 WARN("Releasing context %p\n", ctx);
2531 ReleaseContext(ctx, pDevice);
2532 } while((ctx=pDevice->ContextList) != NULL);
2533 ALCdevice_StopPlayback(pDevice);
2534 pDevice->Flags &= ~DEVICE_RUNNING;
2536 ALCdevice_ClosePlayback(pDevice);
2538 ALCdevice_DecRef(pDevice);
2540 return ALC_TRUE;
2544 /* alcLoopbackOpenDeviceSOFT
2546 * Open a loopback device, for manual rendering.
2548 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2550 ALCdevice *device;
2552 DO_INITCONFIG();
2554 device = calloc(1, sizeof(ALCdevice));
2555 if(!device)
2557 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2558 return NULL;
2561 //Validate device
2562 device->Funcs = &BackendLoopback.Funcs;
2563 device->ref = 1;
2564 device->Connected = ALC_TRUE;
2565 device->IsCaptureDevice = AL_FALSE;
2566 device->IsLoopbackDevice = AL_TRUE;
2567 InitializeCriticalSection(&device->Mutex);
2568 device->LastError = ALC_NO_ERROR;
2570 device->Flags = 0;
2571 device->Bs2b = NULL;
2572 device->Bs2bLevel = 0;
2573 device->szDeviceName = NULL;
2575 device->ContextList = NULL;
2577 device->MaxNoOfSources = 256;
2578 device->AuxiliaryEffectSlotMax = 4;
2579 device->NumAuxSends = MAX_SENDS;
2581 InitUIntMap(&device->BufferMap, ~0);
2582 InitUIntMap(&device->EffectMap, ~0);
2583 InitUIntMap(&device->FilterMap, ~0);
2585 //Set output format
2586 device->NumUpdates = 0;
2587 device->UpdateSize = 0;
2589 device->Frequency = 44100;
2590 device->FmtChans = DevFmtStereo;
2591 device->FmtType = DevFmtShort;
2593 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2594 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2596 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2597 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2599 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2600 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2602 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2604 device->NumStereoSources = 1;
2605 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2607 // Open the "backend"
2608 ALCdevice_OpenPlayback(device, "Loopback");
2609 do {
2610 device->next = DeviceList;
2611 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2613 TRACE("Created device %p\n", device);
2614 return device;
2617 /* alcIsRenderFormatSupportedSOFT
2619 * Determines if the loopback device supports the given format for rendering.
2621 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2623 ALCboolean ret = ALC_FALSE;
2625 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2626 alcSetError(device, ALC_INVALID_DEVICE);
2627 else if(freq <= 0)
2628 alcSetError(device, ALC_INVALID_VALUE);
2629 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2630 alcSetError(device, ALC_INVALID_ENUM);
2631 else
2633 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2634 freq >= 8000)
2635 ret = ALC_TRUE;
2637 if(device) ALCdevice_DecRef(device);
2639 return ret;
2642 /* alcRenderSamplesSOFT
2644 * Renders some samples into a buffer, using the format last set by the
2645 * attributes given to alcCreateContext.
2647 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2649 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2650 alcSetError(device, ALC_INVALID_DEVICE);
2651 else if(samples < 0 || (samples > 0 && buffer == NULL))
2652 alcSetError(device, ALC_INVALID_VALUE);
2653 else
2654 aluMixData(device, buffer, samples);
2655 if(device) ALCdevice_DecRef(device);
2659 static void ReleaseALC(void)
2661 ALCdevice *dev;
2663 free(alcDeviceList); alcDeviceList = NULL;
2664 alcDeviceListSize = 0;
2665 free(alcAllDeviceList); alcAllDeviceList = NULL;
2666 alcAllDeviceListSize = 0;
2667 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2668 alcCaptureDeviceListSize = 0;
2670 free(alcDefaultDeviceSpecifier);
2671 alcDefaultDeviceSpecifier = NULL;
2672 free(alcDefaultAllDeviceSpecifier);
2673 alcDefaultAllDeviceSpecifier = NULL;
2674 free(alcCaptureDefaultDeviceSpecifier);
2675 alcCaptureDefaultDeviceSpecifier = NULL;
2677 if((dev=ExchangePtr((void**)&DeviceList, NULL)) != NULL)
2679 ALCuint num = 0;
2680 do {
2681 num++;
2682 } while((dev=dev->next) != NULL);
2683 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2687 ///////////////////////////////////////////////////////