Restore the old FPU mode if the effects fail to update with new device parameters
[openal-soft/android.git] / Alc / ALc.c
blob93688d5c064e95d5afb19d4263561e8652d66f64
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 RestoreFPUMode(oldMode);
1213 UnlockDevice(device);
1214 ALCdevice_StopPlayback(device);
1215 device->Flags &= ~DEVICE_RUNNING;
1216 return ALC_FALSE;
1218 slot->NeedsUpdate = AL_FALSE;
1219 ALeffectState_Update(slot->EffectState, context, slot);
1221 UnlockUIntMapRead(&context->EffectSlotMap);
1223 LockUIntMapRead(&context->SourceMap);
1224 for(pos = 0;pos < context->SourceMap.size;pos++)
1226 ALsource *source = context->SourceMap.array[pos].value;
1227 ALuint s = device->NumAuxSends;
1228 while(s < MAX_SENDS)
1230 if(source->Send[s].Slot)
1231 DecrementRef(&source->Send[s].Slot->ref);
1232 source->Send[s].Slot = NULL;
1233 source->Send[s].WetGain = 1.0f;
1234 source->Send[s].WetGainHF = 1.0f;
1235 s++;
1237 source->NeedsUpdate = AL_FALSE;
1238 ALsource_Update(source, context);
1240 UnlockUIntMapRead(&context->SourceMap);
1242 context = context->next;
1244 RestoreFPUMode(oldMode);
1245 UnlockDevice(device);
1247 return ALC_TRUE;
1250 /* FreeDevice
1252 * Frees the device structure, and destroys any objects the app failed to
1253 * delete. Called once there's no more references on the device.
1255 static ALCvoid FreeDevice(ALCdevice *device)
1257 TRACE("%p\n", device);
1259 if(device->BufferMap.size > 0)
1261 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1262 ReleaseALBuffers(device);
1264 ResetUIntMap(&device->BufferMap);
1266 if(device->EffectMap.size > 0)
1268 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1269 ReleaseALEffects(device);
1271 ResetUIntMap(&device->EffectMap);
1273 if(device->FilterMap.size > 0)
1275 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1276 ReleaseALFilters(device);
1278 ResetUIntMap(&device->FilterMap);
1280 free(device->Bs2b);
1281 device->Bs2b = NULL;
1283 free(device->szDeviceName);
1284 device->szDeviceName = NULL;
1286 DeleteCriticalSection(&device->Mutex);
1288 free(device);
1292 void ALCdevice_IncRef(ALCdevice *device)
1294 RefCount ref;
1295 ref = IncrementRef(&device->ref);
1296 TRACEREF("%p increasing refcount to %u\n", device, ref);
1299 void ALCdevice_DecRef(ALCdevice *device)
1301 RefCount ref;
1302 ref = DecrementRef(&device->ref);
1303 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1304 if(ref == 0) FreeDevice(device);
1307 /* VerifyDevice
1309 * Checks if the device handle is valid, and increments its ref count if so.
1311 static ALCdevice *VerifyDevice(ALCdevice *device)
1313 ALCdevice *tmpDevice;
1315 if(!device)
1316 return NULL;
1318 LockLists();
1319 tmpDevice = DeviceList;
1320 while(tmpDevice && tmpDevice != device)
1321 tmpDevice = tmpDevice->next;
1323 if(tmpDevice)
1324 ALCdevice_IncRef(tmpDevice);
1325 UnlockLists();
1326 return tmpDevice;
1330 ALCvoid LockDevice(ALCdevice *device)
1332 EnterCriticalSection(&device->Mutex);
1335 ALCvoid UnlockDevice(ALCdevice *device)
1337 LeaveCriticalSection(&device->Mutex);
1341 /* InitContext
1343 * Initializes context variables
1345 static ALvoid InitContext(ALCcontext *pContext)
1347 ALint i, j;
1349 //Initialise listener
1350 pContext->Listener.Gain = 1.0f;
1351 pContext->Listener.MetersPerUnit = 1.0f;
1352 pContext->Listener.Position[0] = 0.0f;
1353 pContext->Listener.Position[1] = 0.0f;
1354 pContext->Listener.Position[2] = 0.0f;
1355 pContext->Listener.Velocity[0] = 0.0f;
1356 pContext->Listener.Velocity[1] = 0.0f;
1357 pContext->Listener.Velocity[2] = 0.0f;
1358 pContext->Listener.Forward[0] = 0.0f;
1359 pContext->Listener.Forward[1] = 0.0f;
1360 pContext->Listener.Forward[2] = -1.0f;
1361 pContext->Listener.Up[0] = 0.0f;
1362 pContext->Listener.Up[1] = 1.0f;
1363 pContext->Listener.Up[2] = 0.0f;
1364 for(i = 0;i < 4;i++)
1366 for(j = 0;j < 4;j++)
1367 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1370 //Validate pContext
1371 pContext->LastError = AL_NO_ERROR;
1372 pContext->UpdateSources = AL_FALSE;
1373 pContext->ActiveSourceCount = 0;
1374 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1375 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1377 //Set globals
1378 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1379 pContext->SourceDistanceModel = AL_FALSE;
1380 pContext->DopplerFactor = 1.0f;
1381 pContext->DopplerVelocity = 1.0f;
1382 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1383 pContext->DeferUpdates = AL_FALSE;
1385 pContext->ExtensionList = alExtList;
1389 /* FreeContext
1391 * Cleans up the context, and destroys any remaining objects the app failed to
1392 * delete. Called once there's no more references on the context.
1394 static ALCvoid FreeContext(ALCcontext *context)
1396 TRACE("%p\n", context);
1398 if(context->SourceMap.size > 0)
1400 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1401 ReleaseALSources(context);
1403 ResetUIntMap(&context->SourceMap);
1405 if(context->EffectSlotMap.size > 0)
1407 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1408 ReleaseALAuxiliaryEffectSlots(context);
1410 ResetUIntMap(&context->EffectSlotMap);
1412 context->ActiveSourceCount = 0;
1413 free(context->ActiveSources);
1414 context->ActiveSources = NULL;
1415 context->MaxActiveSources = 0;
1417 context->ActiveEffectSlotCount = 0;
1418 free(context->ActiveEffectSlots);
1419 context->ActiveEffectSlots = NULL;
1420 context->MaxActiveEffectSlots = 0;
1422 ALCdevice_DecRef(context->Device);
1423 context->Device = NULL;
1425 //Invalidate context
1426 memset(context, 0, sizeof(ALCcontext));
1427 free(context);
1430 /* ReleaseContext
1432 * Removes the context reference from the given device and removes it from
1433 * being current on the running thread or globally.
1435 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1437 ALCcontext *volatile*tmp_ctx;
1439 if(pthread_getspecific(LocalContext) == context)
1441 WARN("%p released while current on thread\n", context);
1442 pthread_setspecific(LocalContext, NULL);
1443 ALCcontext_DecRef(context);
1446 if(CompExchangePtr((void**)&GlobalContext, context, NULL))
1448 WARN("%p released while current\n", context);
1449 ALCcontext_DecRef(context);
1452 tmp_ctx = &device->ContextList;
1453 while(*tmp_ctx)
1455 if(*tmp_ctx == context)
1457 *tmp_ctx = context->next;
1458 break;
1460 tmp_ctx = &(*tmp_ctx)->next;
1463 LockDevice(device);
1464 /* Lock the device to make sure the mixer is not using the contexts in the
1465 * list before we go about deleting this one. There should be a more
1466 * efficient way of doing this. */
1467 UnlockDevice(device);
1469 ALCcontext_DecRef(context);
1472 void ALCcontext_IncRef(ALCcontext *context)
1474 RefCount ref;
1475 ref = IncrementRef(&context->ref);
1476 TRACEREF("%p increasing refcount to %u\n", context, ref);
1479 void ALCcontext_DecRef(ALCcontext *context)
1481 RefCount ref;
1482 ref = DecrementRef(&context->ref);
1483 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1484 if(ref == 0) FreeContext(context);
1487 static void ReleaseThreadCtx(void *ptr)
1489 WARN("%p current for thread being destroyed\n", ptr);
1490 ALCcontext_DecRef(ptr);
1493 /* VerifyContext
1495 * Checks that the given context is valid, and increments its reference count.
1497 static ALCcontext *VerifyContext(ALCcontext *context)
1499 ALCdevice *dev;
1501 LockLists();
1502 dev = DeviceList;
1503 while(dev)
1505 ALCcontext *tmp_ctx = dev->ContextList;
1506 while(tmp_ctx)
1508 if(tmp_ctx == context)
1510 ALCcontext_IncRef(tmp_ctx);
1511 UnlockLists();
1512 return tmp_ctx;
1514 tmp_ctx = tmp_ctx->next;
1516 dev = dev->next;
1518 UnlockLists();
1520 return NULL;
1524 ALCvoid LockContext(ALCcontext *context)
1526 EnterCriticalSection(&context->Device->Mutex);
1529 ALCvoid UnlockContext(ALCcontext *context)
1531 LeaveCriticalSection(&context->Device->Mutex);
1534 /* GetContextRef
1536 * Returns the currently active context, and adds a reference without locking
1537 * it.
1539 ALCcontext *GetContextRef(void)
1541 ALCcontext *context;
1543 context = pthread_getspecific(LocalContext);
1544 if(context)
1545 ALCcontext_IncRef(context);
1546 else
1548 LockLists();
1549 context = GlobalContext;
1550 if(context)
1551 ALCcontext_IncRef(context);
1552 UnlockLists();
1555 return context;
1558 ///////////////////////////////////////////////////////
1561 ///////////////////////////////////////////////////////
1562 // ALC Functions calls
1565 // This should probably move to another c file but for now ...
1566 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1568 ALCdevice *device = NULL;
1569 ALCenum err;
1571 DO_INITCONFIG();
1573 if(!CaptureBackend.name)
1575 alcSetError(NULL, ALC_INVALID_VALUE);
1576 return NULL;
1579 if(SampleSize <= 0)
1581 alcSetError(NULL, ALC_INVALID_VALUE);
1582 return NULL;
1585 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1586 deviceName = NULL;
1588 device = calloc(1, sizeof(ALCdevice));
1589 if(!device)
1591 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1592 return NULL;
1595 //Validate device
1596 device->Funcs = &CaptureBackend.Funcs;
1597 device->ref = 1;
1598 device->Connected = ALC_TRUE;
1599 device->IsCaptureDevice = AL_TRUE;
1600 device->IsLoopbackDevice = AL_FALSE;
1601 InitializeCriticalSection(&device->Mutex);
1603 InitUIntMap(&device->BufferMap, ~0);
1604 InitUIntMap(&device->EffectMap, ~0);
1605 InitUIntMap(&device->FilterMap, ~0);
1607 device->szDeviceName = NULL;
1609 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1610 device->Frequency = frequency;
1612 device->Flags |= DEVICE_CHANNELS_REQUEST;
1613 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1615 DeleteCriticalSection(&device->Mutex);
1616 free(device);
1617 alcSetError(NULL, ALC_INVALID_ENUM);
1618 return NULL;
1621 device->UpdateSize = SampleSize;
1622 device->NumUpdates = 1;
1624 LockLists();
1625 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1627 UnlockLists();
1628 DeleteCriticalSection(&device->Mutex);
1629 free(device);
1630 alcSetError(NULL, err);
1631 return NULL;
1633 UnlockLists();
1635 do {
1636 device->next = DeviceList;
1637 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
1639 TRACE("Created device %p\n", device);
1640 return device;
1643 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1645 ALCdevice *volatile*list;
1647 LockLists();
1648 list = &DeviceList;
1649 while(*list && *list != pDevice)
1650 list = &(*list)->next;
1652 if(!*list || !(*list)->IsCaptureDevice)
1654 alcSetError(*list, ALC_INVALID_DEVICE);
1655 UnlockLists();
1656 return ALC_FALSE;
1659 *list = (*list)->next;
1660 UnlockLists();
1662 LockDevice(pDevice);
1663 ALCdevice_CloseCapture(pDevice);
1664 UnlockDevice(pDevice);
1666 ALCdevice_DecRef(pDevice);
1668 return ALC_TRUE;
1671 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1673 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1675 alcSetError(device, ALC_INVALID_DEVICE);
1676 if(device) ALCdevice_DecRef(device);
1677 return;
1679 LockDevice(device);
1680 if(device->Connected)
1681 ALCdevice_StartCapture(device);
1682 UnlockDevice(device);
1684 ALCdevice_DecRef(device);
1687 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1689 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1691 alcSetError(device, ALC_INVALID_DEVICE);
1692 if(device) ALCdevice_DecRef(device);
1693 return;
1695 LockDevice(device);
1696 if(device->Connected)
1697 ALCdevice_StopCapture(device);
1698 UnlockDevice(device);
1700 ALCdevice_DecRef(device);
1703 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1705 ALCenum err = ALC_INVALID_DEVICE;
1706 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1708 err = ALC_INVALID_VALUE;
1709 LockDevice(device);
1710 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1711 err = ALCdevice_CaptureSamples(device, buffer, samples);
1712 UnlockDevice(device);
1714 if(err != ALC_NO_ERROR)
1715 alcSetError(device, err);
1716 if(device) ALCdevice_DecRef(device);
1720 alcGetError
1722 Return last ALC generated error code
1724 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1726 ALCenum errorCode;
1728 if(VerifyDevice(device))
1730 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1731 ALCdevice_DecRef(device);
1733 else
1734 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1736 return errorCode;
1740 /* alcSuspendContext
1742 * Not functional
1744 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1746 (void)Context;
1749 /* alcProcessContext
1751 * Not functional
1753 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1755 (void)Context;
1759 /* alcGetString
1761 * Returns information about the Device, and error strings
1763 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1765 const ALCchar *value = NULL;
1767 switch(param)
1769 case ALC_NO_ERROR:
1770 value = alcNoError;
1771 break;
1773 case ALC_INVALID_ENUM:
1774 value = alcErrInvalidEnum;
1775 break;
1777 case ALC_INVALID_VALUE:
1778 value = alcErrInvalidValue;
1779 break;
1781 case ALC_INVALID_DEVICE:
1782 value = alcErrInvalidDevice;
1783 break;
1785 case ALC_INVALID_CONTEXT:
1786 value = alcErrInvalidContext;
1787 break;
1789 case ALC_OUT_OF_MEMORY:
1790 value = alcErrOutOfMemory;
1791 break;
1793 case ALC_DEVICE_SPECIFIER:
1794 if(VerifyDevice(pDevice))
1796 value = pDevice->szDeviceName;
1797 ALCdevice_DecRef(pDevice);
1799 else
1801 ProbeDeviceList();
1802 value = alcDeviceList;
1804 break;
1806 case ALC_ALL_DEVICES_SPECIFIER:
1807 ProbeAllDeviceList();
1808 value = alcAllDeviceList;
1809 break;
1811 case ALC_CAPTURE_DEVICE_SPECIFIER:
1812 if(VerifyDevice(pDevice))
1814 value = pDevice->szDeviceName;
1815 ALCdevice_DecRef(pDevice);
1817 else
1819 ProbeCaptureDeviceList();
1820 value = alcCaptureDeviceList;
1822 break;
1824 /* Default devices are always first in the list */
1825 case ALC_DEFAULT_DEVICE_SPECIFIER:
1826 if(!alcDeviceList)
1827 ProbeDeviceList();
1829 pDevice = VerifyDevice(pDevice);
1831 free(alcDefaultDeviceSpecifier);
1832 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1833 if(!alcDefaultDeviceSpecifier)
1834 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1836 value = alcDefaultDeviceSpecifier;
1837 if(pDevice) ALCdevice_DecRef(pDevice);
1838 break;
1840 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1841 if(!alcAllDeviceList)
1842 ProbeAllDeviceList();
1844 pDevice = VerifyDevice(pDevice);
1846 free(alcDefaultAllDeviceSpecifier);
1847 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1848 alcAllDeviceList : "");
1849 if(!alcDefaultAllDeviceSpecifier)
1850 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1852 value = alcDefaultAllDeviceSpecifier;
1853 if(pDevice) ALCdevice_DecRef(pDevice);
1854 break;
1856 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1857 if(!alcCaptureDeviceList)
1858 ProbeCaptureDeviceList();
1860 pDevice = VerifyDevice(pDevice);
1862 free(alcCaptureDefaultDeviceSpecifier);
1863 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1864 alcCaptureDeviceList : "");
1865 if(!alcCaptureDefaultDeviceSpecifier)
1866 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1868 value = alcCaptureDefaultDeviceSpecifier;
1869 if(pDevice) ALCdevice_DecRef(pDevice);
1870 break;
1872 case ALC_EXTENSIONS:
1873 if(!VerifyDevice(pDevice))
1874 value = alcNoDeviceExtList;
1875 else
1877 value = alcExtensionList;
1878 ALCdevice_DecRef(pDevice);
1880 break;
1882 default:
1883 pDevice = VerifyDevice(pDevice);
1884 alcSetError(pDevice, ALC_INVALID_ENUM);
1885 if(pDevice) ALCdevice_DecRef(pDevice);
1886 break;
1889 return value;
1893 /* alcGetIntegerv
1895 * Returns information about the Device and the version of Open AL
1897 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1899 device = VerifyDevice(device);
1901 if(size == 0 || data == NULL)
1903 alcSetError(device, ALC_INVALID_VALUE);
1904 if(device) ALCdevice_DecRef(device);
1905 return;
1908 if(!device)
1910 switch(param)
1912 case ALC_MAJOR_VERSION:
1913 *data = alcMajorVersion;
1914 break;
1915 case ALC_MINOR_VERSION:
1916 *data = alcMinorVersion;
1917 break;
1919 case ALC_ATTRIBUTES_SIZE:
1920 case ALC_ALL_ATTRIBUTES:
1921 case ALC_FREQUENCY:
1922 case ALC_REFRESH:
1923 case ALC_SYNC:
1924 case ALC_MONO_SOURCES:
1925 case ALC_STEREO_SOURCES:
1926 case ALC_CAPTURE_SAMPLES:
1927 case ALC_FORMAT_CHANNELS_SOFT:
1928 case ALC_FORMAT_TYPE_SOFT:
1929 alcSetError(NULL, ALC_INVALID_DEVICE);
1930 break;
1932 default:
1933 alcSetError(NULL, ALC_INVALID_ENUM);
1934 break;
1937 else if(device->IsCaptureDevice)
1939 switch(param)
1941 case ALC_CAPTURE_SAMPLES:
1942 LockDevice(device);
1943 *data = ALCdevice_AvailableSamples(device);
1944 UnlockDevice(device);
1945 break;
1947 case ALC_CONNECTED:
1948 *data = device->Connected;
1949 break;
1951 default:
1952 alcSetError(device, ALC_INVALID_ENUM);
1953 break;
1956 else /* render device */
1958 switch(param)
1960 case ALC_MAJOR_VERSION:
1961 *data = alcMajorVersion;
1962 break;
1964 case ALC_MINOR_VERSION:
1965 *data = alcMinorVersion;
1966 break;
1968 case ALC_EFX_MAJOR_VERSION:
1969 *data = alcEFXMajorVersion;
1970 break;
1972 case ALC_EFX_MINOR_VERSION:
1973 *data = alcEFXMinorVersion;
1974 break;
1976 case ALC_ATTRIBUTES_SIZE:
1977 *data = 13;
1978 break;
1980 case ALC_ALL_ATTRIBUTES:
1981 if(size < 13)
1982 alcSetError(device, ALC_INVALID_VALUE);
1983 else
1985 int i = 0;
1987 data[i++] = ALC_FREQUENCY;
1988 data[i++] = device->Frequency;
1990 if(!device->IsLoopbackDevice)
1992 data[i++] = ALC_REFRESH;
1993 data[i++] = device->Frequency / device->UpdateSize;
1995 data[i++] = ALC_SYNC;
1996 data[i++] = ALC_FALSE;
1998 else
2000 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2001 data[i++] = device->FmtChans;
2003 data[i++] = ALC_FORMAT_TYPE_SOFT;
2004 data[i++] = device->FmtType;
2007 data[i++] = ALC_MONO_SOURCES;
2008 data[i++] = device->NumMonoSources;
2010 data[i++] = ALC_STEREO_SOURCES;
2011 data[i++] = device->NumStereoSources;
2013 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2014 data[i++] = device->NumAuxSends;
2016 data[i++] = 0;
2018 break;
2020 case ALC_FREQUENCY:
2021 *data = device->Frequency;
2022 break;
2024 case ALC_REFRESH:
2025 if(device->IsLoopbackDevice)
2026 alcSetError(device, ALC_INVALID_DEVICE);
2027 else
2028 *data = device->Frequency / device->UpdateSize;
2029 break;
2031 case ALC_SYNC:
2032 if(device->IsLoopbackDevice)
2033 alcSetError(device, ALC_INVALID_DEVICE);
2034 else
2035 *data = ALC_FALSE;
2036 break;
2038 case ALC_FORMAT_CHANNELS_SOFT:
2039 if(!device->IsLoopbackDevice)
2040 alcSetError(device, ALC_INVALID_DEVICE);
2041 else
2042 *data = device->FmtChans;
2043 break;
2045 case ALC_FORMAT_TYPE_SOFT:
2046 if(!device->IsLoopbackDevice)
2047 alcSetError(device, ALC_INVALID_DEVICE);
2048 else
2049 *data = device->FmtType;
2050 break;
2052 case ALC_MONO_SOURCES:
2053 *data = device->NumMonoSources;
2054 break;
2056 case ALC_STEREO_SOURCES:
2057 *data = device->NumStereoSources;
2058 break;
2060 case ALC_MAX_AUXILIARY_SENDS:
2061 *data = device->NumAuxSends;
2062 break;
2064 case ALC_CONNECTED:
2065 *data = device->Connected;
2066 break;
2068 default:
2069 alcSetError(device, ALC_INVALID_ENUM);
2070 break;
2073 if(device)
2074 ALCdevice_DecRef(device);
2078 /* alcIsExtensionPresent
2080 * Determines if there is support for a particular extension
2082 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2084 ALCboolean bResult = ALC_FALSE;
2086 device = VerifyDevice(device);
2088 if(!extName)
2089 alcSetError(device, ALC_INVALID_VALUE);
2090 else
2092 size_t len = strlen(extName);
2093 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2094 while(ptr && *ptr)
2096 if(strncasecmp(ptr, extName, len) == 0 &&
2097 (ptr[len] == '\0' || isspace(ptr[len])))
2099 bResult = ALC_TRUE;
2100 break;
2102 if((ptr=strchr(ptr, ' ')) != NULL)
2104 do {
2105 ++ptr;
2106 } while(isspace(*ptr));
2110 if(device)
2111 ALCdevice_DecRef(device);
2112 return bResult;
2116 /* alcGetProcAddress
2118 * Retrieves the function address for a particular extension function
2120 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2122 ALCvoid *ptr = NULL;
2124 device = VerifyDevice(device);
2126 if(!funcName)
2127 alcSetError(device, ALC_INVALID_VALUE);
2128 else
2130 ALsizei i = 0;
2131 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2132 i++;
2133 ptr = alcFunctions[i].address;
2135 if(device)
2136 ALCdevice_DecRef(device);
2137 return ptr;
2141 /* alcGetEnumValue
2143 * Get the value for a particular ALC Enumerated Value
2145 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2147 ALCenum val = 0;
2149 device = VerifyDevice(device);
2151 if(!enumName)
2152 alcSetError(device, ALC_INVALID_VALUE);
2153 else
2155 ALsizei i = 0;
2156 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2157 i++;
2158 val = enumeration[i].value;
2160 if(device)
2161 ALCdevice_DecRef(device);
2162 return val;
2166 /* alcCreateContext
2168 * Create and attach a Context to a particular Device.
2170 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2172 ALCcontext *ALContext;
2174 LockLists();
2175 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2177 UnlockLists();
2178 alcSetError(device, ALC_INVALID_DEVICE);
2179 if(device) ALCdevice_DecRef(device);
2180 return NULL;
2183 /* Reset Context Last Error code */
2184 device->LastError = ALC_NO_ERROR;
2186 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2188 UnlockLists();
2189 alcSetError(device, ALC_INVALID_DEVICE);
2190 aluHandleDisconnect(device);
2191 ALCdevice_DecRef(device);
2192 return NULL;
2195 ALContext = calloc(1, sizeof(ALCcontext));
2196 if(ALContext)
2198 ALContext->ref = 1;
2200 ALContext->MaxActiveSources = 256;
2201 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2202 ALContext->MaxActiveSources);
2204 if(!ALContext || !ALContext->ActiveSources)
2206 if(!device->ContextList)
2208 ALCdevice_StopPlayback(device);
2209 device->Flags &= ~DEVICE_RUNNING;
2211 UnlockLists();
2213 free(ALContext);
2214 ALContext = NULL;
2216 alcSetError(device, ALC_OUT_OF_MEMORY);
2217 ALCdevice_DecRef(device);
2218 return NULL;
2221 ALContext->Device = device;
2222 ALCdevice_IncRef(device);
2223 InitContext(ALContext);
2225 ALContext->next = device->ContextList;
2226 device->ContextList = ALContext;
2227 UnlockLists();
2229 ALCdevice_DecRef(device);
2231 TRACE("Created context %p\n", ALContext);
2232 return ALContext;
2235 /* alcDestroyContext
2237 * Remove a Context
2239 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2241 ALCdevice *Device;
2243 LockLists();
2244 /* alcGetContextsDevice sets an error for invalid contexts */
2245 Device = alcGetContextsDevice(context);
2246 if(Device)
2248 ReleaseContext(context, Device);
2249 if(!Device->ContextList)
2251 ALCdevice_StopPlayback(Device);
2252 Device->Flags &= ~DEVICE_RUNNING;
2255 UnlockLists();
2259 /* alcGetCurrentContext
2261 * Returns the currently active Context
2263 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2265 ALCcontext *Context;
2267 Context = pthread_getspecific(LocalContext);
2268 if(!Context) Context = GlobalContext;
2270 return Context;
2273 /* alcGetThreadContext
2275 * Returns the currently active thread-local Context
2277 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2279 ALCcontext *Context;
2280 Context = pthread_getspecific(LocalContext);
2281 return Context;
2285 /* alcMakeContextCurrent
2287 * Makes the given Context the active Context
2289 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2291 /* context must be a valid Context or NULL */
2292 if(context && !(context=VerifyContext(context)))
2294 alcSetError(NULL, ALC_INVALID_CONTEXT);
2295 return ALC_FALSE;
2297 /* context's reference count is already incremented */
2298 context = ExchangePtr((void**)&GlobalContext, context);
2299 if(context) ALCcontext_DecRef(context);
2301 if((context=pthread_getspecific(LocalContext)) != NULL)
2303 pthread_setspecific(LocalContext, NULL);
2304 ALCcontext_DecRef(context);
2307 return ALC_TRUE;
2310 /* alcSetThreadContext
2312 * Makes the given Context the active Context for the current thread
2314 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2316 ALCcontext *old;
2318 /* context must be a valid Context or NULL */
2319 if(context && !(context=VerifyContext(context)))
2321 alcSetError(NULL, ALC_INVALID_CONTEXT);
2322 return ALC_FALSE;
2324 /* context's reference count is already incremented */
2325 old = pthread_getspecific(LocalContext);
2326 pthread_setspecific(LocalContext, context);
2327 if(old) ALCcontext_DecRef(old);
2329 return ALC_TRUE;
2333 /* alcGetContextsDevice
2335 * Returns the Device that a particular Context is attached to
2337 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2339 ALCdevice *Device;
2341 if(!(Context=VerifyContext(Context)))
2343 alcSetError(NULL, ALC_INVALID_CONTEXT);
2344 return NULL;
2346 Device = Context->Device;
2347 ALCcontext_DecRef(Context);
2349 return Device;
2353 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2355 static const struct {
2356 const char name[32];
2357 enum DevFmtChannels channels;
2358 enum DevFmtType type;
2359 } formats[] = {
2360 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2361 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2362 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2363 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2364 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2365 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2367 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2368 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2369 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2370 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2371 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2372 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2374 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2375 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2376 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2377 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2378 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2379 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2381 size_t i;
2383 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2385 if(strcasecmp(str, formats[i].name) == 0)
2387 *chans = formats[i].channels;
2388 *type = formats[i].type;
2389 return;
2393 ERR("Unknown format: \"%s\"\n", str);
2394 *chans = DevFmtStereo;
2395 *type = DevFmtShort;
2398 /* alcOpenDevice
2400 * Open the Device specified.
2402 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2404 const ALCchar *fmt;
2405 ALCdevice *device;
2406 ALCenum err;
2408 DO_INITCONFIG();
2410 if(!PlaybackBackend.name)
2412 alcSetError(NULL, ALC_INVALID_VALUE);
2413 return NULL;
2416 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2417 deviceName = NULL;
2419 device = calloc(1, sizeof(ALCdevice));
2420 if(!device)
2422 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2423 return NULL;
2426 //Validate device
2427 device->Funcs = &PlaybackBackend.Funcs;
2428 device->ref = 1;
2429 device->Connected = ALC_TRUE;
2430 device->IsCaptureDevice = AL_FALSE;
2431 device->IsLoopbackDevice = AL_FALSE;
2432 InitializeCriticalSection(&device->Mutex);
2433 device->LastError = ALC_NO_ERROR;
2435 device->Flags = 0;
2436 device->Bs2b = NULL;
2437 device->Bs2bLevel = 0;
2438 device->szDeviceName = NULL;
2440 device->ContextList = NULL;
2442 device->MaxNoOfSources = 256;
2443 device->AuxiliaryEffectSlotMax = 4;
2444 device->NumAuxSends = MAX_SENDS;
2446 InitUIntMap(&device->BufferMap, ~0);
2447 InitUIntMap(&device->EffectMap, ~0);
2448 InitUIntMap(&device->FilterMap, ~0);
2450 //Set output format
2451 device->NumUpdates = 4;
2452 device->UpdateSize = 1024;
2454 device->Frequency = DEFAULT_OUTPUT_RATE;
2455 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2456 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2457 device->Frequency = maxu(device->Frequency, 8000);
2459 fmt = "AL_FORMAT_STEREO16";
2460 if(ConfigValueStr(NULL, "format", &fmt))
2461 device->Flags |= DEVICE_CHANNELS_REQUEST;
2462 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2464 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2465 if(device->NumUpdates < 2) device->NumUpdates = 4;
2467 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2468 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2470 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2471 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2473 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2474 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2476 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2477 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2479 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2481 device->NumStereoSources = 1;
2482 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2484 // Find a playback device to open
2485 LockLists();
2486 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2488 UnlockLists();
2489 DeleteCriticalSection(&device->Mutex);
2490 free(device);
2491 alcSetError(NULL, err);
2492 return NULL;
2494 UnlockLists();
2496 do {
2497 device->next = DeviceList;
2498 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2500 TRACE("Created device %p\n", device);
2501 return device;
2504 /* alcCloseDevice
2506 * Close the specified Device
2508 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2510 ALCdevice *volatile*list;
2511 ALCcontext *ctx;
2513 LockLists();
2514 list = &DeviceList;
2515 while(*list && *list != pDevice)
2516 list = &(*list)->next;
2518 if(!*list || (*list)->IsCaptureDevice)
2520 alcSetError(*list, ALC_INVALID_DEVICE);
2521 UnlockLists();
2522 return ALC_FALSE;
2525 *list = (*list)->next;
2526 UnlockLists();
2528 if((ctx=pDevice->ContextList) != NULL)
2530 do {
2531 WARN("Releasing context %p\n", ctx);
2532 ReleaseContext(ctx, pDevice);
2533 } while((ctx=pDevice->ContextList) != NULL);
2534 ALCdevice_StopPlayback(pDevice);
2535 pDevice->Flags &= ~DEVICE_RUNNING;
2537 ALCdevice_ClosePlayback(pDevice);
2539 ALCdevice_DecRef(pDevice);
2541 return ALC_TRUE;
2545 /* alcLoopbackOpenDeviceSOFT
2547 * Open a loopback device, for manual rendering.
2549 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2551 ALCdevice *device;
2553 DO_INITCONFIG();
2555 device = calloc(1, sizeof(ALCdevice));
2556 if(!device)
2558 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2559 return NULL;
2562 //Validate device
2563 device->Funcs = &BackendLoopback.Funcs;
2564 device->ref = 1;
2565 device->Connected = ALC_TRUE;
2566 device->IsCaptureDevice = AL_FALSE;
2567 device->IsLoopbackDevice = AL_TRUE;
2568 InitializeCriticalSection(&device->Mutex);
2569 device->LastError = ALC_NO_ERROR;
2571 device->Flags = 0;
2572 device->Bs2b = NULL;
2573 device->Bs2bLevel = 0;
2574 device->szDeviceName = NULL;
2576 device->ContextList = NULL;
2578 device->MaxNoOfSources = 256;
2579 device->AuxiliaryEffectSlotMax = 4;
2580 device->NumAuxSends = MAX_SENDS;
2582 InitUIntMap(&device->BufferMap, ~0);
2583 InitUIntMap(&device->EffectMap, ~0);
2584 InitUIntMap(&device->FilterMap, ~0);
2586 //Set output format
2587 device->NumUpdates = 0;
2588 device->UpdateSize = 0;
2590 device->Frequency = 44100;
2591 device->FmtChans = DevFmtStereo;
2592 device->FmtType = DevFmtShort;
2594 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2595 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2597 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2598 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2600 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2601 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2603 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2605 device->NumStereoSources = 1;
2606 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2608 // Open the "backend"
2609 ALCdevice_OpenPlayback(device, "Loopback");
2610 do {
2611 device->next = DeviceList;
2612 } while(!CompExchangePtr((void**)&DeviceList, device->next, device));
2614 TRACE("Created device %p\n", device);
2615 return device;
2618 /* alcIsRenderFormatSupportedSOFT
2620 * Determines if the loopback device supports the given format for rendering.
2622 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2624 ALCboolean ret = ALC_FALSE;
2626 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2627 alcSetError(device, ALC_INVALID_DEVICE);
2628 else if(freq <= 0)
2629 alcSetError(device, ALC_INVALID_VALUE);
2630 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2631 alcSetError(device, ALC_INVALID_ENUM);
2632 else
2634 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2635 freq >= 8000)
2636 ret = ALC_TRUE;
2638 if(device) ALCdevice_DecRef(device);
2640 return ret;
2643 /* alcRenderSamplesSOFT
2645 * Renders some samples into a buffer, using the format last set by the
2646 * attributes given to alcCreateContext.
2648 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2650 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2651 alcSetError(device, ALC_INVALID_DEVICE);
2652 else if(samples < 0 || (samples > 0 && buffer == NULL))
2653 alcSetError(device, ALC_INVALID_VALUE);
2654 else
2655 aluMixData(device, buffer, samples);
2656 if(device) ALCdevice_DecRef(device);
2660 static void ReleaseALC(void)
2662 ALCdevice *dev;
2664 free(alcDeviceList); alcDeviceList = NULL;
2665 alcDeviceListSize = 0;
2666 free(alcAllDeviceList); alcAllDeviceList = NULL;
2667 alcAllDeviceListSize = 0;
2668 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2669 alcCaptureDeviceListSize = 0;
2671 free(alcDefaultDeviceSpecifier);
2672 alcDefaultDeviceSpecifier = NULL;
2673 free(alcDefaultAllDeviceSpecifier);
2674 alcDefaultAllDeviceSpecifier = NULL;
2675 free(alcCaptureDefaultDeviceSpecifier);
2676 alcCaptureDefaultDeviceSpecifier = NULL;
2678 if((dev=ExchangePtr((void**)&DeviceList, NULL)) != NULL)
2680 ALCuint num = 0;
2681 do {
2682 num++;
2683 } while((dev=dev->next) != NULL);
2684 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2688 ///////////////////////////////////////////////////////