Change the default output format to 32-bit float
[openal-soft.git] / Alc / ALc.c
blobb6a01c57c73fbd68167e5c22d47066695737744d
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 ///////////////////////////////////////////////////////
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(ConfigValueStr(NULL, "resampler", &str))
588 if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0)
589 DefaultResampler = POINT_RESAMPLER;
590 else if(strcasecmp(str, "linear") == 0)
591 DefaultResampler = LINEAR_RESAMPLER;
592 else if(strcasecmp(str, "cubic") == 0)
593 DefaultResampler = CUBIC_RESAMPLER;
594 else
596 char *end;
598 n = strtol(str, &end, 0);
599 if(*end == '\0' && n < RESAMPLER_MAX && n > RESAMPLER_MIN)
600 DefaultResampler = n;
601 else
602 WARN("Invalid resampler: %s\n", str);
606 if(!TrapALCError)
607 TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", ALC_FALSE);
609 if(!TrapALError)
610 TrapALError = GetConfigValueBool(NULL, "trap-al-error", AL_FALSE);
612 if(ConfigValueFloat("reverb", "boost", &valf))
613 ReverbBoost *= aluPow(10.0f, valf / 20.0f);
615 EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE);
617 if(ConfigValueStr(NULL, "drivers", &devs))
619 int n;
620 size_t len;
621 const char *next = devs;
622 int endlist, delitem;
624 i = 0;
625 do {
626 devs = next;
627 next = strchr(devs, ',');
629 delitem = (devs[0] == '-');
630 if(devs[0] == '-') devs++;
632 if(!devs[0] || devs[0] == ',')
634 endlist = 0;
635 continue;
637 endlist = 1;
639 len = (next ? ((size_t)(next-devs)) : strlen(devs));
640 for(n = i;BackendList[n].Init;n++)
642 if(len == strlen(BackendList[n].name) &&
643 strncmp(BackendList[n].name, devs, len) == 0)
645 if(delitem)
647 do {
648 BackendList[n] = BackendList[n+1];
649 ++n;
650 } while(BackendList[n].Init);
652 else
654 struct BackendInfo Bkp = BackendList[n];
655 while(n > i)
657 BackendList[n] = BackendList[n-1];
658 --n;
660 BackendList[n] = Bkp;
662 i++;
664 break;
667 } while(next++);
669 if(endlist)
671 BackendList[i].name = NULL;
672 BackendList[i].Init = NULL;
673 BackendList[i].Deinit = NULL;
674 BackendList[i].Probe = NULL;
678 for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++)
680 if(!BackendList[i].Init(&BackendList[i].Funcs))
682 WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name);
683 continue;
686 TRACE("Initialized backend \"%s\"\n", BackendList[i].name);
687 if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name)
689 PlaybackBackend = BackendList[i];
690 TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
692 if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name)
694 CaptureBackend = BackendList[i];
695 TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
698 BackendLoopback.Init(&BackendLoopback.Funcs);
700 if(ConfigValueStr(NULL, "excludefx", &str))
702 size_t len;
703 const char *next = str;
705 do {
706 str = next;
707 next = strchr(str, ',');
709 if(!str[0] || next == str)
710 continue;
712 len = (next ? ((size_t)(next-str)) : strlen(str));
713 for(n = 0;EffectList[n].name;n++)
715 if(len == strlen(EffectList[n].name) &&
716 strncmp(EffectList[n].name, str, len) == 0)
717 DisabledEffects[EffectList[n].type] = AL_TRUE;
719 } while(next++);
724 static void LockLists(void)
726 EnterCriticalSection(&ListLock);
729 static void UnlockLists(void)
731 LeaveCriticalSection(&ListLock);
735 static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type)
737 DO_INITCONFIG();
739 LockLists();
740 free(*list);
741 *list = NULL;
742 *listsize = 0;
744 if(type == CAPTURE_DEVICE_PROBE)
745 CaptureBackend.Probe(type);
746 else
747 PlaybackBackend.Probe(type);
748 UnlockLists();
751 static void ProbeDeviceList(void)
752 { ProbeList(&alcDeviceList, &alcDeviceListSize, DEVICE_PROBE); }
753 static void ProbeAllDeviceList(void)
754 { ProbeList(&alcAllDeviceList, &alcAllDeviceListSize, ALL_DEVICE_PROBE); }
755 static void ProbeCaptureDeviceList(void)
756 { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); }
759 static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize)
761 size_t len = strlen(name);
762 void *temp;
764 if(len == 0)
765 return;
767 temp = realloc(*List, (*ListSize) + len + 2);
768 if(!temp)
770 ERR("Realloc failed to add %s!\n", name);
771 return;
773 *List = temp;
775 memcpy((*List)+(*ListSize), name, len+1);
776 *ListSize += len+1;
777 (*List)[*ListSize] = 0;
780 #define DECL_APPEND_LIST_FUNC(type) \
781 void Append##type##List(const ALCchar *name) \
782 { AppendList(name, &alc##type##List, &alc##type##ListSize); }
784 DECL_APPEND_LIST_FUNC(Device)
785 DECL_APPEND_LIST_FUNC(AllDevice)
786 DECL_APPEND_LIST_FUNC(CaptureDevice)
788 #undef DECL_APPEND_LIST_FUNC
791 /* Sets the default channel order used by most non-WaveFormatEx-based APIs */
792 void SetDefaultChannelOrder(ALCdevice *device)
794 switch(device->FmtChans)
796 case DevFmtX51: device->DevChannels[0] = FRONT_LEFT;
797 device->DevChannels[1] = FRONT_RIGHT;
798 device->DevChannels[2] = BACK_LEFT;
799 device->DevChannels[3] = BACK_RIGHT;
800 device->DevChannels[4] = FRONT_CENTER;
801 device->DevChannels[5] = LFE;
802 return;
804 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
805 device->DevChannels[1] = FRONT_RIGHT;
806 device->DevChannels[2] = BACK_LEFT;
807 device->DevChannels[3] = BACK_RIGHT;
808 device->DevChannels[4] = FRONT_CENTER;
809 device->DevChannels[5] = LFE;
810 device->DevChannels[6] = SIDE_LEFT;
811 device->DevChannels[7] = SIDE_RIGHT;
812 return;
814 /* Same as WFX order */
815 case DevFmtMono:
816 case DevFmtStereo:
817 case DevFmtQuad:
818 case DevFmtX51Side:
819 case DevFmtX61:
820 break;
822 SetDefaultWFXChannelOrder(device);
824 /* Sets the default order used by WaveFormatEx */
825 void SetDefaultWFXChannelOrder(ALCdevice *device)
827 switch(device->FmtChans)
829 case DevFmtMono: device->DevChannels[0] = FRONT_CENTER; break;
831 case DevFmtStereo: device->DevChannels[0] = FRONT_LEFT;
832 device->DevChannels[1] = FRONT_RIGHT; break;
834 case DevFmtQuad: device->DevChannels[0] = FRONT_LEFT;
835 device->DevChannels[1] = FRONT_RIGHT;
836 device->DevChannels[2] = BACK_LEFT;
837 device->DevChannels[3] = BACK_RIGHT; break;
839 case DevFmtX51: 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_LEFT;
844 device->DevChannels[5] = BACK_RIGHT; break;
846 case DevFmtX51Side: device->DevChannels[0] = FRONT_LEFT;
847 device->DevChannels[1] = FRONT_RIGHT;
848 device->DevChannels[2] = FRONT_CENTER;
849 device->DevChannels[3] = LFE;
850 device->DevChannels[4] = SIDE_LEFT;
851 device->DevChannels[5] = SIDE_RIGHT; break;
853 case DevFmtX61: device->DevChannels[0] = FRONT_LEFT;
854 device->DevChannels[1] = FRONT_RIGHT;
855 device->DevChannels[2] = FRONT_CENTER;
856 device->DevChannels[3] = LFE;
857 device->DevChannels[4] = BACK_CENTER;
858 device->DevChannels[5] = SIDE_LEFT;
859 device->DevChannels[6] = SIDE_RIGHT; break;
861 case DevFmtX71: device->DevChannels[0] = FRONT_LEFT;
862 device->DevChannels[1] = FRONT_RIGHT;
863 device->DevChannels[2] = FRONT_CENTER;
864 device->DevChannels[3] = LFE;
865 device->DevChannels[4] = BACK_LEFT;
866 device->DevChannels[5] = BACK_RIGHT;
867 device->DevChannels[6] = SIDE_LEFT;
868 device->DevChannels[7] = SIDE_RIGHT; break;
873 const ALCchar *DevFmtTypeString(enum DevFmtType type)
875 switch(type)
877 case DevFmtByte: return "Signed Byte";
878 case DevFmtUByte: return "Unsigned Byte";
879 case DevFmtShort: return "Signed Short";
880 case DevFmtUShort: return "Unsigned Short";
881 case DevFmtFloat: return "Float";
883 return "(unknown type)";
885 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans)
887 switch(chans)
889 case DevFmtMono: return "Mono";
890 case DevFmtStereo: return "Stereo";
891 case DevFmtQuad: return "Quadraphonic";
892 case DevFmtX51: return "5.1 Surround";
893 case DevFmtX51Side: return "5.1 Side";
894 case DevFmtX61: return "6.1 Surround";
895 case DevFmtX71: return "7.1 Surround";
897 return "(unknown channels)";
900 ALuint BytesFromDevFmt(enum DevFmtType type)
902 switch(type)
904 case DevFmtByte: return sizeof(ALbyte);
905 case DevFmtUByte: return sizeof(ALubyte);
906 case DevFmtShort: return sizeof(ALshort);
907 case DevFmtUShort: return sizeof(ALushort);
908 case DevFmtFloat: return sizeof(ALfloat);
910 return 0;
912 ALuint ChannelsFromDevFmt(enum DevFmtChannels chans)
914 switch(chans)
916 case DevFmtMono: return 1;
917 case DevFmtStereo: return 2;
918 case DevFmtQuad: return 4;
919 case DevFmtX51: return 6;
920 case DevFmtX51Side: return 6;
921 case DevFmtX61: return 7;
922 case DevFmtX71: return 8;
924 return 0;
926 static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans,
927 enum DevFmtType *type)
929 static const struct {
930 ALenum format;
931 enum DevFmtChannels channels;
932 enum DevFmtType type;
933 } list[] = {
934 { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
935 { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
936 { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
938 { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
939 { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
940 { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
942 { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
943 { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
944 { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
946 { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
947 { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
948 { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
950 { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
951 { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
952 { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
954 { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
955 { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
956 { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
958 ALuint i;
960 for(i = 0;i < sizeof(list)/sizeof(list[0]);i++)
962 if(list[i].format == format)
964 *chans = list[i].channels;
965 *type = list[i].type;
966 return AL_TRUE;
970 return AL_FALSE;
973 static ALCboolean IsValidALCType(ALCenum type)
975 switch(type)
977 case ALC_BYTE_SOFT:
978 case ALC_UNSIGNED_BYTE_SOFT:
979 case ALC_SHORT_SOFT:
980 case ALC_UNSIGNED_SHORT_SOFT:
981 case ALC_INT_SOFT:
982 case ALC_UNSIGNED_INT_SOFT:
983 case ALC_FLOAT_SOFT:
984 return ALC_TRUE;
986 return ALC_FALSE;
989 static ALCboolean IsValidALCChannels(ALCenum channels)
991 switch(channels)
993 case ALC_MONO_SOFT:
994 case ALC_STEREO_SOFT:
995 case ALC_QUAD_SOFT:
996 case ALC_5POINT1_SOFT:
997 case ALC_6POINT1_SOFT:
998 case ALC_7POINT1_SOFT:
999 return ALC_TRUE;
1001 return ALC_FALSE;
1005 /* alcSetError
1007 * Stores the latest ALC Error
1009 static void alcSetError(ALCdevice *device, ALCenum errorCode)
1011 if(TrapALCError)
1013 #ifdef _WIN32
1014 /* DebugBreak() will cause an exception if there is no debugger */
1015 if(IsDebuggerPresent())
1016 DebugBreak();
1017 #elif defined(SIGTRAP)
1018 raise(SIGTRAP);
1019 #endif
1022 if(device)
1023 device->LastError = errorCode;
1024 else
1025 g_eLastNullDeviceError = errorCode;
1029 /* UpdateDeviceParams
1031 * Updates device parameters according to the attribute list (caller is
1032 * responsible for holding the list lock).
1034 static ALCboolean UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
1036 ALCcontext *context;
1037 int oldMode;
1038 ALuint i;
1040 // Check for attributes
1041 if(attrList && attrList[0])
1043 ALCuint freq, numMono, numStereo, numSends;
1044 enum DevFmtChannels schans;
1045 enum DevFmtType stype;
1046 ALuint attrIdx;
1048 // If a context is already running on the device, stop playback so the
1049 // device attributes can be updated
1050 if((device->Flags&DEVICE_RUNNING))
1051 ALCdevice_StopPlayback(device);
1052 device->Flags &= ~DEVICE_RUNNING;
1054 freq = device->Frequency;
1055 schans = device->FmtChans;
1056 stype = device->FmtType;
1057 numMono = device->NumMonoSources;
1058 numStereo = device->NumStereoSources;
1059 numSends = device->NumAuxSends;
1061 attrIdx = 0;
1062 while(attrList[attrIdx])
1064 if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT &&
1065 device->IsLoopbackDevice)
1067 ALCint val = attrList[attrIdx + 1];
1068 if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val))
1070 alcSetError(device, ALC_INVALID_VALUE);
1071 return ALC_FALSE;
1073 schans = val;
1076 if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT &&
1077 device->IsLoopbackDevice)
1079 ALCint val = attrList[attrIdx + 1];
1080 if(!IsValidALCType(val) || !BytesFromDevFmt(val))
1082 alcSetError(device, ALC_INVALID_VALUE);
1083 return ALC_FALSE;
1085 stype = val;
1088 if(attrList[attrIdx] == ALC_FREQUENCY)
1090 if(device->IsLoopbackDevice)
1092 freq = attrList[attrIdx + 1];
1093 if(freq < 8000)
1095 alcSetError(device, ALC_INVALID_VALUE);
1096 return ALC_FALSE;
1099 else
1101 freq = attrList[attrIdx + 1];
1102 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1106 if(attrList[attrIdx] == ALC_STEREO_SOURCES)
1108 numStereo = attrList[attrIdx + 1];
1109 if(numStereo > device->MaxNoOfSources)
1110 numStereo = device->MaxNoOfSources;
1112 numMono = device->MaxNoOfSources - numStereo;
1115 if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS)
1116 numSends = attrList[attrIdx + 1];
1118 attrIdx += 2;
1121 if(!device->IsLoopbackDevice)
1123 ConfigValueUInt(NULL, "frequency", &freq);
1124 freq = maxu(freq, 8000);
1126 ConfigValueUInt(NULL, "sends", &numSends);
1127 numSends = minu(MAX_SENDS, numSends);
1129 device->UpdateSize = (ALuint64)device->UpdateSize * freq /
1130 device->Frequency;
1132 device->Frequency = freq;
1133 device->FmtChans = schans;
1134 device->FmtType = stype;
1135 device->NumMonoSources = numMono;
1136 device->NumStereoSources = numStereo;
1137 device->NumAuxSends = numSends;
1140 if((device->Flags&DEVICE_RUNNING))
1141 return ALC_TRUE;
1143 LockDevice(device);
1144 TRACE("Format pre-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1145 DevFmtChannelsString(device->FmtChans),
1146 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1147 DevFmtTypeString(device->FmtType), device->Frequency,
1148 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1149 device->UpdateSize, device->NumUpdates);
1150 if(ALCdevice_ResetPlayback(device) == ALC_FALSE)
1152 UnlockDevice(device);
1153 return ALC_FALSE;
1155 device->Flags |= DEVICE_RUNNING;
1156 TRACE("Format post-setup: %s%s, %s, %uhz%s, %u update size x%d\n",
1157 DevFmtChannelsString(device->FmtChans),
1158 (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"",
1159 DevFmtTypeString(device->FmtType), device->Frequency,
1160 (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"",
1161 device->UpdateSize, device->NumUpdates);
1163 aluInitPanning(device);
1165 for(i = 0;i < MAXCHANNELS;i++)
1167 device->ClickRemoval[i] = 0.0f;
1168 device->PendingClicks[i] = 0.0f;
1171 device->Hrtf = NULL;
1172 if(!device->IsLoopbackDevice && GetConfigValueBool(NULL, "hrtf", AL_FALSE))
1173 device->Hrtf = GetHrtf(device);
1174 TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled");
1176 if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6)
1178 if(!device->Bs2b)
1180 device->Bs2b = calloc(1, sizeof(*device->Bs2b));
1181 bs2b_clear(device->Bs2b);
1183 bs2b_set_srate(device->Bs2b, device->Frequency);
1184 bs2b_set_level(device->Bs2b, device->Bs2bLevel);
1185 TRACE("BS2B level %d\n", device->Bs2bLevel);
1187 else
1189 free(device->Bs2b);
1190 device->Bs2b = NULL;
1191 TRACE("BS2B disabled\n");
1194 device->Flags &= ~DEVICE_DUPLICATE_STEREO;
1195 switch(device->FmtChans)
1197 case DevFmtMono:
1198 case DevFmtStereo:
1199 break;
1200 case DevFmtQuad:
1201 case DevFmtX51:
1202 case DevFmtX51Side:
1203 case DevFmtX61:
1204 case DevFmtX71:
1205 if(GetConfigValueBool(NULL, "stereodup", AL_TRUE))
1206 device->Flags |= DEVICE_DUPLICATE_STEREO;
1207 break;
1209 TRACE("Stereo duplication %s\n", (device->Flags&DEVICE_DUPLICATE_STEREO)?"enabled":"disabled");
1211 oldMode = SetMixerFPUMode();
1212 context = device->ContextList;
1213 while(context)
1215 ALsizei pos;
1217 context->UpdateSources = AL_FALSE;
1218 LockUIntMapRead(&context->EffectSlotMap);
1219 for(pos = 0;pos < context->EffectSlotMap.size;pos++)
1221 ALeffectslot *slot = context->EffectSlotMap.array[pos].value;
1223 if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE)
1225 UnlockUIntMapRead(&context->EffectSlotMap);
1226 RestoreFPUMode(oldMode);
1227 UnlockDevice(device);
1228 ALCdevice_StopPlayback(device);
1229 device->Flags &= ~DEVICE_RUNNING;
1230 return ALC_FALSE;
1232 slot->NeedsUpdate = AL_FALSE;
1233 ALeffectState_Update(slot->EffectState, context, slot);
1235 UnlockUIntMapRead(&context->EffectSlotMap);
1237 LockUIntMapRead(&context->SourceMap);
1238 for(pos = 0;pos < context->SourceMap.size;pos++)
1240 ALsource *source = context->SourceMap.array[pos].value;
1241 ALuint s = device->NumAuxSends;
1242 while(s < MAX_SENDS)
1244 if(source->Send[s].Slot)
1245 DecrementRef(&source->Send[s].Slot->ref);
1246 source->Send[s].Slot = NULL;
1247 source->Send[s].WetGain = 1.0f;
1248 source->Send[s].WetGainHF = 1.0f;
1249 s++;
1251 source->NeedsUpdate = AL_FALSE;
1252 ALsource_Update(source, context);
1254 UnlockUIntMapRead(&context->SourceMap);
1256 context = context->next;
1258 RestoreFPUMode(oldMode);
1259 UnlockDevice(device);
1261 return ALC_TRUE;
1264 /* FreeDevice
1266 * Frees the device structure, and destroys any objects the app failed to
1267 * delete. Called once there's no more references on the device.
1269 static ALCvoid FreeDevice(ALCdevice *device)
1271 TRACE("%p\n", device);
1273 if(device->BufferMap.size > 0)
1275 WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size);
1276 ReleaseALBuffers(device);
1278 ResetUIntMap(&device->BufferMap);
1280 if(device->EffectMap.size > 0)
1282 WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size);
1283 ReleaseALEffects(device);
1285 ResetUIntMap(&device->EffectMap);
1287 if(device->FilterMap.size > 0)
1289 WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size);
1290 ReleaseALFilters(device);
1292 ResetUIntMap(&device->FilterMap);
1294 free(device->Bs2b);
1295 device->Bs2b = NULL;
1297 free(device->szDeviceName);
1298 device->szDeviceName = NULL;
1300 DeleteCriticalSection(&device->Mutex);
1302 free(device);
1306 void ALCdevice_IncRef(ALCdevice *device)
1308 RefCount ref;
1309 ref = IncrementRef(&device->ref);
1310 TRACEREF("%p increasing refcount to %u\n", device, ref);
1313 void ALCdevice_DecRef(ALCdevice *device)
1315 RefCount ref;
1316 ref = DecrementRef(&device->ref);
1317 TRACEREF("%p decreasing refcount to %u\n", device, ref);
1318 if(ref == 0) FreeDevice(device);
1321 /* VerifyDevice
1323 * Checks if the device handle is valid, and increments its ref count if so.
1325 static ALCdevice *VerifyDevice(ALCdevice *device)
1327 ALCdevice *tmpDevice;
1329 if(!device)
1330 return NULL;
1332 LockLists();
1333 tmpDevice = DeviceList;
1334 while(tmpDevice && tmpDevice != device)
1335 tmpDevice = tmpDevice->next;
1337 if(tmpDevice)
1338 ALCdevice_IncRef(tmpDevice);
1339 UnlockLists();
1340 return tmpDevice;
1344 /* InitContext
1346 * Initializes context variables
1348 static ALvoid InitContext(ALCcontext *pContext)
1350 ALint i, j;
1352 //Initialise listener
1353 pContext->Listener.Gain = 1.0f;
1354 pContext->Listener.MetersPerUnit = 1.0f;
1355 pContext->Listener.Position[0] = 0.0f;
1356 pContext->Listener.Position[1] = 0.0f;
1357 pContext->Listener.Position[2] = 0.0f;
1358 pContext->Listener.Velocity[0] = 0.0f;
1359 pContext->Listener.Velocity[1] = 0.0f;
1360 pContext->Listener.Velocity[2] = 0.0f;
1361 pContext->Listener.Forward[0] = 0.0f;
1362 pContext->Listener.Forward[1] = 0.0f;
1363 pContext->Listener.Forward[2] = -1.0f;
1364 pContext->Listener.Up[0] = 0.0f;
1365 pContext->Listener.Up[1] = 1.0f;
1366 pContext->Listener.Up[2] = 0.0f;
1367 for(i = 0;i < 4;i++)
1369 for(j = 0;j < 4;j++)
1370 pContext->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f);
1373 //Validate pContext
1374 pContext->LastError = AL_NO_ERROR;
1375 pContext->UpdateSources = AL_FALSE;
1376 pContext->ActiveSourceCount = 0;
1377 InitUIntMap(&pContext->SourceMap, pContext->Device->MaxNoOfSources);
1378 InitUIntMap(&pContext->EffectSlotMap, pContext->Device->AuxiliaryEffectSlotMax);
1380 //Set globals
1381 pContext->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED;
1382 pContext->SourceDistanceModel = AL_FALSE;
1383 pContext->DopplerFactor = 1.0f;
1384 pContext->DopplerVelocity = 1.0f;
1385 pContext->flSpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
1386 pContext->DeferUpdates = AL_FALSE;
1388 pContext->ExtensionList = alExtList;
1392 /* FreeContext
1394 * Cleans up the context, and destroys any remaining objects the app failed to
1395 * delete. Called once there's no more references on the context.
1397 static ALCvoid FreeContext(ALCcontext *context)
1399 TRACE("%p\n", context);
1401 if(context->SourceMap.size > 0)
1403 ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size);
1404 ReleaseALSources(context);
1406 ResetUIntMap(&context->SourceMap);
1408 if(context->EffectSlotMap.size > 0)
1410 ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size);
1411 ReleaseALAuxiliaryEffectSlots(context);
1413 ResetUIntMap(&context->EffectSlotMap);
1415 context->ActiveSourceCount = 0;
1416 free(context->ActiveSources);
1417 context->ActiveSources = NULL;
1418 context->MaxActiveSources = 0;
1420 context->ActiveEffectSlotCount = 0;
1421 free(context->ActiveEffectSlots);
1422 context->ActiveEffectSlots = NULL;
1423 context->MaxActiveEffectSlots = 0;
1425 ALCdevice_DecRef(context->Device);
1426 context->Device = NULL;
1428 //Invalidate context
1429 memset(context, 0, sizeof(ALCcontext));
1430 free(context);
1433 /* ReleaseContext
1435 * Removes the context reference from the given device and removes it from
1436 * being current on the running thread or globally.
1438 static void ReleaseContext(ALCcontext *context, ALCdevice *device)
1440 ALCcontext *volatile*tmp_ctx;
1442 if(pthread_getspecific(LocalContext) == context)
1444 WARN("%p released while current on thread\n", context);
1445 pthread_setspecific(LocalContext, NULL);
1446 ALCcontext_DecRef(context);
1449 if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL))
1450 ALCcontext_DecRef(context);
1452 LockDevice(device);
1453 tmp_ctx = &device->ContextList;
1454 while(*tmp_ctx)
1456 if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next))
1457 break;
1458 tmp_ctx = &(*tmp_ctx)->next;
1460 UnlockDevice(device);
1462 ALCcontext_DecRef(context);
1465 void ALCcontext_IncRef(ALCcontext *context)
1467 RefCount ref;
1468 ref = IncrementRef(&context->ref);
1469 TRACEREF("%p increasing refcount to %u\n", context, ref);
1472 void ALCcontext_DecRef(ALCcontext *context)
1474 RefCount ref;
1475 ref = DecrementRef(&context->ref);
1476 TRACEREF("%p decreasing refcount to %u\n", context, ref);
1477 if(ref == 0) FreeContext(context);
1480 static void ReleaseThreadCtx(void *ptr)
1482 WARN("%p current for thread being destroyed\n", ptr);
1483 ALCcontext_DecRef(ptr);
1486 /* VerifyContext
1488 * Checks that the given context is valid, and increments its reference count.
1490 static ALCcontext *VerifyContext(ALCcontext *context)
1492 ALCdevice *dev;
1494 LockLists();
1495 dev = DeviceList;
1496 while(dev)
1498 ALCcontext *tmp_ctx = dev->ContextList;
1499 while(tmp_ctx)
1501 if(tmp_ctx == context)
1503 ALCcontext_IncRef(tmp_ctx);
1504 UnlockLists();
1505 return tmp_ctx;
1507 tmp_ctx = tmp_ctx->next;
1509 dev = dev->next;
1511 UnlockLists();
1513 return NULL;
1517 /* GetContextRef
1519 * Returns the currently active context, and adds a reference without locking
1520 * it.
1522 ALCcontext *GetContextRef(void)
1524 ALCcontext *context;
1526 context = pthread_getspecific(LocalContext);
1527 if(context)
1528 ALCcontext_IncRef(context);
1529 else
1531 LockLists();
1532 context = GlobalContext;
1533 if(context)
1534 ALCcontext_IncRef(context);
1535 UnlockLists();
1538 return context;
1541 ///////////////////////////////////////////////////////
1544 ///////////////////////////////////////////////////////
1545 // ALC Functions calls
1548 // This should probably move to another c file but for now ...
1549 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
1551 ALCdevice *device = NULL;
1552 ALCenum err;
1554 DO_INITCONFIG();
1556 if(!CaptureBackend.name)
1558 alcSetError(NULL, ALC_INVALID_VALUE);
1559 return NULL;
1562 if(SampleSize <= 0)
1564 alcSetError(NULL, ALC_INVALID_VALUE);
1565 return NULL;
1568 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
1569 deviceName = NULL;
1571 device = calloc(1, sizeof(ALCdevice));
1572 if(!device)
1574 alcSetError(NULL, ALC_OUT_OF_MEMORY);
1575 return NULL;
1578 //Validate device
1579 device->Funcs = &CaptureBackend.Funcs;
1580 device->ref = 1;
1581 device->Connected = ALC_TRUE;
1582 device->IsCaptureDevice = AL_TRUE;
1583 device->IsLoopbackDevice = AL_FALSE;
1584 InitializeCriticalSection(&device->Mutex);
1586 InitUIntMap(&device->BufferMap, ~0);
1587 InitUIntMap(&device->EffectMap, ~0);
1588 InitUIntMap(&device->FilterMap, ~0);
1590 device->szDeviceName = NULL;
1592 device->Flags |= DEVICE_FREQUENCY_REQUEST;
1593 device->Frequency = frequency;
1595 device->Flags |= DEVICE_CHANNELS_REQUEST;
1596 if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
1598 DeleteCriticalSection(&device->Mutex);
1599 free(device);
1600 alcSetError(NULL, ALC_INVALID_ENUM);
1601 return NULL;
1604 device->UpdateSize = SampleSize;
1605 device->NumUpdates = 1;
1607 LockLists();
1608 if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR)
1610 UnlockLists();
1611 DeleteCriticalSection(&device->Mutex);
1612 free(device);
1613 alcSetError(NULL, err);
1614 return NULL;
1616 UnlockLists();
1618 do {
1619 device->next = DeviceList;
1620 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
1622 TRACE("Created device %p\n", device);
1623 return device;
1626 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *pDevice)
1628 ALCdevice *volatile*list;
1630 LockLists();
1631 list = &DeviceList;
1632 while(*list && *list != pDevice)
1633 list = &(*list)->next;
1635 if(!*list || !(*list)->IsCaptureDevice)
1637 alcSetError(*list, ALC_INVALID_DEVICE);
1638 UnlockLists();
1639 return ALC_FALSE;
1642 *list = (*list)->next;
1643 UnlockLists();
1645 LockDevice(pDevice);
1646 ALCdevice_CloseCapture(pDevice);
1647 UnlockDevice(pDevice);
1649 ALCdevice_DecRef(pDevice);
1651 return ALC_TRUE;
1654 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
1656 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1658 alcSetError(device, ALC_INVALID_DEVICE);
1659 if(device) ALCdevice_DecRef(device);
1660 return;
1662 LockDevice(device);
1663 if(device->Connected)
1664 ALCdevice_StartCapture(device);
1665 UnlockDevice(device);
1667 ALCdevice_DecRef(device);
1670 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
1672 if(!(device=VerifyDevice(device)) || !device->IsCaptureDevice)
1674 alcSetError(device, ALC_INVALID_DEVICE);
1675 if(device) ALCdevice_DecRef(device);
1676 return;
1678 LockDevice(device);
1679 if(device->Connected)
1680 ALCdevice_StopCapture(device);
1681 UnlockDevice(device);
1683 ALCdevice_DecRef(device);
1686 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
1688 ALCenum err = ALC_INVALID_DEVICE;
1689 if((device=VerifyDevice(device)) != NULL && device->IsCaptureDevice)
1691 err = ALC_INVALID_VALUE;
1692 LockDevice(device);
1693 if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples)
1694 err = ALCdevice_CaptureSamples(device, buffer, samples);
1695 UnlockDevice(device);
1697 if(err != ALC_NO_ERROR)
1698 alcSetError(device, err);
1699 if(device) ALCdevice_DecRef(device);
1703 alcGetError
1705 Return last ALC generated error code
1707 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
1709 ALCenum errorCode;
1711 if(VerifyDevice(device))
1713 errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR);
1714 ALCdevice_DecRef(device);
1716 else
1717 errorCode = ExchangeInt(&g_eLastNullDeviceError, ALC_NO_ERROR);
1719 return errorCode;
1723 /* alcSuspendContext
1725 * Not functional
1727 ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context)
1729 (void)Context;
1732 /* alcProcessContext
1734 * Not functional
1736 ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context)
1738 (void)Context;
1742 /* alcGetString
1744 * Returns information about the Device, and error strings
1746 ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *pDevice,ALCenum param)
1748 const ALCchar *value = NULL;
1750 switch(param)
1752 case ALC_NO_ERROR:
1753 value = alcNoError;
1754 break;
1756 case ALC_INVALID_ENUM:
1757 value = alcErrInvalidEnum;
1758 break;
1760 case ALC_INVALID_VALUE:
1761 value = alcErrInvalidValue;
1762 break;
1764 case ALC_INVALID_DEVICE:
1765 value = alcErrInvalidDevice;
1766 break;
1768 case ALC_INVALID_CONTEXT:
1769 value = alcErrInvalidContext;
1770 break;
1772 case ALC_OUT_OF_MEMORY:
1773 value = alcErrOutOfMemory;
1774 break;
1776 case ALC_DEVICE_SPECIFIER:
1777 if(VerifyDevice(pDevice))
1779 value = pDevice->szDeviceName;
1780 ALCdevice_DecRef(pDevice);
1782 else
1784 ProbeDeviceList();
1785 value = alcDeviceList;
1787 break;
1789 case ALC_ALL_DEVICES_SPECIFIER:
1790 ProbeAllDeviceList();
1791 value = alcAllDeviceList;
1792 break;
1794 case ALC_CAPTURE_DEVICE_SPECIFIER:
1795 if(VerifyDevice(pDevice))
1797 value = pDevice->szDeviceName;
1798 ALCdevice_DecRef(pDevice);
1800 else
1802 ProbeCaptureDeviceList();
1803 value = alcCaptureDeviceList;
1805 break;
1807 /* Default devices are always first in the list */
1808 case ALC_DEFAULT_DEVICE_SPECIFIER:
1809 if(!alcDeviceList)
1810 ProbeDeviceList();
1812 pDevice = VerifyDevice(pDevice);
1814 free(alcDefaultDeviceSpecifier);
1815 alcDefaultDeviceSpecifier = strdup(alcDeviceList ? alcDeviceList : "");
1816 if(!alcDefaultDeviceSpecifier)
1817 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1819 value = alcDefaultDeviceSpecifier;
1820 if(pDevice) ALCdevice_DecRef(pDevice);
1821 break;
1823 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
1824 if(!alcAllDeviceList)
1825 ProbeAllDeviceList();
1827 pDevice = VerifyDevice(pDevice);
1829 free(alcDefaultAllDeviceSpecifier);
1830 alcDefaultAllDeviceSpecifier = strdup(alcAllDeviceList ?
1831 alcAllDeviceList : "");
1832 if(!alcDefaultAllDeviceSpecifier)
1833 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1835 value = alcDefaultAllDeviceSpecifier;
1836 if(pDevice) ALCdevice_DecRef(pDevice);
1837 break;
1839 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
1840 if(!alcCaptureDeviceList)
1841 ProbeCaptureDeviceList();
1843 pDevice = VerifyDevice(pDevice);
1845 free(alcCaptureDefaultDeviceSpecifier);
1846 alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ?
1847 alcCaptureDeviceList : "");
1848 if(!alcCaptureDefaultDeviceSpecifier)
1849 alcSetError(pDevice, ALC_OUT_OF_MEMORY);
1851 value = alcCaptureDefaultDeviceSpecifier;
1852 if(pDevice) ALCdevice_DecRef(pDevice);
1853 break;
1855 case ALC_EXTENSIONS:
1856 if(!VerifyDevice(pDevice))
1857 value = alcNoDeviceExtList;
1858 else
1860 value = alcExtensionList;
1861 ALCdevice_DecRef(pDevice);
1863 break;
1865 default:
1866 pDevice = VerifyDevice(pDevice);
1867 alcSetError(pDevice, ALC_INVALID_ENUM);
1868 if(pDevice) ALCdevice_DecRef(pDevice);
1869 break;
1872 return value;
1876 /* alcGetIntegerv
1878 * Returns information about the Device and the version of Open AL
1880 ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data)
1882 device = VerifyDevice(device);
1884 if(size == 0 || data == NULL)
1886 alcSetError(device, ALC_INVALID_VALUE);
1887 if(device) ALCdevice_DecRef(device);
1888 return;
1891 if(!device)
1893 switch(param)
1895 case ALC_MAJOR_VERSION:
1896 *data = alcMajorVersion;
1897 break;
1898 case ALC_MINOR_VERSION:
1899 *data = alcMinorVersion;
1900 break;
1902 case ALC_ATTRIBUTES_SIZE:
1903 case ALC_ALL_ATTRIBUTES:
1904 case ALC_FREQUENCY:
1905 case ALC_REFRESH:
1906 case ALC_SYNC:
1907 case ALC_MONO_SOURCES:
1908 case ALC_STEREO_SOURCES:
1909 case ALC_CAPTURE_SAMPLES:
1910 case ALC_FORMAT_CHANNELS_SOFT:
1911 case ALC_FORMAT_TYPE_SOFT:
1912 alcSetError(NULL, ALC_INVALID_DEVICE);
1913 break;
1915 default:
1916 alcSetError(NULL, ALC_INVALID_ENUM);
1917 break;
1920 else if(device->IsCaptureDevice)
1922 switch(param)
1924 case ALC_CAPTURE_SAMPLES:
1925 LockDevice(device);
1926 *data = ALCdevice_AvailableSamples(device);
1927 UnlockDevice(device);
1928 break;
1930 case ALC_CONNECTED:
1931 *data = device->Connected;
1932 break;
1934 default:
1935 alcSetError(device, ALC_INVALID_ENUM);
1936 break;
1939 else /* render device */
1941 switch(param)
1943 case ALC_MAJOR_VERSION:
1944 *data = alcMajorVersion;
1945 break;
1947 case ALC_MINOR_VERSION:
1948 *data = alcMinorVersion;
1949 break;
1951 case ALC_EFX_MAJOR_VERSION:
1952 *data = alcEFXMajorVersion;
1953 break;
1955 case ALC_EFX_MINOR_VERSION:
1956 *data = alcEFXMinorVersion;
1957 break;
1959 case ALC_ATTRIBUTES_SIZE:
1960 *data = 13;
1961 break;
1963 case ALC_ALL_ATTRIBUTES:
1964 if(size < 13)
1965 alcSetError(device, ALC_INVALID_VALUE);
1966 else
1968 int i = 0;
1970 data[i++] = ALC_FREQUENCY;
1971 data[i++] = device->Frequency;
1973 if(!device->IsLoopbackDevice)
1975 data[i++] = ALC_REFRESH;
1976 data[i++] = device->Frequency / device->UpdateSize;
1978 data[i++] = ALC_SYNC;
1979 data[i++] = ALC_FALSE;
1981 else
1983 data[i++] = ALC_FORMAT_CHANNELS_SOFT;
1984 data[i++] = device->FmtChans;
1986 data[i++] = ALC_FORMAT_TYPE_SOFT;
1987 data[i++] = device->FmtType;
1990 data[i++] = ALC_MONO_SOURCES;
1991 data[i++] = device->NumMonoSources;
1993 data[i++] = ALC_STEREO_SOURCES;
1994 data[i++] = device->NumStereoSources;
1996 data[i++] = ALC_MAX_AUXILIARY_SENDS;
1997 data[i++] = device->NumAuxSends;
1999 data[i++] = 0;
2001 break;
2003 case ALC_FREQUENCY:
2004 *data = device->Frequency;
2005 break;
2007 case ALC_REFRESH:
2008 if(device->IsLoopbackDevice)
2009 alcSetError(device, ALC_INVALID_DEVICE);
2010 else
2011 *data = device->Frequency / device->UpdateSize;
2012 break;
2014 case ALC_SYNC:
2015 if(device->IsLoopbackDevice)
2016 alcSetError(device, ALC_INVALID_DEVICE);
2017 else
2018 *data = ALC_FALSE;
2019 break;
2021 case ALC_FORMAT_CHANNELS_SOFT:
2022 if(!device->IsLoopbackDevice)
2023 alcSetError(device, ALC_INVALID_DEVICE);
2024 else
2025 *data = device->FmtChans;
2026 break;
2028 case ALC_FORMAT_TYPE_SOFT:
2029 if(!device->IsLoopbackDevice)
2030 alcSetError(device, ALC_INVALID_DEVICE);
2031 else
2032 *data = device->FmtType;
2033 break;
2035 case ALC_MONO_SOURCES:
2036 *data = device->NumMonoSources;
2037 break;
2039 case ALC_STEREO_SOURCES:
2040 *data = device->NumStereoSources;
2041 break;
2043 case ALC_MAX_AUXILIARY_SENDS:
2044 *data = device->NumAuxSends;
2045 break;
2047 case ALC_CONNECTED:
2048 *data = device->Connected;
2049 break;
2051 default:
2052 alcSetError(device, ALC_INVALID_ENUM);
2053 break;
2056 if(device)
2057 ALCdevice_DecRef(device);
2061 /* alcIsExtensionPresent
2063 * Determines if there is support for a particular extension
2065 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
2067 ALCboolean bResult = ALC_FALSE;
2069 device = VerifyDevice(device);
2071 if(!extName)
2072 alcSetError(device, ALC_INVALID_VALUE);
2073 else
2075 size_t len = strlen(extName);
2076 const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList);
2077 while(ptr && *ptr)
2079 if(strncasecmp(ptr, extName, len) == 0 &&
2080 (ptr[len] == '\0' || isspace(ptr[len])))
2082 bResult = ALC_TRUE;
2083 break;
2085 if((ptr=strchr(ptr, ' ')) != NULL)
2087 do {
2088 ++ptr;
2089 } while(isspace(*ptr));
2093 if(device)
2094 ALCdevice_DecRef(device);
2095 return bResult;
2099 /* alcGetProcAddress
2101 * Retrieves the function address for a particular extension function
2103 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
2105 ALCvoid *ptr = NULL;
2107 device = VerifyDevice(device);
2109 if(!funcName)
2110 alcSetError(device, ALC_INVALID_VALUE);
2111 else
2113 ALsizei i = 0;
2114 while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName,funcName) != 0)
2115 i++;
2116 ptr = alcFunctions[i].address;
2118 if(device)
2119 ALCdevice_DecRef(device);
2120 return ptr;
2124 /* alcGetEnumValue
2126 * Get the value for a particular ALC Enumerated Value
2128 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
2130 ALCenum val = 0;
2132 device = VerifyDevice(device);
2134 if(!enumName)
2135 alcSetError(device, ALC_INVALID_VALUE);
2136 else
2138 ALsizei i = 0;
2139 while(enumeration[i].enumName && strcmp(enumeration[i].enumName,enumName) != 0)
2140 i++;
2141 val = enumeration[i].value;
2143 if(device)
2144 ALCdevice_DecRef(device);
2145 return val;
2149 /* alcCreateContext
2151 * Create and attach a Context to a particular Device.
2153 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
2155 ALCcontext *ALContext;
2157 LockLists();
2158 if(!(device=VerifyDevice(device)) || device->IsCaptureDevice || !device->Connected)
2160 UnlockLists();
2161 alcSetError(device, ALC_INVALID_DEVICE);
2162 if(device) ALCdevice_DecRef(device);
2163 return NULL;
2166 /* Reset Context Last Error code */
2167 device->LastError = ALC_NO_ERROR;
2169 if(UpdateDeviceParams(device, attrList) == ALC_FALSE)
2171 UnlockLists();
2172 alcSetError(device, ALC_INVALID_DEVICE);
2173 aluHandleDisconnect(device);
2174 ALCdevice_DecRef(device);
2175 return NULL;
2178 ALContext = calloc(1, sizeof(ALCcontext));
2179 if(ALContext)
2181 ALContext->ref = 1;
2183 ALContext->MaxActiveSources = 256;
2184 ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) *
2185 ALContext->MaxActiveSources);
2187 if(!ALContext || !ALContext->ActiveSources)
2189 if(!device->ContextList)
2191 ALCdevice_StopPlayback(device);
2192 device->Flags &= ~DEVICE_RUNNING;
2194 UnlockLists();
2196 free(ALContext);
2197 ALContext = NULL;
2199 alcSetError(device, ALC_OUT_OF_MEMORY);
2200 ALCdevice_DecRef(device);
2201 return NULL;
2204 ALContext->Device = device;
2205 ALCdevice_IncRef(device);
2206 InitContext(ALContext);
2208 do {
2209 ALContext->next = device->ContextList;
2210 } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext));
2211 UnlockLists();
2213 ALCdevice_DecRef(device);
2215 TRACE("Created context %p\n", ALContext);
2216 return ALContext;
2219 /* alcDestroyContext
2221 * Remove a Context
2223 ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
2225 ALCdevice *Device;
2227 LockLists();
2228 /* alcGetContextsDevice sets an error for invalid contexts */
2229 Device = alcGetContextsDevice(context);
2230 if(Device)
2232 ReleaseContext(context, Device);
2233 if(!Device->ContextList)
2235 ALCdevice_StopPlayback(Device);
2236 Device->Flags &= ~DEVICE_RUNNING;
2239 UnlockLists();
2243 /* alcGetCurrentContext
2245 * Returns the currently active Context
2247 ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(ALCvoid)
2249 ALCcontext *Context;
2251 Context = pthread_getspecific(LocalContext);
2252 if(!Context) Context = GlobalContext;
2254 return Context;
2257 /* alcGetThreadContext
2259 * Returns the currently active thread-local Context
2261 ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
2263 ALCcontext *Context;
2264 Context = pthread_getspecific(LocalContext);
2265 return Context;
2269 /* alcMakeContextCurrent
2271 * Makes the given Context the active Context
2273 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
2275 /* context must be a valid Context or NULL */
2276 if(context && !(context=VerifyContext(context)))
2278 alcSetError(NULL, ALC_INVALID_CONTEXT);
2279 return ALC_FALSE;
2281 /* context's reference count is already incremented */
2282 context = ExchangePtr((XchgPtr*)&GlobalContext, context);
2283 if(context) ALCcontext_DecRef(context);
2285 if((context=pthread_getspecific(LocalContext)) != NULL)
2287 pthread_setspecific(LocalContext, NULL);
2288 ALCcontext_DecRef(context);
2291 return ALC_TRUE;
2294 /* alcSetThreadContext
2296 * Makes the given Context the active Context for the current thread
2298 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
2300 ALCcontext *old;
2302 /* context must be a valid Context or NULL */
2303 if(context && !(context=VerifyContext(context)))
2305 alcSetError(NULL, ALC_INVALID_CONTEXT);
2306 return ALC_FALSE;
2308 /* context's reference count is already incremented */
2309 old = pthread_getspecific(LocalContext);
2310 pthread_setspecific(LocalContext, context);
2311 if(old) ALCcontext_DecRef(old);
2313 return ALC_TRUE;
2317 /* alcGetContextsDevice
2319 * Returns the Device that a particular Context is attached to
2321 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
2323 ALCdevice *Device;
2325 if(!(Context=VerifyContext(Context)))
2327 alcSetError(NULL, ALC_INVALID_CONTEXT);
2328 return NULL;
2330 Device = Context->Device;
2331 ALCcontext_DecRef(Context);
2333 return Device;
2337 static void GetFormatFromString(const char *str, enum DevFmtChannels *chans, enum DevFmtType *type)
2339 static const struct {
2340 const char name[32];
2341 enum DevFmtChannels channels;
2342 enum DevFmtType type;
2343 } formats[] = {
2344 { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat },
2345 { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat },
2346 { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat },
2347 { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat },
2348 { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat },
2349 { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat },
2351 { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort },
2352 { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort },
2353 { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort },
2354 { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort },
2355 { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort },
2356 { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort },
2358 { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte },
2359 { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte },
2360 { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte },
2361 { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte },
2362 { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte },
2363 { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte }
2365 size_t i;
2367 for(i = 0;i < sizeof(formats)/sizeof(formats[0]);i++)
2369 if(strcasecmp(str, formats[i].name) == 0)
2371 *chans = formats[i].channels;
2372 *type = formats[i].type;
2373 return;
2377 ERR("Unknown format: \"%s\"\n", str);
2378 *chans = DevFmtStereo;
2379 *type = DevFmtShort;
2382 /* alcOpenDevice
2384 * Open the Device specified.
2386 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
2388 const ALCchar *fmt;
2389 ALCdevice *device;
2390 ALCenum err;
2392 DO_INITCONFIG();
2394 if(!PlaybackBackend.name)
2396 alcSetError(NULL, ALC_INVALID_VALUE);
2397 return NULL;
2400 if(deviceName && (!deviceName[0] || strcasecmp(deviceName, "openal soft") == 0 || strcasecmp(deviceName, "openal-soft") == 0))
2401 deviceName = NULL;
2403 device = calloc(1, sizeof(ALCdevice));
2404 if(!device)
2406 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2407 return NULL;
2410 //Validate device
2411 device->Funcs = &PlaybackBackend.Funcs;
2412 device->ref = 1;
2413 device->Connected = ALC_TRUE;
2414 device->IsCaptureDevice = AL_FALSE;
2415 device->IsLoopbackDevice = AL_FALSE;
2416 InitializeCriticalSection(&device->Mutex);
2417 device->LastError = ALC_NO_ERROR;
2419 device->Flags = 0;
2420 device->Bs2b = NULL;
2421 device->Bs2bLevel = 0;
2422 device->szDeviceName = NULL;
2424 device->ContextList = NULL;
2426 device->MaxNoOfSources = 256;
2427 device->AuxiliaryEffectSlotMax = 4;
2428 device->NumAuxSends = MAX_SENDS;
2430 InitUIntMap(&device->BufferMap, ~0);
2431 InitUIntMap(&device->EffectMap, ~0);
2432 InitUIntMap(&device->FilterMap, ~0);
2434 //Set output format
2435 device->NumUpdates = 4;
2436 device->UpdateSize = 1024;
2438 device->Frequency = DEFAULT_OUTPUT_RATE;
2439 if(ConfigValueUInt(NULL, "frequency", &device->Frequency))
2440 device->Flags |= DEVICE_FREQUENCY_REQUEST;
2441 device->Frequency = maxu(device->Frequency, 8000);
2443 fmt = "AL_FORMAT_STEREO32";
2444 if(ConfigValueStr(NULL, "format", &fmt))
2445 device->Flags |= DEVICE_CHANNELS_REQUEST;
2446 GetFormatFromString(fmt, &device->FmtChans, &device->FmtType);
2448 ConfigValueUInt(NULL, "periods", &device->NumUpdates);
2449 if(device->NumUpdates < 2) device->NumUpdates = 4;
2451 ConfigValueUInt(NULL, "period_size", &device->UpdateSize);
2452 if(device->UpdateSize == 0) device->UpdateSize = 1024;
2454 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2455 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2457 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2458 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2460 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2461 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2463 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2465 device->NumStereoSources = 1;
2466 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2468 // Find a playback device to open
2469 LockLists();
2470 if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR)
2472 UnlockLists();
2473 DeleteCriticalSection(&device->Mutex);
2474 free(device);
2475 alcSetError(NULL, err);
2476 return NULL;
2478 UnlockLists();
2480 do {
2481 device->next = DeviceList;
2482 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2484 TRACE("Created device %p\n", device);
2485 return device;
2488 /* alcCloseDevice
2490 * Close the specified Device
2492 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *pDevice)
2494 ALCdevice *volatile*list;
2495 ALCcontext *ctx;
2497 LockLists();
2498 list = &DeviceList;
2499 while(*list && *list != pDevice)
2500 list = &(*list)->next;
2502 if(!*list || (*list)->IsCaptureDevice)
2504 alcSetError(*list, ALC_INVALID_DEVICE);
2505 UnlockLists();
2506 return ALC_FALSE;
2509 *list = (*list)->next;
2510 UnlockLists();
2512 if((ctx=pDevice->ContextList) != NULL)
2514 do {
2515 WARN("Releasing context %p\n", ctx);
2516 ReleaseContext(ctx, pDevice);
2517 } while((ctx=pDevice->ContextList) != NULL);
2518 ALCdevice_StopPlayback(pDevice);
2519 pDevice->Flags &= ~DEVICE_RUNNING;
2521 ALCdevice_ClosePlayback(pDevice);
2523 ALCdevice_DecRef(pDevice);
2525 return ALC_TRUE;
2529 /* alcLoopbackOpenDeviceSOFT
2531 * Open a loopback device, for manual rendering.
2533 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(void)
2535 ALCdevice *device;
2537 DO_INITCONFIG();
2539 device = calloc(1, sizeof(ALCdevice));
2540 if(!device)
2542 alcSetError(NULL, ALC_OUT_OF_MEMORY);
2543 return NULL;
2546 //Validate device
2547 device->Funcs = &BackendLoopback.Funcs;
2548 device->ref = 1;
2549 device->Connected = ALC_TRUE;
2550 device->IsCaptureDevice = AL_FALSE;
2551 device->IsLoopbackDevice = AL_TRUE;
2552 InitializeCriticalSection(&device->Mutex);
2553 device->LastError = ALC_NO_ERROR;
2555 device->Flags = 0;
2556 device->Bs2b = NULL;
2557 device->Bs2bLevel = 0;
2558 device->szDeviceName = NULL;
2560 device->ContextList = NULL;
2562 device->MaxNoOfSources = 256;
2563 device->AuxiliaryEffectSlotMax = 4;
2564 device->NumAuxSends = MAX_SENDS;
2566 InitUIntMap(&device->BufferMap, ~0);
2567 InitUIntMap(&device->EffectMap, ~0);
2568 InitUIntMap(&device->FilterMap, ~0);
2570 //Set output format
2571 device->NumUpdates = 0;
2572 device->UpdateSize = 0;
2574 device->Frequency = 44100;
2575 device->FmtChans = DevFmtStereo;
2576 device->FmtType = DevFmtShort;
2578 ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources);
2579 if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256;
2581 ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax);
2582 if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4;
2584 ConfigValueUInt(NULL, "sends", &device->NumAuxSends);
2585 if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS;
2587 ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel);
2589 device->NumStereoSources = 1;
2590 device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources;
2592 // Open the "backend"
2593 ALCdevice_OpenPlayback(device, "Loopback");
2594 do {
2595 device->next = DeviceList;
2596 } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device));
2598 TRACE("Created device %p\n", device);
2599 return device;
2602 /* alcIsRenderFormatSupportedSOFT
2604 * Determines if the loopback device supports the given format for rendering.
2606 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
2608 ALCboolean ret = ALC_FALSE;
2610 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2611 alcSetError(device, ALC_INVALID_DEVICE);
2612 else if(freq <= 0)
2613 alcSetError(device, ALC_INVALID_VALUE);
2614 else if(!IsValidALCType(type) || !IsValidALCChannels(channels))
2615 alcSetError(device, ALC_INVALID_ENUM);
2616 else
2618 if(BytesFromDevFmt(type) > 0 && ChannelsFromDevFmt(channels) > 0 &&
2619 freq >= 8000)
2620 ret = ALC_TRUE;
2622 if(device) ALCdevice_DecRef(device);
2624 return ret;
2627 /* alcRenderSamplesSOFT
2629 * Renders some samples into a buffer, using the format last set by the
2630 * attributes given to alcCreateContext.
2632 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
2634 if(!(device=VerifyDevice(device)) || !device->IsLoopbackDevice)
2635 alcSetError(device, ALC_INVALID_DEVICE);
2636 else if(samples < 0 || (samples > 0 && buffer == NULL))
2637 alcSetError(device, ALC_INVALID_VALUE);
2638 else
2639 aluMixData(device, buffer, samples);
2640 if(device) ALCdevice_DecRef(device);
2644 static void ReleaseALC(void)
2646 ALCdevice *dev;
2648 free(alcDeviceList); alcDeviceList = NULL;
2649 alcDeviceListSize = 0;
2650 free(alcAllDeviceList); alcAllDeviceList = NULL;
2651 alcAllDeviceListSize = 0;
2652 free(alcCaptureDeviceList); alcCaptureDeviceList = NULL;
2653 alcCaptureDeviceListSize = 0;
2655 free(alcDefaultDeviceSpecifier);
2656 alcDefaultDeviceSpecifier = NULL;
2657 free(alcDefaultAllDeviceSpecifier);
2658 alcDefaultAllDeviceSpecifier = NULL;
2659 free(alcCaptureDefaultDeviceSpecifier);
2660 alcCaptureDefaultDeviceSpecifier = NULL;
2662 if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL)
2664 ALCuint num = 0;
2665 do {
2666 num++;
2667 } while((dev=dev->next) != NULL);
2668 ERR("%u device%s not closed\n", num, (num>1)?"s":"");
2672 ///////////////////////////////////////////////////////