Make sure the attributes list specifies a format for loopback devices
[openal-soft/android.git] / Alc / ALc.c
blob314c04414e1879bca25e576963e38fe285e06491
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_SOFT_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 /* Forced effect that applies to sources that don't have an effect on send 0 */
403 static ALeffect ForcedEffect;
405 ///////////////////////////////////////////////////////
408 ///////////////////////////////////////////////////////
409 // ALC Related helper functions
410 static void ReleaseALC(void);
411 static void ReleaseThreadCtx(void *ptr);
413 static void alc_initconfig(void);
414 #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig)
416 #if defined(_WIN32)
417 static void alc_init(void);
418 static void alc_deinit(void);
419 static void alc_deinit_safe(void);
421 UIntMap TlsDestructor;
423 #ifndef AL_LIBTYPE_STATIC
424 BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
426 ALsizei i;
427 (void)hModule;
429 // Perform actions based on the reason for calling.
430 switch(ul_reason_for_call)
432 case DLL_PROCESS_ATTACH:
433 InitUIntMap(&TlsDestructor, ~0);
434 alc_init();
435 break;
437 case DLL_THREAD_DETACH:
438 LockUIntMapRead(&TlsDestructor);
439 for(i = 0;i < TlsDestructor.size;i++)
441 void *ptr = pthread_getspecific(TlsDestructor.array[i].key);
442 void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value;
443 if(ptr && callback)
444 callback(ptr);
446 UnlockUIntMapRead(&TlsDestructor);
447 break;
449 case DLL_PROCESS_DETACH:
450 if(!lpReserved)
451 alc_deinit();
452 else
453 alc_deinit_safe();
454 ResetUIntMap(&TlsDestructor);
455 break;
457 return TRUE;
459 #elif defined(_MSC_VER)
460 #pragma section(".CRT$XCU",read)
461 static void alc_constructor(void);
462 static void alc_destructor(void);
463 __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor;
465 static void alc_constructor(void)
467 atexit(alc_destructor);
468 alc_init();
471 static void alc_destructor(void)
473 alc_deinit();
475 #elif defined(HAVE_GCC_DESTRUCTOR)
476 static void alc_init(void) __attribute__((constructor));
477 static void alc_deinit(void) __attribute__((destructor));
478 #else
479 #error "No static initialization available on this platform!"
480 #endif
481 #elif defined(HAVE_GCC_DESTRUCTOR)
482 static void alc_init(void) __attribute__((constructor));
483 static void alc_deinit(void) __attribute__((destructor));
484 #else
485 #error "No global initialization available on this platform!"
486 #endif
488 static void alc_init(void)
490 const char *str;
492 LogFile = stderr;
494 str = getenv("__ALSOFT_HALF_ANGLE_CONES");
495 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
496 ConeScale = 1.0f;
498 str = getenv("__ALSOFT_REVERSE_Z");
499 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
500 ZScale = -1.0f;
502 str = getenv("__ALSOFT_TRAP_ERROR");
503 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
505 TrapALError = AL_TRUE;
506 TrapALCError = AL_TRUE;
508 else
510 str = getenv("__ALSOFT_TRAP_AL_ERROR");
511 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
512 TrapALError = AL_TRUE;
514 str = getenv("__ALSOFT_TRAP_ALC_ERROR");
515 if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1))
516 TrapALCError = ALC_TRUE;
519 pthread_key_create(&LocalContext, ReleaseThreadCtx);
520 InitializeCriticalSection(&ListLock);
521 ThunkInit();
524 static void alc_deinit_safe(void)
526 ReleaseALC();
528 FreeHrtf();
529 FreeALConfig();
531 ThunkExit();
532 DeleteCriticalSection(&ListLock);
533 pthread_key_delete(LocalContext);
535 if(LogFile != stderr)
536 fclose(LogFile);
537 LogFile = NULL;
540 static void alc_deinit(void)
542 int i;
544 ReleaseALC();
546 memset(&PlaybackBackend, 0, sizeof(PlaybackBackend));
547 memset(&CaptureBackend, 0, sizeof(CaptureBackend));
549 for(i = 0;BackendList[i].Deinit;i++)
550 BackendList[i].Deinit();
551 BackendLoopback.Deinit();
553 alc_deinit_safe();
556 static void alc_initconfig(void)
558 const char *devs, *str;
559 float valf;
560 int i, n;
562 str = getenv("ALSOFT_LOGLEVEL");
563 if(str)
565 long lvl = strtol(str, NULL, 0);
566 if(lvl >= NoLog && lvl <= LogRef)
567 LogLevel = lvl;
570 str = getenv("ALSOFT_LOGFILE");
571 if(str && str[0])
573 FILE *logfile = fopen(str, "wat");
574 if(logfile) LogFile = logfile;
575 else ERR("Failed to open log file '%s'\n", str);
578 ReadALConfig();
580 InitHrtf();
582 #ifdef _WIN32
583 RTPrioLevel = 1;
584 #else
585 RTPrioLevel = 0;
586 #endif
587 ConfigValueInt(NULL, "rt-prio", &RTPrioLevel);
589 if(ConfigValueStr(NULL, "resampler", &str))
591 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
592 DefaultResampler = POINT_RESAMPLER;
593 else if(strcasecmp(str, "linear") == 0)
594 DefaultResampler = LINEAR_RESAMPLER;
595 else if(strcasecmp(str, "cubic") == 0)
596 DefaultResampler = CUBIC_RESAMPLER;
597 else
599 char *end;
601 n = strtol(str, &end, 0);
602 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
603 DefaultResampler = n;
604 else
605 WARN("Invalid resampler: %s\n", str);
609 if(!TrapALCError)
610 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
612 if(!TrapALError)
613 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
615 if(ConfigValueFloat("reverb", "boost", &valf))
616 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
618 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
620 if(ConfigValueStr(NULL, "drivers", &devs))
622 int n;
623 size_t len;
624 const char *next = devs;
625 int endlist, delitem;
627 i = 0;
628 do {
629 devs = next;
630 next = strchr(devs, ',');
632 delitem = (devs[0] == '-');
633 if(devs[0] == '-') devs++;
635 if(!devs[0] || devs[0] == ',')
637 endlist = 0;
638 continue;
640 endlist = 1;
642 len = (next ? ((size_t)(next-devs)) : strlen(devs));
643 for(n = i;BackendList[n].Init;n++)
645 if(len == strlen(BackendList[n].name) &&
646 strncmp(BackendList[n].name, devs, len) == 0)
648 if(delitem)
650 do {
651 BackendList[n] = BackendList[n+1];
652 ++n;
653 } while(BackendList[n].Init);
655 else
657 struct BackendInfo Bkp = BackendList[n];
658 while(n > i)
660 BackendList[n] = BackendList[n-1];
661 --n;
663 BackendList[n] = Bkp;
665 i++;
667 break;
670 } while(next++);
672 if(endlist)
674 BackendList[i].name = NULL;
675 BackendList[i].Init = NULL;
676 BackendList[i].Deinit = NULL;
677 BackendList[i].Probe = NULL;
681 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
683 if(!BackendList[i].Init(&BackendList[i].Funcs))
685 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
686 continue;
689 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
690 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
692 PlaybackBackend = BackendList[i];
693 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
695 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
697 CaptureBackend = BackendList[i];
698 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
701 BackendLoopback.Init(&BackendLoopback.Funcs);
703 if(ConfigValueStr(NULL, "excludefx", &str))
705 size_t len;
706 const char *next = str;
708 do {
709 str = next;
710 next = strchr(str, ',');
712 if(!str[0] || next == str)
713 continue;
715 len = (next ? ((size_t)(next-str)) : strlen(str));
716 for(n = 0;EffectList[n].name;n++)
718 if(len == strlen(EffectList[n].name) &&
719 strncmp(EffectList[n].name, str, len) == 0)
720 DisabledEffects[EffectList[n].type] = AL_TRUE;
722 } while(next++);
725 InitEffect(&ForcedEffect);
726 str = getenv("__ALSOFT_DEFAULT_REVERB");
727 if(str && str[0])
728 GetReverbEffect(str, &ForcedEffect);
729 else if(ConfigValueStr(NULL, "default-reverb", &str))
730 GetReverbEffect(str, &ForcedEffect);
734 static void LockLists(void)
736 EnterCriticalSection(&ListLock);
739 static void UnlockLists(void)
741 LeaveCriticalSection(&ListLock);
745 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
747 DO_INITCONFIG();
749 LockLists();
750 free(*list);
751 *list = NULL;
752 *listsize = 0;
754 if(type == CAPTURE_DEVICE_PROBE)
755 CaptureBackend.Probe(type);
756 else
757 PlaybackBackend.Probe(type);
758 UnlockLists();
761 static void ProbeDeviceList(void)
762 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
763 static void ProbeAllDeviceList(void)
764 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
765 static void ProbeCaptureDeviceList(void)
766 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
769 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
771 size_t len = strlen(name);
772 void *temp;
774 if(len == 0)
775 return;
777 temp = realloc(*List, (*ListSize) + len + 2);
778 if(!temp)
780 ERR("Realloc failed to add %s!\n", name);
781 return;
783 *List = temp;
785 memcpy((*List)+(*ListSize), name, len+1);
786 *ListSize += len+1;
787 (*List)[*ListSize] = 0;
790 #define DECL_APPEND_LIST_FUNC(type) \
791 void Append##type##List(const ALCchar *name) \
792 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
794 DECL_APPEND_LIST_FUNC(Device)
795 DECL_APPEND_LIST_FUNC(AllDevice)
796 DECL_APPEND_LIST_FUNC(CaptureDevice)
798 #undef DECL_APPEND_LIST_FUNC
801 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
802 void SetDefaultChannelOrder(ALCdevice *device)
804 switch(device->FmtChans)
806 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
807 device->DevChannels[1] = FRONT_RIGHT;
808 device->DevChannels[2] = BACK_LEFT;
809 device->DevChannels[3] = BACK_RIGHT;
810 device->DevChannels[4] = FRONT_CENTER;
811 device->DevChannels[5] = LFE;
812 return;
814 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
815 device->DevChannels[1] = FRONT_RIGHT;
816 device->DevChannels[2] = BACK_LEFT;
817 device->DevChannels[3] = BACK_RIGHT;
818 device->DevChannels[4] = FRONT_CENTER;
819 device->DevChannels[5] = LFE;
820 device->DevChannels[6] = SIDE_LEFT;
821 device->DevChannels[7] = SIDE_RIGHT;
822 return;
824 /* Same as WFX order */
825 case DevFmtMono:
826 case DevFmtStereo:
827 case DevFmtQuad:
828 case DevFmtX51Side:
829 case DevFmtX61:
830 break;
832 SetDefaultWFXChannelOrder(device);
834 /* Sets the default order used by WaveFormatEx */
835 void SetDefaultWFXChannelOrder(ALCdevice *device)
837 switch(device->FmtChans)
839 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
841 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
842 device->DevChannels[1] = FRONT_RIGHT; break;
844 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
845 device->DevChannels[1] = FRONT_RIGHT;
846 device->DevChannels[2] = BACK_LEFT;
847 device->DevChannels[3] = BACK_RIGHT; break;
849 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
850 device->DevChannels[1] = FRONT_RIGHT;
851 device->DevChannels[2] = FRONT_CENTER;
852 device->DevChannels[3] = LFE;
853 device->DevChannels[4] = BACK_LEFT;
854 device->DevChannels[5] = BACK_RIGHT; break;
856 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
857 device->DevChannels[1] = FRONT_RIGHT;
858 device->DevChannels[2] = FRONT_CENTER;
859 device->DevChannels[3] = LFE;
860 device->DevChannels[4] = SIDE_LEFT;
861 device->DevChannels[5] = SIDE_RIGHT; break;
863 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
864 device->DevChannels[1] = FRONT_RIGHT;
865 device->DevChannels[2] = FRONT_CENTER;
866 device->DevChannels[3] = LFE;
867 device->DevChannels[4] = BACK_CENTER;
868 device->DevChannels[5] = SIDE_LEFT;
869 device->DevChannels[6] = SIDE_RIGHT; break;
871 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
872 device->DevChannels[1] = FRONT_RIGHT;
873 device->DevChannels[2] = FRONT_CENTER;
874 device->DevChannels[3] = LFE;
875 device->DevChannels[4] = BACK_LEFT;
876 device->DevChannels[5] = BACK_RIGHT;
877 device->DevChannels[6] = SIDE_LEFT;
878 device->DevChannels[7] = SIDE_RIGHT; break;
883 const ALCchar *DevFmtTypeString(enum DevFmtType type)
885 switch(type)
887 case DevFmtByte: return "Signed Byte";
888 case DevFmtUByte: return "Unsigned Byte";
889 case DevFmtShort: return "Signed Short";
890 case DevFmtUShort: return "Unsigned Short";
891 case DevFmtFloat: return "Float";
893 return "(unknown type)";
895 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
897 switch(chans)
899 case DevFmtMono: return "Mono";
900 case DevFmtStereo: return "Stereo";
901 case DevFmtQuad: return "Quadraphonic";
902 case DevFmtX51: return "5.1 Surround";
903 case DevFmtX51Side: return "5.1 Side";
904 case DevFmtX61: return "6.1 Surround";
905 case DevFmtX71: return "7.1 Surround";
907 return "(unknown channels)";
910 ALuint BytesFromDevFmt(enum DevFmtType type)
912 switch(type)
914 case DevFmtByte: return sizeof(ALbyte);
915 case DevFmtUByte: return sizeof(ALubyte);
916 case DevFmtShort: return sizeof(ALshort);
917 case DevFmtUShort: return sizeof(ALushort);
918 case DevFmtFloat: return sizeof(ALfloat);
920 return 0;
922 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
924 switch(chans)
926 case DevFmtMono: return 1;
927 case DevFmtStereo: return 2;
928 case DevFmtQuad: return 4;
929 case DevFmtX51: return 6;
930 case DevFmtX51Side: return 6;
931 case DevFmtX61: return 7;
932 case DevFmtX71: return 8;
934 return 0;
936 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
937 enum DevFmtType *type)
939 static const struct {
940 ALenum format;
941 enum DevFmtChannels channels;
942 enum DevFmtType type;
943 } list[] = {
944 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
945 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
946 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
948 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
949 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
950 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
952 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
953 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
954 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
956 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
957 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
958 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
960 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
961 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
962 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
964 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
965 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
966 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
968 ALuint i;
970 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
972 if(list[i].format == format)
974 *chans = list[i].channels;
975 *type = list[i].type;
976 return AL_TRUE;
980 return AL_FALSE;
983 static ALCboolean IsValidALCType(ALCenum type)
985 switch(type)
987 case ALC_BYTE_SOFT:
988 case ALC_UNSIGNED_BYTE_SOFT:
989 case ALC_SHORT_SOFT:
990 case ALC_UNSIGNED_SHORT_SOFT:
991 case ALC_INT_SOFT:
992 case ALC_UNSIGNED_INT_SOFT:
993 case ALC_FLOAT_SOFT:
994 return ALC_TRUE;
996 return ALC_FALSE;
999 static ALCboolean IsValidALCChannels(ALCenum channels)
1001 switch(channels)
1003 case ALC_MONO_SOFT:
1004 case ALC_STEREO_SOFT:
1005 case ALC_QUAD_SOFT:
1006 case ALC_5POINT1_SOFT:
1007 case ALC_6POINT1_SOFT:
1008 case ALC_7POINT1_SOFT:
1009 return ALC_TRUE;
1011 return ALC_FALSE;
1015 /* alcSetError
1017 * Stores the latest ALC Error
1019 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1021 if(TrapALCError)
1023 #ifdef _WIN32
1024 /* DebugBreak() will cause an exception if there is no debugger */
1025 if(IsDebuggerPresent())
1026 DebugBreak();
1027 #elif defined(SIGTRAP)
1028 raise(SIGTRAP);
1029 #endif
1032 if(device)
1033 device->LastError = errorCode;
1034 else
1035 g_eLastNullDeviceError = errorCode;
1039 /* UpdateDeviceParams
1041 * Updates device parameters according to the attribute list (caller is
1042 * responsible for holding the list lock).
1044 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1046 ALCcontext *context;
1047 enum DevFmtChannels oldChans;
1048 enum DevFmtType oldType;
1049 ALCuint oldFreq;
1050 int oldMode;
1051 ALuint i;
1053 // Check for attributes
1054 if(attrList && attrList[0])
1056 static const ALCint GotFreq = 1<<0;
1057 static const ALCint GotChans = 1<<1;
1058 static const ALCint GotType = 1<<2;
1059 static const ALCint GotAll = GotFreq|GotChans|GotType;
1060 ALCuint freq, numMono, numStereo, numSends;
1061 enum DevFmtChannels schans;
1062 enum DevFmtType stype;
1063 ALCuint attrIdx = 0;
1064 ALCint gotFmt = 0;
1066 // If a context is already running on the device, stop playback so the
1067 // device attributes can be updated
1068 if((device->Flags&DEVICE_RUNNING))
1069 ALCdevice_StopPlayback(device);
1070 device->Flags &= ~DEVICE_RUNNING;
1072 freq = device->Frequency;
1073 schans = device->FmtChans;
1074 stype = device->FmtType;
1075 numMono = device->NumMonoSources;
1076 numStereo = device->NumStereoSources;
1077 numSends = device->NumAuxSends;
1079 while(attrList[attrIdx])
1081 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1082 device->IsLoopbackDevice)
1084 ALCint val = attrList[attrIdx + 1];
1085 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1087 alcSetError(device, ALC_INVALID_VALUE);
1088 return ALC_FALSE;
1090 schans = val;
1091 gotFmt |= GotChans;
1094 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1095 device->IsLoopbackDevice)
1097 ALCint val = attrList[attrIdx + 1];
1098 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1100 alcSetError(device, ALC_INVALID_VALUE);
1101 return ALC_FALSE;
1103 stype = val;
1104 gotFmt |= GotType;
1107 if(attrList[attrIdx] == ALC_FREQUENCY)
1109 if(device->IsLoopbackDevice)
1111 freq = attrList[attrIdx + 1];
1112 if(freq < 8000)
1114 alcSetError(device, ALC_INVALID_VALUE);
1115 return ALC_FALSE;
1117 gotFmt |= GotFreq;
1119 else
1121 freq = attrList[attrIdx + 1];
1122 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1126 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1128 numStereo = attrList[attrIdx + 1];
1129 if(numStereo > device->MaxNoOfSources)
1130 numStereo = device->MaxNoOfSources;
1132 numMono = device->MaxNoOfSources - numStereo;
1135 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1136 numSends = attrList[attrIdx + 1];
1138 attrIdx += 2;
1141 if(device->IsLoopbackDevice)
1143 if(gotFmt != GotAll)
1145 WARN("Missing format for loopback device\n");
1146 alcSetError(device, ALC_INVALID_VALUE);
1147 return ALC_FALSE;
1150 else
1152 ConfigValueUInt(NULL, "frequency", &freq);
1153 freq = maxu(freq, 8000);
1155 ConfigValueUInt(NULL, "sends", &numSends);
1156 numSends = minu(MAX_SENDS, numSends);
1158 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1159 device->Frequency;
1161 device->Frequency = freq;
1162 device->FmtChans = schans;
1163 device->FmtType = stype;
1164 device->NumMonoSources = numMono;
1165 device->NumStereoSources = numStereo;
1166 device->NumAuxSends = numSends;
1169 if((device->Flags&DEVICE_RUNNING))
1170 return ALC_TRUE;
1172 LockDevice(device);
1174 oldFreq = device->Frequency;
1175 oldChans = device->FmtChans;
1176 oldType = device->FmtType;
1178 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1179 DevFmtChannelsString(device->FmtChans),
1180 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1181 DevFmtTypeString(device->FmtType), device->Frequency,
1182 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1183 device->UpdateSize, device->NumUpdates);
1184 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1186 UnlockDevice(device);
1187 return ALC_FALSE;
1189 device->Flags |= DEVICE_RUNNING;
1191 if(device->FmtChans != oldChans)
1193 if((device->Flags&DEVICE_CHANNELS_REQUEST))
1194 ERR("Failed to set %s, got %s instead\n",
1195 DevFmtChannelsString(oldChans),
1196 DevFmtChannelsString(device->FmtChans));
1197 device->Flags &= ~DEVICE_CHANNELS_REQUEST;
1199 if(device->Frequency != oldFreq)
1201 if((device->Flags&DEVICE_FREQUENCY_REQUEST))
1202 ERR("Failed to set %uhz, got %uhz instead\n",
1203 oldFreq, device->Frequency);
1204 device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
1207 TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n",
1208 DevFmtChannelsString(device->FmtChans),
1209 DevFmtTypeString(device->FmtType), device->Frequency,
1210 device->UpdateSize, device->NumUpdates);
1212 aluInitPanning(device);
1214 for(i = 0;i < MAXCHANNELS;i++)
1216 device->ClickRemoval[i] = 0.0f;
1217 device->PendingClicks[i] = 0.0f;
1220 device->Hrtf = NULL;
1221 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1222 device->Hrtf = GetHrtf(device);
1223 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1225 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1227 if(!device->Bs2b)
1229 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1230 bs2b_clear(device->Bs2b);
1232 bs2b_set_srate(device->Bs2b, device->Frequency);
1233 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1234 TRACE("BS2B level %d\n", device->Bs2bLevel);
1236 else
1238 free(device->Bs2b);
1239 device->Bs2b = NULL;
1240 TRACE("BS2B disabled\n");
1243 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1244 switch(device->FmtChans)
1246 case DevFmtMono:
1247 case DevFmtStereo:
1248 break;
1249 case DevFmtQuad:
1250 case DevFmtX51:
1251 case DevFmtX51Side:
1252 case DevFmtX61:
1253 case DevFmtX71:
1254 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1255 device->Flags |= DEVICE_DUPLICATE_STEREO;
1256 break;
1258 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1260 oldMode = SetMixerFPUMode();
1261 context = device->ContextList;
1262 while(context)
1264 ALsizei pos;
1266 context->UpdateSources = AL_FALSE;
1267 LockUIntMapRead(&context->EffectSlotMap);
1268 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1270 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1272 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1274 UnlockUIntMapRead(&context->EffectSlotMap);
1275 RestoreFPUMode(oldMode);
1276 UnlockDevice(device);
1277 ALCdevice_StopPlayback(device);
1278 device->Flags &= ~DEVICE_RUNNING;
1279 return ALC_FALSE;
1281 slot->NeedsUpdate = AL_FALSE;
1282 ALeffectState_Update(slot->EffectState, context, slot);
1284 UnlockUIntMapRead(&context->EffectSlotMap);
1286 LockUIntMapRead(&context->SourceMap);
1287 for(pos = 0;pos < context->SourceMap.size;pos++)
1289 ALsource *source = context->SourceMap.array[pos].value;
1290 ALuint s = device->NumAuxSends;
1291 while(s < MAX_SENDS)
1293 if(source->Send[s].Slot)
1294 DecrementRef(&source->Send[s].Slot->ref);
1295 source->Send[s].Slot = NULL;
1296 source->Send[s].WetGain = 1.0f;
1297 source->Send[s].WetGainHF = 1.0f;
1298 s++;
1300 source->NeedsUpdate = AL_FALSE;
1301 ALsource_Update(source, context);
1303 UnlockUIntMapRead(&context->SourceMap);
1305 context = context->next;
1307 RestoreFPUMode(oldMode);
1308 UnlockDevice(device);
1310 return ALC_TRUE;
1313 /* FreeDevice
1315 * Frees the device structure, and destroys any objects the app failed to
1316 * delete. Called once there's no more references on the device.
1318 static ALCvoid FreeDevice(ALCdevice *device)
1320 TRACE("%p\n", device);
1322 if(device->DefaultSlot)
1324 ALeffectState_Destroy(device->DefaultSlot->EffectState);
1325 device->DefaultSlot->EffectState = NULL;
1328 if(device->BufferMap.size > 0)
1330 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1331 ReleaseALBuffers(device);
1333 ResetUIntMap(&device->BufferMap);
1335 if(device->EffectMap.size > 0)
1337 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1338 ReleaseALEffects(device);
1340 ResetUIntMap(&device->EffectMap);
1342 if(device->FilterMap.size > 0)
1344 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1345 ReleaseALFilters(device);
1347 ResetUIntMap(&device->FilterMap);
1349 free(device->Bs2b);
1350 device->Bs2b = NULL;
1352 free(device->szDeviceName);
1353 device->szDeviceName = NULL;
1355 DeleteCriticalSection(&device->Mutex);
1357 free(device);
1361 void ALCdevice_IncRef(ALCdevice *device)
1363 RefCount ref;
1364 ref = IncrementRef(&device->ref);
1365 TRACEREF("%p increasing refcount to %u\n", device, ref);
1368 void ALCdevice_DecRef(ALCdevice *device)
1370 RefCount ref;
1371 ref = DecrementRef(&device->ref);
1372 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1373 if(ref == 0) FreeDevice(device);
1376 /* VerifyDevice
1378 * Checks if the device handle is valid, and increments its ref count if so.
1380 static ALCdevice *VerifyDevice(ALCdevice *device)
1382 ALCdevice *tmpDevice;
1384 if(!device)
1385 return NULL;
1387 LockLists();
1388 tmpDevice = DeviceList;
1389 while(tmpDevice && tmpDevice != device)
1390 tmpDevice = tmpDevice->next;
1392 if(tmpDevice)
1393 ALCdevice_IncRef(tmpDevice);
1394 UnlockLists();
1395 return tmpDevice;
1399 /* InitContext
1401 * Initializes context variables
1403 static ALvoid InitContext(ALCcontext *pContext)
1405 ALint i, j;
1407 //Initialise listener
1408 pContext->Listener.Gain = 1.0f;
1409 pContext->Listener.MetersPerUnit = 1.0f;
1410 pContext->Listener.Position[0] = 0.0f;
1411 pContext->Listener.Position[1] = 0.0f;
1412 pContext->Listener.Position[2] = 0.0f;
1413 pContext->Listener.Velocity[0] = 0.0f;
1414 pContext->Listener.Velocity[1] = 0.0f;
1415 pContext->Listener.Velocity[2] = 0.0f;
1416 pContext->Listener.Forward[0] = 0.0f;
1417 pContext->Listener.Forward[1] = 0.0f;
1418 pContext->Listener.Forward[2] = -1.0f;
1419 pContext->Listener.Up[0] = 0.0f;
1420 pContext->Listener.Up[1] = 1.0f;
1421 pContext->Listener.Up[2] = 0.0f;
1422 for(i = 0;i < 4;i++)
1424 for(j = 0;j < 4;j++)
1425 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1428 //Validate pContext
1429 pContext->LastError = AL_NO_ERROR;
1430 pContext->UpdateSources = AL_FALSE;
1431 pContext->ActiveSourceCount = 0;
1432 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1433 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1435 //Set globals
1436 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1437 pContext->SourceDistanceModel = AL_FALSE;
1438 pContext->DopplerFactor = 1.0f;
1439 pContext->DopplerVelocity = 1.0f;
1440 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1441 pContext->DeferUpdates = AL_FALSE;
1443 pContext->ExtensionList = alExtList;
1447 /* FreeContext
1449 * Cleans up the context, and destroys any remaining objects the app failed to
1450 * delete. Called once there's no more references on the context.
1452 static ALCvoid FreeContext(ALCcontext *context)
1454 TRACE("%p\n", context);
1456 if(context->SourceMap.size > 0)
1458 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1459 ReleaseALSources(context);
1461 ResetUIntMap(&context->SourceMap);
1463 if(context->EffectSlotMap.size > 0)
1465 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1466 ReleaseALAuxiliaryEffectSlots(context);
1468 ResetUIntMap(&context->EffectSlotMap);
1470 context->ActiveSourceCount = 0;
1471 free(context->ActiveSources);
1472 context->ActiveSources = NULL;
1473 context->MaxActiveSources = 0;
1475 context->ActiveEffectSlotCount = 0;
1476 free(context->ActiveEffectSlots);
1477 context->ActiveEffectSlots = NULL;
1478 context->MaxActiveEffectSlots = 0;
1480 ALCdevice_DecRef(context->Device);
1481 context->Device = NULL;
1483 //Invalidate context
1484 memset(context, 0, sizeof(ALCcontext));
1485 free(context);
1488 /* ReleaseContext
1490 * Removes the context reference from the given device and removes it from
1491 * being current on the running thread or globally.
1493 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1495 ALCcontext *volatile*tmp_ctx;
1497 if(pthread_getspecific(LocalContext) == context)
1499 WARN("%p released while current on thread\n", context);
1500 pthread_setspecific(LocalContext, NULL);
1501 ALCcontext_DecRef(context);
1504 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1505 ALCcontext_DecRef(context);
1507 LockDevice(device);
1508 tmp_ctx = &device->ContextList;
1509 while(*tmp_ctx)
1511 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1512 break;
1513 tmp_ctx = &(*tmp_ctx)->next;
1515 UnlockDevice(device);
1517 ALCcontext_DecRef(context);
1520 void ALCcontext_IncRef(ALCcontext *context)
1522 RefCount ref;
1523 ref = IncrementRef(&context->ref);
1524 TRACEREF("%p increasing refcount to %u\n", context, ref);
1527 void ALCcontext_DecRef(ALCcontext *context)
1529 RefCount ref;
1530 ref = DecrementRef(&context->ref);
1531 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1532 if(ref == 0) FreeContext(context);
1535 static void ReleaseThreadCtx(void *ptr)
1537 WARN("%p current for thread being destroyed\n", ptr);
1538 ALCcontext_DecRef(ptr);
1541 /* VerifyContext
1543 * Checks that the given context is valid, and increments its reference count.
1545 static ALCcontext *VerifyContext(ALCcontext *context)
1547 ALCdevice *dev;
1549 LockLists();
1550 dev = DeviceList;
1551 while(dev)
1553 ALCcontext *tmp_ctx = dev->ContextList;
1554 while(tmp_ctx)
1556 if(tmp_ctx == context)
1558 ALCcontext_IncRef(tmp_ctx);
1559 UnlockLists();
1560 return tmp_ctx;
1562 tmp_ctx = tmp_ctx->next;
1564 dev = dev->next;
1566 UnlockLists();
1568 return NULL;
1572 /* GetContextRef
1574 * Returns the currently active context, and adds a reference without locking
1575 * it.
1577 ALCcontext *GetContextRef(void)
1579 ALCcontext *context;
1581 context = pthread_getspecific(LocalContext);
1582 if(context)
1583 ALCcontext_IncRef(context);
1584 else
1586 LockLists();
1587 context = GlobalContext;
1588 if(context)
1589 ALCcontext_IncRef(context);
1590 UnlockLists();
1593 return context;
1596 ///////////////////////////////////////////////////////
1599 ///////////////////////////////////////////////////////
1600 // ALC Functions calls
1603 // This should probably move to another c file but for now ...
1604 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1606 ALCdevice *device = NULL;
1607 ALCenum err;
1609 DO_INITCONFIG();
1611 if(!CaptureBackend.name)
1613 alcSetError(NULL, ALC_INVALID_VALUE);
1614 return NULL;
1617 if(SampleSize <= 0)
1619 alcSetError(NULL, ALC_INVALID_VALUE);
1620 return NULL;
1623 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1624 deviceName = NULL;
1626 device = calloc(1, sizeof(ALCdevice));
1627 if(!device)
1629 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1630 return NULL;
1633 //Validate device
1634 device->Funcs = &CaptureBackend.Funcs;
1635 device->ref = 1;
1636 device->Connected = ALC_TRUE;
1637 device->IsCaptureDevice = AL_TRUE;
1638 device->IsLoopbackDevice = AL_FALSE;
1639 InitializeCriticalSection(&device->Mutex);
1641 InitUIntMap(&device->BufferMap, ~0);
1642 InitUIntMap(&device->EffectMap, ~0);
1643 InitUIntMap(&device->FilterMap, ~0);
1645 device->szDeviceName = NULL;
1647 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1648 device->Frequency = frequency;
1650 device->Flags |= DEVICE_CHANNELS_REQUEST;
1651 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1653 DeleteCriticalSection(&device->Mutex);
1654 free(device);
1655 alcSetError(NULL, ALC_INVALID_ENUM);
1656 return NULL;
1659 device->UpdateSize = SampleSize;
1660 device->NumUpdates = 1;
1662 LockLists();
1663 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1665 UnlockLists();
1666 DeleteCriticalSection(&device->Mutex);
1667 free(device);
1668 alcSetError(NULL, err);
1669 return NULL;
1671 UnlockLists();
1673 do {
1674 device->next = DeviceList;
1675 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1677 TRACE("Created device %p\n", device);
1678 return device;
1681 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1683 ALCdevice *volatile*list;
1685 LockLists();
1686 list = &DeviceList;
1687 while(*list && *list != pDevice)
1688 list = &(*list)->next;
1690 if(!*list || !(*list)->IsCaptureDevice)
1692 alcSetError(*list, ALC_INVALID_DEVICE);
1693 UnlockLists();
1694 return ALC_FALSE;
1697 *list = (*list)->next;
1698 UnlockLists();
1700 LockDevice(pDevice);
1701 ALCdevice_CloseCapture(pDevice);
1702 UnlockDevice(pDevice);
1704 ALCdevice_DecRef(pDevice);
1706 return ALC_TRUE;
1709 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1711 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1713 alcSetError(device, ALC_INVALID_DEVICE);
1714 if(device) ALCdevice_DecRef(device);
1715 return;
1717 LockDevice(device);
1718 if(device->Connected)
1719 ALCdevice_StartCapture(device);
1720 UnlockDevice(device);
1722 ALCdevice_DecRef(device);
1725 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1727 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1729 alcSetError(device, ALC_INVALID_DEVICE);
1730 if(device) ALCdevice_DecRef(device);
1731 return;
1733 LockDevice(device);
1734 if(device->Connected)
1735 ALCdevice_StopCapture(device);
1736 UnlockDevice(device);
1738 ALCdevice_DecRef(device);
1741 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1743 ALCenum err = ALC_INVALID_DEVICE;
1744 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1746 err = ALC_INVALID_VALUE;
1747 LockDevice(device);
1748 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1749 err = ALCdevice_CaptureSamples(device, buffer, samples);
1750 UnlockDevice(device);
1752 if(err != ALC_NO_ERROR)
1753 alcSetError(device, err);
1754 if(device) ALCdevice_DecRef(device);
1758 alcGetError
1760 Return last ALC generated error code
1762 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1764 ALCenum errorCode;
1766 if(VerifyDevice(device))
1768 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1769 ALCdevice_DecRef(device);
1771 else
1772 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1774 return errorCode;
1778 /* alcSuspendContext
1780 * Not functional
1782 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1784 (void)Context;
1787 /* alcProcessContext
1789 * Not functional
1791 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1793 (void)Context;
1797 /* alcGetString
1799 * Returns information about the Device, and error strings
1801 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1803 const ALCchar *value = NULL;
1805 switch(param)
1807 case ALC_NO_ERROR:
1808 value = alcNoError;
1809 break;
1811 case ALC_INVALID_ENUM:
1812 value = alcErrInvalidEnum;
1813 break;
1815 case ALC_INVALID_VALUE:
1816 value = alcErrInvalidValue;
1817 break;
1819 case ALC_INVALID_DEVICE:
1820 value = alcErrInvalidDevice;
1821 break;
1823 case ALC_INVALID_CONTEXT:
1824 value = alcErrInvalidContext;
1825 break;
1827 case ALC_OUT_OF_MEMORY:
1828 value = alcErrOutOfMemory;
1829 break;
1831 case ALC_DEVICE_SPECIFIER:
1832 if(VerifyDevice(pDevice))
1834 value = pDevice->szDeviceName;
1835 ALCdevice_DecRef(pDevice);
1837 else
1839 ProbeDeviceList();
1840 value = alcDeviceList;
1842 break;
1844 case ALC_ALL_DEVICES_SPECIFIER:
1845 ProbeAllDeviceList();
1846 value = alcAllDeviceList;
1847 break;
1849 case ALC_CAPTURE_DEVICE_SPECIFIER:
1850 if(VerifyDevice(pDevice))
1852 value = pDevice->szDeviceName;
1853 ALCdevice_DecRef(pDevice);
1855 else
1857 ProbeCaptureDeviceList();
1858 value = alcCaptureDeviceList;
1860 break;
1862 /* Default devices are always first in the list */
1863 case ALC_DEFAULT_DEVICE_SPECIFIER:
1864 if(!alcDeviceList)
1865 ProbeDeviceList();
1867 pDevice = VerifyDevice(pDevice);
1869 free(alcDefaultDeviceSpecifier);
1870 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1871 if(!alcDefaultDeviceSpecifier)
1872 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1874 value = alcDefaultDeviceSpecifier;
1875 if(pDevice) ALCdevice_DecRef(pDevice);
1876 break;
1878 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1879 if(!alcAllDeviceList)
1880 ProbeAllDeviceList();
1882 pDevice = VerifyDevice(pDevice);
1884 free(alcDefaultAllDeviceSpecifier);
1885 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1886 alcAllDeviceList : "");
1887 if(!alcDefaultAllDeviceSpecifier)
1888 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1890 value = alcDefaultAllDeviceSpecifier;
1891 if(pDevice) ALCdevice_DecRef(pDevice);
1892 break;
1894 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1895 if(!alcCaptureDeviceList)
1896 ProbeCaptureDeviceList();
1898 pDevice = VerifyDevice(pDevice);
1900 free(alcCaptureDefaultDeviceSpecifier);
1901 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1902 alcCaptureDeviceList : "");
1903 if(!alcCaptureDefaultDeviceSpecifier)
1904 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1906 value = alcCaptureDefaultDeviceSpecifier;
1907 if(pDevice) ALCdevice_DecRef(pDevice);
1908 break;
1910 case ALC_EXTENSIONS:
1911 if(!VerifyDevice(pDevice))
1912 value = alcNoDeviceExtList;
1913 else
1915 value = alcExtensionList;
1916 ALCdevice_DecRef(pDevice);
1918 break;
1920 default:
1921 pDevice = VerifyDevice(pDevice);
1922 alcSetError(pDevice, ALC_INVALID_ENUM);
1923 if(pDevice) ALCdevice_DecRef(pDevice);
1924 break;
1927 return value;
1931 /* alcGetIntegerv
1933 * Returns information about the Device and the version of Open AL
1935 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1937 device = VerifyDevice(device);
1939 if(size == 0 || data == NULL)
1941 alcSetError(device, ALC_INVALID_VALUE);
1942 if(device) ALCdevice_DecRef(device);
1943 return;
1946 if(!device)
1948 switch(param)
1950 case ALC_MAJOR_VERSION:
1951 *data = alcMajorVersion;
1952 break;
1953 case ALC_MINOR_VERSION:
1954 *data = alcMinorVersion;
1955 break;
1957 case ALC_ATTRIBUTES_SIZE:
1958 case ALC_ALL_ATTRIBUTES:
1959 case ALC_FREQUENCY:
1960 case ALC_REFRESH:
1961 case ALC_SYNC:
1962 case ALC_MONO_SOURCES:
1963 case ALC_STEREO_SOURCES:
1964 case ALC_CAPTURE_SAMPLES:
1965 case ALC_FORMAT_CHANNELS_SOFT:
1966 case ALC_FORMAT_TYPE_SOFT:
1967 alcSetError(NULL, ALC_INVALID_DEVICE);
1968 break;
1970 default:
1971 alcSetError(NULL, ALC_INVALID_ENUM);
1972 break;
1975 else if(device->IsCaptureDevice)
1977 switch(param)
1979 case ALC_CAPTURE_SAMPLES:
1980 LockDevice(device);
1981 *data = ALCdevice_AvailableSamples(device);
1982 UnlockDevice(device);
1983 break;
1985 case ALC_CONNECTED:
1986 *data = device->Connected;
1987 break;
1989 default:
1990 alcSetError(device, ALC_INVALID_ENUM);
1991 break;
1994 else /* render device */
1996 switch(param)
1998 case ALC_MAJOR_VERSION:
1999 *data = alcMajorVersion;
2000 break;
2002 case ALC_MINOR_VERSION:
2003 *data = alcMinorVersion;
2004 break;
2006 case ALC_EFX_MAJOR_VERSION:
2007 *data = alcEFXMajorVersion;
2008 break;
2010 case ALC_EFX_MINOR_VERSION:
2011 *data = alcEFXMinorVersion;
2012 break;
2014 case ALC_ATTRIBUTES_SIZE:
2015 *data = 13;
2016 break;
2018 case ALC_ALL_ATTRIBUTES:
2019 if(size < 13)
2020 alcSetError(device, ALC_INVALID_VALUE);
2021 else
2023 int i = 0;
2025 data[i++] = ALC_FREQUENCY;
2026 data[i++] = device->Frequency;
2028 if(!device->IsLoopbackDevice)
2030 data[i++] = ALC_REFRESH;
2031 data[i++] = device->Frequency / device->UpdateSize;
2033 data[i++] = ALC_SYNC;
2034 data[i++] = ALC_FALSE;
2036 else
2038 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
2039 data[i++] = device->FmtChans;
2041 data[i++] = ALC_FORMAT_TYPE_SOFT;
2042 data[i++] = device->FmtType;
2045 data[i++] = ALC_MONO_SOURCES;
2046 data[i++] = device->NumMonoSources;
2048 data[i++] = ALC_STEREO_SOURCES;
2049 data[i++] = device->NumStereoSources;
2051 data[i++] = ALC_MAX_AUXILIARY_SENDS;
2052 data[i++] = device->NumAuxSends;
2054 data[i++] = 0;
2056 break;
2058 case ALC_FREQUENCY:
2059 *data = device->Frequency;
2060 break;
2062 case ALC_REFRESH:
2063 if(device->IsLoopbackDevice)
2064 alcSetError(device, ALC_INVALID_DEVICE);
2065 else
2066 *data = device->Frequency / device->UpdateSize;
2067 break;
2069 case ALC_SYNC:
2070 if(device->IsLoopbackDevice)
2071 alcSetError(device, ALC_INVALID_DEVICE);
2072 else
2073 *data = ALC_FALSE;
2074 break;
2076 case ALC_FORMAT_CHANNELS_SOFT:
2077 if(!device->IsLoopbackDevice)
2078 alcSetError(device, ALC_INVALID_DEVICE);
2079 else
2080 *data = device->FmtChans;
2081 break;
2083 case ALC_FORMAT_TYPE_SOFT:
2084 if(!device->IsLoopbackDevice)
2085 alcSetError(device, ALC_INVALID_DEVICE);
2086 else
2087 *data = device->FmtType;
2088 break;
2090 case ALC_MONO_SOURCES:
2091 *data = device->NumMonoSources;
2092 break;
2094 case ALC_STEREO_SOURCES:
2095 *data = device->NumStereoSources;
2096 break;
2098 case ALC_MAX_AUXILIARY_SENDS:
2099 *data = device->NumAuxSends;
2100 break;
2102 case ALC_CONNECTED:
2103 *data = device->Connected;
2104 break;
2106 default:
2107 alcSetError(device, ALC_INVALID_ENUM);
2108 break;
2111 if(device)
2112 ALCdevice_DecRef(device);
2116 /* alcIsExtensionPresent
2118 * Determines if there is support for a particular extension
2120 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2122 ALCboolean bResult = ALC_FALSE;
2124 device = VerifyDevice(device);
2126 if(!extName)
2127 alcSetError(device, ALC_INVALID_VALUE);
2128 else
2130 size_t len = strlen(extName);
2131 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2132 while(ptr && *ptr)
2134 if(strncasecmp(ptr, extName, len) == 0 &&
2135 (ptr[len] == '\0' || isspace(ptr[len])))
2137 bResult = ALC_TRUE;
2138 break;
2140 if((ptr=strchr(ptr, ' ')) != NULL)
2142 do {
2143 ++ptr;
2144 } while(isspace(*ptr));
2148 if(device)
2149 ALCdevice_DecRef(device);
2150 return bResult;
2154 /* alcGetProcAddress
2156 * Retrieves the function address for a particular extension function
2158 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2160 ALCvoid *ptr = NULL;
2162 device = VerifyDevice(device);
2164 if(!funcName)
2165 alcSetError(device, ALC_INVALID_VALUE);
2166 else
2168 ALsizei i = 0;
2169 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2170 i++;
2171 ptr = alcFunctions[i].address;
2173 if(device)
2174 ALCdevice_DecRef(device);
2175 return ptr;
2179 /* alcGetEnumValue
2181 * Get the value for a particular ALC Enumerated Value
2183 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2185 ALCenum val = 0;
2187 device = VerifyDevice(device);
2189 if(!enumName)
2190 alcSetError(device, ALC_INVALID_VALUE);
2191 else
2193 ALsizei i = 0;
2194 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2195 i++;
2196 val = enumeration[i].value;
2198 if(device)
2199 ALCdevice_DecRef(device);
2200 return val;
2204 /* alcCreateContext
2206 * Create and attach a Context to a particular Device.
2208 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2210 ALCcontext *ALContext;
2212 LockLists();
2213 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2215 UnlockLists();
2216 alcSetError(device, ALC_INVALID_DEVICE);
2217 if(device) ALCdevice_DecRef(device);
2218 return NULL;
2221 /* Reset Context Last Error code */
2222 device->LastError = ALC_NO_ERROR;
2224 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2226 UnlockLists();
2227 alcSetError(device, ALC_INVALID_DEVICE);
2228 aluHandleDisconnect(device);
2229 ALCdevice_DecRef(device);
2230 return NULL;
2233 ALContext = calloc(1, sizeof(ALCcontext));
2234 if(ALContext)
2236 ALContext->ref = 1;
2238 ALContext->MaxActiveSources = 256;
2239 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2240 ALContext->MaxActiveSources);
2242 if(!ALContext || !ALContext->ActiveSources)
2244 if(!device->ContextList)
2246 ALCdevice_StopPlayback(device);
2247 device->Flags &= ~DEVICE_RUNNING;
2249 UnlockLists();
2251 free(ALContext);
2252 ALContext = NULL;
2254 alcSetError(device, ALC_OUT_OF_MEMORY);
2255 ALCdevice_DecRef(device);
2256 return NULL;
2259 ALContext->Device = device;
2260 ALCdevice_IncRef(device);
2261 InitContext(ALContext);
2263 do {
2264 ALContext->next = device->ContextList;
2265 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2266 UnlockLists();
2268 InitializeEffect(ALContext, device->DefaultSlot, &ForcedEffect);
2270 ALCdevice_DecRef(device);
2272 TRACE("Created context %p\n", ALContext);
2273 return ALContext;
2276 /* alcDestroyContext
2278 * Remove a Context
2280 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2282 ALCdevice *Device;
2284 LockLists();
2285 /* alcGetContextsDevice sets an error for invalid contexts */
2286 Device = alcGetContextsDevice(context);
2287 if(Device)
2289 ReleaseContext(context, Device);
2290 if(!Device->ContextList)
2292 ALCdevice_StopPlayback(Device);
2293 Device->Flags &= ~DEVICE_RUNNING;
2296 UnlockLists();
2300 /* alcGetCurrentContext
2302 * Returns the currently active Context
2304 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2306 ALCcontext *Context;
2308 Context = pthread_getspecific(LocalContext);
2309 if(!Context) Context = GlobalContext;
2311 return Context;
2314 /* alcGetThreadContext
2316 * Returns the currently active thread-local Context
2318 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2320 ALCcontext *Context;
2321 Context = pthread_getspecific(LocalContext);
2322 return Context;
2326 /* alcMakeContextCurrent
2328 * Makes the given Context the active Context
2330 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2332 /* context must be a valid Context or NULL */
2333 if(context && !(context=VerifyContext(context)))
2335 alcSetError(NULL, ALC_INVALID_CONTEXT);
2336 return ALC_FALSE;
2338 /* context's reference count is already incremented */
2339 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2340 if(context) ALCcontext_DecRef(context);
2342 if((context=pthread_getspecific(LocalContext)) != NULL)
2344 pthread_setspecific(LocalContext, NULL);
2345 ALCcontext_DecRef(context);
2348 return ALC_TRUE;
2351 /* alcSetThreadContext
2353 * Makes the given Context the active Context for the current thread
2355 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2357 ALCcontext *old;
2359 /* context must be a valid Context or NULL */
2360 if(context && !(context=VerifyContext(context)))
2362 alcSetError(NULL, ALC_INVALID_CONTEXT);
2363 return ALC_FALSE;
2365 /* context's reference count is already incremented */
2366 old = pthread_getspecific(LocalContext);
2367 pthread_setspecific(LocalContext, context);
2368 if(old) ALCcontext_DecRef(old);
2370 return ALC_TRUE;
2374 /* alcGetContextsDevice
2376 * Returns the Device that a particular Context is attached to
2378 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2380 ALCdevice *Device;
2382 if(!(Context=VerifyContext(Context)))
2384 alcSetError(NULL, ALC_INVALID_CONTEXT);
2385 return NULL;
2387 Device = Context->Device;
2388 ALCcontext_DecRef(Context);
2390 return Device;
2394 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2396 static const struct {
2397 const char name[32];
2398 enum DevFmtChannels channels;
2399 enum DevFmtType type;
2400 } formats[] = {
2401 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2402 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2403 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2404 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2405 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2406 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2408 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2409 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2410 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2411 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2412 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2413 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2415 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2416 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2417 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2418 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2419 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2420 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2422 size_t i;
2424 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2426 if(strcasecmp(str, formats[i].name) == 0)
2428 *chans = formats[i].channels;
2429 *type = formats[i].type;
2430 return;
2434 ERR("Unknown format: \"%s\"\n", str);
2435 *chans = DevFmtStereo;
2436 *type = DevFmtShort;
2439 /* alcOpenDevice
2441 * Open the Device specified.
2443 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2445 const ALCchar *fmt;
2446 ALCdevice *device;
2447 ALCenum err;
2449 DO_INITCONFIG();
2451 if(!PlaybackBackend.name)
2453 alcSetError(NULL, ALC_INVALID_VALUE);
2454 return NULL;
2457 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2458 deviceName = NULL;
2460 device = calloc(1, sizeof(ALCdevice)+sizeof(ALeffectslot));
2461 if(!device)
2463 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2464 return NULL;
2467 //Validate device
2468 device->Funcs = &PlaybackBackend.Funcs;
2469 device->ref = 1;
2470 device->Connected = ALC_TRUE;
2471 device->IsCaptureDevice = AL_FALSE;
2472 device->IsLoopbackDevice = AL_FALSE;
2473 InitializeCriticalSection(&device->Mutex);
2474 device->LastError = ALC_NO_ERROR;
2476 device->Flags = 0;
2477 device->Bs2b = NULL;
2478 device->Bs2bLevel = 0;
2479 device->szDeviceName = NULL;
2481 device->ContextList = NULL;
2483 device->MaxNoOfSources = 256;
2484 device->AuxiliaryEffectSlotMax = 4;
2485 device->NumAuxSends = MAX_SENDS;
2487 InitUIntMap(&device->BufferMap, ~0);
2488 InitUIntMap(&device->EffectMap, ~0);
2489 InitUIntMap(&device->FilterMap, ~0);
2491 //Set output format
2492 device->NumUpdates = 4;
2493 device->UpdateSize = 1024;
2495 device->Frequency = DEFAULT_OUTPUT_RATE;
2496 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2497 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2498 device->Frequency = maxu(device->Frequency, 8000);
2500 fmt = "AL_FORMAT_STEREO32";
2501 if(ConfigValueStr(NULL, "format", &fmt))
2502 device->Flags |= DEVICE_CHANNELS_REQUEST;
2503 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2505 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2506 if(device->NumUpdates < 2) device->NumUpdates = 4;
2508 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2509 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2511 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2512 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2514 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2515 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2517 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2518 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2520 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2522 device->NumStereoSources = 1;
2523 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2525 device->DefaultSlot = (ALeffectslot*)(device+1);
2526 if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR)
2527 device->DefaultSlot = NULL;
2529 // Find a playback device to open
2530 LockLists();
2531 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2533 UnlockLists();
2534 DeleteCriticalSection(&device->Mutex);
2535 free(device);
2536 alcSetError(NULL, err);
2537 return NULL;
2539 UnlockLists();
2541 do {
2542 device->next = DeviceList;
2543 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2545 TRACE("Created device %p\n", device);
2546 return device;
2549 /* alcCloseDevice
2551 * Close the specified Device
2553 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2555 ALCdevice *volatile*list;
2556 ALCcontext *ctx;
2558 LockLists();
2559 list = &DeviceList;
2560 while(*list && *list != pDevice)
2561 list = &(*list)->next;
2563 if(!*list || (*list)->IsCaptureDevice)
2565 alcSetError(*list, ALC_INVALID_DEVICE);
2566 UnlockLists();
2567 return ALC_FALSE;
2570 *list = (*list)->next;
2571 UnlockLists();
2573 if((ctx=pDevice->ContextList) != NULL)
2575 do {
2576 WARN("Releasing context %p\n", ctx);
2577 ReleaseContext(ctx, pDevice);
2578 } while((ctx=pDevice->ContextList) != NULL);
2579 ALCdevice_StopPlayback(pDevice);
2580 pDevice->Flags &= ~DEVICE_RUNNING;
2582 ALCdevice_ClosePlayback(pDevice);
2584 ALCdevice_DecRef(pDevice);
2586 return ALC_TRUE;
2590 /* alcLoopbackOpenDeviceSOFT
2592 * Open a loopback device, for manual rendering.
2594 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2596 ALCdevice *device;
2598 DO_INITCONFIG();
2600 device = calloc(1, sizeof(ALCdevice));
2601 if(!device)
2603 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2604 return NULL;
2607 //Validate device
2608 device->Funcs = &BackendLoopback.Funcs;
2609 device->ref = 1;
2610 device->Connected = ALC_TRUE;
2611 device->IsCaptureDevice = AL_FALSE;
2612 device->IsLoopbackDevice = AL_TRUE;
2613 InitializeCriticalSection(&device->Mutex);
2614 device->LastError = ALC_NO_ERROR;
2616 device->Flags = 0;
2617 device->Bs2b = NULL;
2618 device->Bs2bLevel = 0;
2619 device->szDeviceName = NULL;
2621 device->ContextList = NULL;
2623 device->MaxNoOfSources = 256;
2624 device->AuxiliaryEffectSlotMax = 4;
2625 device->NumAuxSends = MAX_SENDS;
2627 InitUIntMap(&device->BufferMap, ~0);
2628 InitUIntMap(&device->EffectMap, ~0);
2629 InitUIntMap(&device->FilterMap, ~0);
2631 //Set output format
2632 device->NumUpdates = 0;
2633 device->UpdateSize = 0;
2635 device->Frequency = 44100;
2636 device->FmtChans = DevFmtStereo;
2637 device->FmtType = DevFmtShort;
2639 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2640 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2642 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2643 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2645 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2646 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2648 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2650 device->NumStereoSources = 1;
2651 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2653 // Open the "backend"
2654 ALCdevice_OpenPlayback(device, "Loopback");
2655 do {
2656 device->next = DeviceList;
2657 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2659 TRACE("Created device %p\n", device);
2660 return device;
2663 /* alcIsRenderFormatSupportedSOFT
2665 * Determines if the loopback device supports the given format for rendering.
2667 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2669 ALCboolean ret = ALC_FALSE;
2671 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2672 alcSetError(device, ALC_INVALID_DEVICE);
2673 else if(freq <= 0)
2674 alcSetError(device, ALC_INVALID_VALUE);
2675 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2676 alcSetError(device, ALC_INVALID_ENUM);
2677 else
2679 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2680 freq >= 8000)
2681 ret = ALC_TRUE;
2683 if(device) ALCdevice_DecRef(device);
2685 return ret;
2688 /* alcRenderSamplesSOFT
2690 * Renders some samples into a buffer, using the format last set by the
2691 * attributes given to alcCreateContext.
2693 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2695 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2696 alcSetError(device, ALC_INVALID_DEVICE);
2697 else if(samples < 0 || (samples > 0 && buffer == NULL))
2698 alcSetError(device, ALC_INVALID_VALUE);
2699 else
2700 aluMixData(device, buffer, samples);
2701 if(device) ALCdevice_DecRef(device);
2705 static void ReleaseALC(void)
2707 ALCdevice *dev;
2709 free(alcDeviceList); alcDeviceList = NULL;
2710 alcDeviceListSize = 0;
2711 free(alcAllDeviceList); alcAllDeviceList = NULL;
2712 alcAllDeviceListSize = 0;
2713 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2714 alcCaptureDeviceListSize = 0;
2716 free(alcDefaultDeviceSpecifier);
2717 alcDefaultDeviceSpecifier = NULL;
2718 free(alcDefaultAllDeviceSpecifier);
2719 alcDefaultAllDeviceSpecifier = NULL;
2720 free(alcCaptureDefaultDeviceSpecifier);
2721 alcCaptureDefaultDeviceSpecifier = NULL;
2723 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2725 ALCuint num = 0;
2726 do {
2727 num++;
2728 } while((dev=dev->next) != NULL);
2729 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2733 ///////////////////////////////////////////////////////