Prepare the new driver in a local variable
[openal-soft.git] / OpenAL32 / Include / alMain.h
blobbe80020bd0b16c6564f2053dfd28e2eb1939a13f
1 #ifndef AL_MAIN_H
2 #define AL_MAIN_H
4 #include <string.h>
5 #include <stdio.h>
6 #include <stddef.h>
7 #include <stdarg.h>
8 #include <assert.h>
9 #include <math.h>
10 #include <limits.h>
12 #ifdef HAVE_STRINGS_H
13 #include <strings.h>
14 #endif
16 #ifdef HAVE_FENV_H
17 #include <fenv.h>
18 #endif
20 #include "AL/al.h"
21 #include "AL/alc.h"
22 #include "AL/alext.h"
24 #include "static_assert.h"
25 #include "align.h"
26 #include "atomic.h"
27 #include "uintmap.h"
28 #include "vector.h"
29 #include "alstring.h"
30 #include "almalloc.h"
31 #include "threads.h"
33 #ifndef ALC_SOFT_loopback2
34 #define ALC_SOFT_loopback2 1
35 #define ALC_AMBISONIC_LAYOUT_SOFT 0x1997
36 #define ALC_AMBISONIC_SCALING_SOFT 0x1998
37 #define ALC_AMBISONIC_ORDER_SOFT 0x1999
39 #define ALC_BFORMAT3D_SOFT 0x1508
41 /* Ambisonic layouts */
42 #define ALC_ACN_SOFT 0x1600
43 #define ALC_FUMA_SOFT 0x1601
45 /* Ambisonic scalings (normalization) */
46 /*#define ALC_FUMA_SOFT*/
47 #define ALC_SN3D_SOFT 0x1602
48 #define ALC_N3D_SOFT 0x1603
50 typedef ALCboolean (ALC_APIENTRY*LPALCISAMBISONICFORMATSUPPORTEDSOFT)(ALCdevice *device, ALCenum layout, ALCenum scaling, ALsizei order);
51 #ifdef AL_ALEXT_PROTOTYPES
52 ALC_API ALCboolean ALC_APIENTRY alcIsAmbisonicFormatSupportedSOFT(ALCdevice *device, ALCenum layout, ALCenum scaling, ALsizei order);
53 #endif
54 #endif
56 #ifndef ALC_SOFT_device_clock
57 #define ALC_SOFT_device_clock 1
58 typedef int64_t ALCint64SOFT;
59 typedef uint64_t ALCuint64SOFT;
60 #define ALC_DEVICE_CLOCK_SOFT 0x1600
61 #define ALC_DEVICE_LATENCY_SOFT 0x1601
62 #define ALC_DEVICE_CLOCK_LATENCY_SOFT 0x1602
63 typedef void (ALC_APIENTRY*LPALCGETINTEGER64VSOFT)(ALCdevice *device, ALCenum pname, ALsizei size, ALCint64SOFT *values);
64 #ifdef AL_ALEXT_PROTOTYPES
65 ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALsizei size, ALCint64SOFT *values);
66 #endif
67 #endif
69 #ifndef AL_SOFT_buffer_samples2
70 #define AL_SOFT_buffer_samples2 1
71 /* Channel configurations */
72 #define AL_MONO_SOFT 0x1500
73 #define AL_STEREO_SOFT 0x1501
74 #define AL_REAR_SOFT 0x1502
75 #define AL_QUAD_SOFT 0x1503
76 #define AL_5POINT1_SOFT 0x1504
77 #define AL_6POINT1_SOFT 0x1505
78 #define AL_7POINT1_SOFT 0x1506
79 #define AL_BFORMAT2D_SOFT 0x1507
80 #define AL_BFORMAT3D_SOFT 0x1508
82 /* Sample types */
83 #define AL_BYTE_SOFT 0x1400
84 #define AL_UNSIGNED_BYTE_SOFT 0x1401
85 #define AL_SHORT_SOFT 0x1402
86 #define AL_UNSIGNED_SHORT_SOFT 0x1403
87 #define AL_INT_SOFT 0x1404
88 #define AL_UNSIGNED_INT_SOFT 0x1405
89 #define AL_FLOAT_SOFT 0x1406
90 #define AL_DOUBLE_SOFT 0x1407
91 #define AL_BYTE3_SOFT 0x1408
92 #define AL_UNSIGNED_BYTE3_SOFT 0x1409
93 #define AL_MULAW_SOFT 0x140A
95 /* Storage formats */
96 #define AL_MONO8_SOFT 0x1100
97 #define AL_MONO16_SOFT 0x1101
98 #define AL_MONO32F_SOFT 0x10010
99 #define AL_STEREO8_SOFT 0x1102
100 #define AL_STEREO16_SOFT 0x1103
101 #define AL_STEREO32F_SOFT 0x10011
102 #define AL_QUAD8_SOFT 0x1204
103 #define AL_QUAD16_SOFT 0x1205
104 #define AL_QUAD32F_SOFT 0x1206
105 #define AL_REAR8_SOFT 0x1207
106 #define AL_REAR16_SOFT 0x1208
107 #define AL_REAR32F_SOFT 0x1209
108 #define AL_5POINT1_8_SOFT 0x120A
109 #define AL_5POINT1_16_SOFT 0x120B
110 #define AL_5POINT1_32F_SOFT 0x120C
111 #define AL_6POINT1_8_SOFT 0x120D
112 #define AL_6POINT1_16_SOFT 0x120E
113 #define AL_6POINT1_32F_SOFT 0x120F
114 #define AL_7POINT1_8_SOFT 0x1210
115 #define AL_7POINT1_16_SOFT 0x1211
116 #define AL_7POINT1_32F_SOFT 0x1212
117 #define AL_BFORMAT2D_8_SOFT 0x20021
118 #define AL_BFORMAT2D_16_SOFT 0x20022
119 #define AL_BFORMAT2D_32F_SOFT 0x20023
120 #define AL_BFORMAT3D_8_SOFT 0x20031
121 #define AL_BFORMAT3D_16_SOFT 0x20032
122 #define AL_BFORMAT3D_32F_SOFT 0x20033
124 /* Buffer attributes */
125 #define AL_INTERNAL_FORMAT_SOFT 0x2008
126 #define AL_BYTE_LENGTH_SOFT 0x2009
127 #define AL_SAMPLE_LENGTH_SOFT 0x200A
128 #define AL_SEC_LENGTH_SOFT 0x200B
130 #if 0
131 typedef void (AL_APIENTRY*LPALBUFFERSAMPLESSOFT)(ALuint,ALuint,ALenum,ALsizei,ALenum,ALenum,const ALvoid*);
132 typedef void (AL_APIENTRY*LPALGETBUFFERSAMPLESSOFT)(ALuint,ALsizei,ALsizei,ALenum,ALenum,ALvoid*);
133 typedef ALboolean (AL_APIENTRY*LPALISBUFFERFORMATSUPPORTEDSOFT)(ALenum);
134 #ifdef AL_ALEXT_PROTOTYPES
135 AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint buffer, ALuint samplerate, ALenum internalformat, ALsizei samples, ALenum channels, ALenum type, const ALvoid *data);
136 AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint buffer, ALsizei offset, ALsizei samples, ALenum channels, ALenum type, ALvoid *data);
137 AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum format);
138 #endif
139 #endif
140 #endif
143 #if defined(_WIN64)
144 #define SZFMT "%I64u"
145 #elif defined(_WIN32)
146 #define SZFMT "%u"
147 #else
148 #define SZFMT "%zu"
149 #endif
152 #ifdef __GNUC__
153 /* Because of a long-standing deficiency in C, you're not allowed to implicitly
154 * cast a pointer-to-type-array to a pointer-to-const-type-array. For example,
156 * int (*ptr)[10];
157 * const int (*cptr)[10] = ptr;
159 * is not allowed and most compilers will generate noisy warnings about
160 * incompatible types, even though it just makes the array elements const.
161 * Clang will allow it if you make the array type a typedef, like this:
163 * typedef int int10[10];
164 * int10 *ptr;
165 * const int10 *cptr = ptr;
167 * however GCC does not and still issues the incompatible type warning. The
168 * "proper" way to fix it is to add an explicit cast for the constified type,
169 * but that removes the vast majority of otherwise useful type-checking you'd
170 * get, and runs the risk of improper casts if types are later changed. Leaving
171 * it non-const can also be an issue if you use it as a function parameter, and
172 * happen to have a const type as input (and also reduce the capabilities of
173 * the compiler to better optimize the function).
175 * So to work around the problem, we use a macro. The macro first assigns the
176 * incoming variable to the specified non-const type to ensure it's the correct
177 * type, then casts the variable as the desired constified type. Very ugly, but
178 * I'd rather not have hundreds of lines of warnings because I want to tell the
179 * compiler that some array(s) can't be changed by the code, or have lots of
180 * error-prone casts.
182 #define SAFE_CONST(T, var) __extension__({ \
183 T _tmp = (var); \
184 (const T)_tmp; \
186 #else
187 /* Non-GNU-compatible compilers have to use a straight cast with no extra
188 * checks, due to the lack of multi-statement expressions.
190 #define SAFE_CONST(T, var) ((const T)(var))
191 #endif
194 #ifdef __GNUC__
195 /* This helps cast away the const-ness of a pointer without accidentally
196 * changing the pointer type. This is necessary due to Clang's inability to use
197 * atomic_load on a const _Atomic variable.
199 #define CONST_CAST(T, V) __extension__({ \
200 const T _tmp = (V); \
201 (T)_tmp; \
203 #else
204 #define CONST_CAST(T, V) ((T)(V))
205 #endif
208 typedef ALint64SOFT ALint64;
209 typedef ALuint64SOFT ALuint64;
211 #ifndef U64
212 #if defined(_MSC_VER)
213 #define U64(x) ((ALuint64)(x##ui64))
214 #elif SIZEOF_LONG == 8
215 #define U64(x) ((ALuint64)(x##ul))
216 #elif SIZEOF_LONG_LONG == 8
217 #define U64(x) ((ALuint64)(x##ull))
218 #endif
219 #endif
221 #ifndef UINT64_MAX
222 #define UINT64_MAX U64(18446744073709551615)
223 #endif
225 #ifndef UNUSED
226 #if defined(__cplusplus)
227 #define UNUSED(x)
228 #elif defined(__GNUC__)
229 #define UNUSED(x) UNUSED_##x __attribute__((unused))
230 #elif defined(__LCLINT__)
231 #define UNUSED(x) /*@unused@*/ x
232 #else
233 #define UNUSED(x) x
234 #endif
235 #endif
237 #ifdef __GNUC__
238 #define DECL_FORMAT(x, y, z) __attribute__((format(x, (y), (z))))
239 #else
240 #define DECL_FORMAT(x, y, z)
241 #endif
243 /* Calculates the size of a struct with N elements of a flexible array member.
244 * GCC and Clang allow offsetof(Type, fam[N]) for this, but MSVC seems to have
245 * trouble, so a bit more verbose workaround is needed.
247 #define FAM_SIZE(T, M, N) (offsetof(T, M) + sizeof(((T*)NULL)->M[0])*(N))
249 #if defined(__GNUC__) && defined(__i386__)
250 /* force_align_arg_pointer is required for proper function arguments aligning
251 * when SSE code is used. Some systems (Windows, QNX) do not guarantee our
252 * thread functions will be properly aligned on the stack, even though GCC may
253 * generate code with the assumption that it is. */
254 #define FORCE_ALIGN __attribute__((force_align_arg_pointer))
255 #else
256 #define FORCE_ALIGN
257 #endif
259 #ifdef HAVE_C99_VLA
260 #define DECL_VLA(T, _name, _size) T _name[(_size)]
261 #else
262 #define DECL_VLA(T, _name, _size) T *_name = alloca((_size) * sizeof(T))
263 #endif
265 #ifndef PATH_MAX
266 #ifdef MAX_PATH
267 #define PATH_MAX MAX_PATH
268 #else
269 #define PATH_MAX 4096
270 #endif
271 #endif
274 static const union {
275 ALuint u;
276 ALubyte b[sizeof(ALuint)];
277 } EndianTest = { 1 };
278 #define IS_LITTLE_ENDIAN (EndianTest.b[0] == 1)
280 #define COUNTOF(x) (sizeof(x) / sizeof(0[x]))
283 #define DERIVE_FROM_TYPE(t) t t##_parent
284 #define STATIC_CAST(to, obj) (&(obj)->to##_parent)
285 #ifdef __GNUC__
286 #define STATIC_UPCAST(to, from, obj) __extension__({ \
287 static_assert(__builtin_types_compatible_p(from, __typeof(*(obj))), \
288 "Invalid upcast object from type"); \
289 (to*)((char*)(obj) - offsetof(to, from##_parent)); \
291 #else
292 #define STATIC_UPCAST(to, from, obj) ((to*)((char*)(obj) - offsetof(to, from##_parent)))
293 #endif
295 #define DECLARE_FORWARD(T1, T2, rettype, func) \
296 rettype T1##_##func(T1 *obj) \
297 { return T2##_##func(STATIC_CAST(T2, obj)); }
299 #define DECLARE_FORWARD1(T1, T2, rettype, func, argtype1) \
300 rettype T1##_##func(T1 *obj, argtype1 a) \
301 { return T2##_##func(STATIC_CAST(T2, obj), a); }
303 #define DECLARE_FORWARD2(T1, T2, rettype, func, argtype1, argtype2) \
304 rettype T1##_##func(T1 *obj, argtype1 a, argtype2 b) \
305 { return T2##_##func(STATIC_CAST(T2, obj), a, b); }
307 #define DECLARE_FORWARD3(T1, T2, rettype, func, argtype1, argtype2, argtype3) \
308 rettype T1##_##func(T1 *obj, argtype1 a, argtype2 b, argtype3 c) \
309 { return T2##_##func(STATIC_CAST(T2, obj), a, b, c); }
312 #define GET_VTABLE1(T1) (&(T1##_vtable))
313 #define GET_VTABLE2(T1, T2) (&(T1##_##T2##_vtable))
315 #define SET_VTABLE1(T1, obj) ((obj)->vtbl = GET_VTABLE1(T1))
316 #define SET_VTABLE2(T1, T2, obj) (STATIC_CAST(T2, obj)->vtbl = GET_VTABLE2(T1, T2))
318 #define DECLARE_THUNK(T1, T2, rettype, func) \
319 static rettype T1##_##T2##_##func(T2 *obj) \
320 { return T1##_##func(STATIC_UPCAST(T1, T2, obj)); }
322 #define DECLARE_THUNK1(T1, T2, rettype, func, argtype1) \
323 static rettype T1##_##T2##_##func(T2 *obj, argtype1 a) \
324 { return T1##_##func(STATIC_UPCAST(T1, T2, obj), a); }
326 #define DECLARE_THUNK2(T1, T2, rettype, func, argtype1, argtype2) \
327 static rettype T1##_##T2##_##func(T2 *obj, argtype1 a, argtype2 b) \
328 { return T1##_##func(STATIC_UPCAST(T1, T2, obj), a, b); }
330 #define DECLARE_THUNK3(T1, T2, rettype, func, argtype1, argtype2, argtype3) \
331 static rettype T1##_##T2##_##func(T2 *obj, argtype1 a, argtype2 b, argtype3 c) \
332 { return T1##_##func(STATIC_UPCAST(T1, T2, obj), a, b, c); }
334 #define DECLARE_THUNK4(T1, T2, rettype, func, argtype1, argtype2, argtype3, argtype4) \
335 static rettype T1##_##T2##_##func(T2 *obj, argtype1 a, argtype2 b, argtype3 c, argtype4 d) \
336 { return T1##_##func(STATIC_UPCAST(T1, T2, obj), a, b, c, d); }
338 #define DECLARE_DEFAULT_ALLOCATORS(T) \
339 static void* T##_New(size_t size) { return al_malloc(16, size); } \
340 static void T##_Delete(void *ptr) { al_free(ptr); }
342 /* Helper to extract an argument list for VCALL. Not used directly. */
343 #define EXTRACT_VCALL_ARGS(...) __VA_ARGS__))
345 /* Call a "virtual" method on an object, with arguments. */
346 #define V(obj, func) ((obj)->vtbl->func((obj), EXTRACT_VCALL_ARGS
347 /* Call a "virtual" method on an object, with no arguments. */
348 #define V0(obj, func) ((obj)->vtbl->func((obj) EXTRACT_VCALL_ARGS
350 #define DELETE_OBJ(obj) do { \
351 if((obj) != NULL) \
353 V0((obj),Destruct)(); \
354 V0((obj),Delete)(); \
356 } while(0)
359 #define EXTRACT_NEW_ARGS(...) __VA_ARGS__); \
361 } while(0)
363 #define NEW_OBJ(_res, T) do { \
364 _res = T##_New(sizeof(T)); \
365 if(_res) \
367 memset(_res, 0, sizeof(T)); \
368 T##_Construct(_res, EXTRACT_NEW_ARGS
369 #define NEW_OBJ0(_res, T) do { \
370 _res = T##_New(sizeof(T)); \
371 if(_res) \
373 memset(_res, 0, sizeof(T)); \
374 T##_Construct(_res EXTRACT_NEW_ARGS
377 #ifdef __cplusplus
378 extern "C" {
379 #endif
381 struct Hrtf;
382 struct HrtfEntry;
383 struct Compressor;
386 #define DEFAULT_OUTPUT_RATE (44100)
387 #define MIN_OUTPUT_RATE (8000)
390 /* Find the next power-of-2 for non-power-of-2 numbers. */
391 inline ALuint NextPowerOf2(ALuint value)
393 if(value > 0)
395 value--;
396 value |= value>>1;
397 value |= value>>2;
398 value |= value>>4;
399 value |= value>>8;
400 value |= value>>16;
402 return value+1;
405 /** Round up a value to the next multiple. */
406 inline size_t RoundUp(size_t value, size_t r)
408 value += r-1;
409 return value - (value%r);
412 /* Scales the given value using 64-bit integer math, rounding the result. */
413 inline ALuint64 ScaleRound(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale)
415 return (val*new_scale + old_scale/2) / old_scale;
418 /* Scales the given value using 64-bit integer math, flooring the result. */
419 inline ALuint64 ScaleFloor(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale)
421 return val * new_scale / old_scale;
424 /* Scales the given value using 64-bit integer math, ceiling the result. */
425 inline ALuint64 ScaleCeil(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale)
427 return (val*new_scale + old_scale-1) / old_scale;
430 /* Fast float-to-int conversion. Assumes the FPU is already in round-to-zero
431 * mode. */
432 inline ALint fastf2i(ALfloat f)
434 #ifdef HAVE_LRINTF
435 return lrintf(f);
436 #elif defined(_MSC_VER) && defined(_M_IX86)
437 ALint i;
438 __asm fld f
439 __asm fistp i
440 return i;
441 #else
442 return (ALint)f;
443 #endif
447 enum DevProbe {
448 ALL_DEVICE_PROBE,
449 CAPTURE_DEVICE_PROBE
452 struct ALCbackend;
455 enum DistanceModel {
456 InverseDistanceClamped = AL_INVERSE_DISTANCE_CLAMPED,
457 LinearDistanceClamped = AL_LINEAR_DISTANCE_CLAMPED,
458 ExponentDistanceClamped = AL_EXPONENT_DISTANCE_CLAMPED,
459 InverseDistance = AL_INVERSE_DISTANCE,
460 LinearDistance = AL_LINEAR_DISTANCE,
461 ExponentDistance = AL_EXPONENT_DISTANCE,
462 DisableDistance = AL_NONE,
464 DefaultDistanceModel = InverseDistanceClamped
467 enum Channel {
468 FrontLeft = 0,
469 FrontRight,
470 FrontCenter,
471 LFE,
472 BackLeft,
473 BackRight,
474 BackCenter,
475 SideLeft,
476 SideRight,
478 UpperFrontLeft,
479 UpperFrontRight,
480 UpperBackLeft,
481 UpperBackRight,
482 LowerFrontLeft,
483 LowerFrontRight,
484 LowerBackLeft,
485 LowerBackRight,
487 Aux0,
488 Aux1,
489 Aux2,
490 Aux3,
491 Aux4,
492 Aux5,
493 Aux6,
494 Aux7,
495 Aux8,
496 Aux9,
497 Aux10,
498 Aux11,
499 Aux12,
500 Aux13,
501 Aux14,
502 Aux15,
504 InvalidChannel
508 /* Device formats */
509 enum DevFmtType {
510 DevFmtByte = ALC_BYTE_SOFT,
511 DevFmtUByte = ALC_UNSIGNED_BYTE_SOFT,
512 DevFmtShort = ALC_SHORT_SOFT,
513 DevFmtUShort = ALC_UNSIGNED_SHORT_SOFT,
514 DevFmtInt = ALC_INT_SOFT,
515 DevFmtUInt = ALC_UNSIGNED_INT_SOFT,
516 DevFmtFloat = ALC_FLOAT_SOFT,
518 DevFmtTypeDefault = DevFmtFloat
520 enum DevFmtChannels {
521 DevFmtMono = ALC_MONO_SOFT,
522 DevFmtStereo = ALC_STEREO_SOFT,
523 DevFmtQuad = ALC_QUAD_SOFT,
524 DevFmtX51 = ALC_5POINT1_SOFT,
525 DevFmtX61 = ALC_6POINT1_SOFT,
526 DevFmtX71 = ALC_7POINT1_SOFT,
527 DevFmtAmbi3D = ALC_BFORMAT3D_SOFT,
529 /* Similar to 5.1, except using rear channels instead of sides */
530 DevFmtX51Rear = 0x80000000,
532 DevFmtChannelsDefault = DevFmtStereo
534 #define MAX_OUTPUT_CHANNELS (16)
536 ALsizei BytesFromDevFmt(enum DevFmtType type);
537 ALsizei ChannelsFromDevFmt(enum DevFmtChannels chans, ALsizei ambiorder);
538 inline ALsizei FrameSizeFromDevFmt(enum DevFmtChannels chans, enum DevFmtType type, ALsizei ambiorder)
540 return ChannelsFromDevFmt(chans, ambiorder) * BytesFromDevFmt(type);
543 enum AmbiLayout {
544 AmbiLayout_FuMa = ALC_FUMA_SOFT, /* FuMa channel order */
545 AmbiLayout_ACN = ALC_ACN_SOFT, /* ACN channel order */
547 AmbiLayout_Default = AmbiLayout_ACN
550 enum AmbiNorm {
551 AmbiNorm_FuMa = ALC_FUMA_SOFT, /* FuMa normalization */
552 AmbiNorm_SN3D = ALC_SN3D_SOFT, /* SN3D normalization */
553 AmbiNorm_N3D = ALC_N3D_SOFT, /* N3D normalization */
555 AmbiNorm_Default = AmbiNorm_SN3D
559 extern const struct EffectList {
560 const char *name;
561 int type;
562 const char *ename;
563 ALenum val;
564 } EffectList[];
567 enum DeviceType {
568 Playback,
569 Capture,
570 Loopback
574 enum RenderMode {
575 NormalRender,
576 StereoPair,
577 HrtfRender
581 /* The maximum number of Ambisonics coefficients. For a given order (o), the
582 * size needed will be (o+1)**2, thus zero-order has 1, first-order has 4,
583 * second-order has 9, third-order has 16, and fourth-order has 25.
585 #define MAX_AMBI_ORDER 3
586 #define MAX_AMBI_COEFFS ((MAX_AMBI_ORDER+1) * (MAX_AMBI_ORDER+1))
588 /* A bitmask of ambisonic channels with height information. If none of these
589 * channels are used/needed, there's no height (e.g. with most surround sound
590 * speaker setups). This only specifies up to 4th order, which is the highest
591 * order a 32-bit mask value can specify (a 64-bit mask could handle up to 7th
592 * order). This is ACN ordering, with bit 0 being ACN 0, etc.
594 #define AMBI_PERIPHONIC_MASK (0xfe7ce4)
596 /* The maximum number of Ambisonic coefficients for 2D (non-periphonic)
597 * representation. This is 2 per each order above zero-order, plus 1 for zero-
598 * order. Or simply, o*2 + 1.
600 #define MAX_AMBI2D_COEFFS (MAX_AMBI_ORDER*2 + 1)
603 typedef ALfloat ChannelConfig[MAX_AMBI_COEFFS];
604 typedef struct BFChannelConfig {
605 ALfloat Scale;
606 ALsizei Index;
607 } BFChannelConfig;
609 typedef union AmbiConfig {
610 /* Ambisonic coefficients for mixing to the dry buffer. */
611 ChannelConfig Coeffs[MAX_OUTPUT_CHANNELS];
612 /* Coefficient channel mapping for mixing to the dry buffer. */
613 BFChannelConfig Map[MAX_OUTPUT_CHANNELS];
614 } AmbiConfig;
617 #define HRTF_HISTORY_BITS (6)
618 #define HRTF_HISTORY_LENGTH (1<<HRTF_HISTORY_BITS)
619 #define HRTF_HISTORY_MASK (HRTF_HISTORY_LENGTH-1)
621 #define HRIR_BITS (7)
622 #define HRIR_LENGTH (1<<HRIR_BITS)
623 #define HRIR_MASK (HRIR_LENGTH-1)
625 typedef struct HrtfState {
626 alignas(16) ALfloat History[HRTF_HISTORY_LENGTH];
627 alignas(16) ALfloat Values[HRIR_LENGTH][2];
628 } HrtfState;
630 typedef struct HrtfParams {
631 alignas(16) ALfloat Coeffs[HRIR_LENGTH][2];
632 ALsizei Delay[2];
633 ALfloat Gain;
634 } HrtfParams;
636 typedef struct DirectHrtfState {
637 /* HRTF filter state for dry buffer content */
638 ALsizei Offset;
639 ALsizei IrSize;
640 struct {
641 alignas(16) ALfloat Values[HRIR_LENGTH][2];
642 alignas(16) ALfloat Coeffs[HRIR_LENGTH][2];
643 } Chan[];
644 } DirectHrtfState;
646 typedef struct EnumeratedHrtf {
647 al_string name;
649 struct HrtfEntry *hrtf;
650 } EnumeratedHrtf;
651 TYPEDEF_VECTOR(EnumeratedHrtf, vector_EnumeratedHrtf)
654 /* Maximum delay in samples for speaker distance compensation. */
655 #define MAX_DELAY_LENGTH 1024
657 typedef struct DistanceComp {
658 ALfloat Gain;
659 ALsizei Length; /* Valid range is [0...MAX_DELAY_LENGTH). */
660 ALfloat *Buffer;
661 } DistanceComp;
663 /* Size for temporary storage of buffer data, in ALfloats. Larger values need
664 * more memory, while smaller values may need more iterations. The value needs
665 * to be a sensible size, however, as it constrains the max stepping value used
666 * for mixing, as well as the maximum number of samples per mixing iteration.
668 #define BUFFERSIZE 2048
670 struct ALCdevice_struct
672 RefCount ref;
674 ALCboolean Connected;
675 enum DeviceType Type;
677 ALuint Frequency;
678 ALuint UpdateSize;
679 ALuint NumUpdates;
680 enum DevFmtChannels FmtChans;
681 enum DevFmtType FmtType;
682 ALboolean IsHeadphones;
683 ALsizei AmbiOrder;
684 /* For DevFmtAmbi* output only, specifies the channel order and
685 * normalization.
687 enum AmbiLayout AmbiLayout;
688 enum AmbiNorm AmbiScale;
690 al_string DeviceName;
692 ATOMIC(ALCenum) LastError;
694 // Maximum number of sources that can be created
695 ALuint SourcesMax;
696 // Maximum number of slots that can be created
697 ALuint AuxiliaryEffectSlotMax;
699 ALCuint NumMonoSources;
700 ALCuint NumStereoSources;
701 ALsizei NumAuxSends;
703 // Map of Buffers for this device
704 UIntMap BufferMap;
706 // Map of Effects for this device
707 UIntMap EffectMap;
709 // Map of Filters for this device
710 UIntMap FilterMap;
712 /* HRTF state and info */
713 DirectHrtfState *Hrtf;
714 al_string HrtfName;
715 struct Hrtf *HrtfHandle;
716 vector_EnumeratedHrtf HrtfList;
717 ALCenum HrtfStatus;
719 /* UHJ encoder state */
720 struct Uhj2Encoder *Uhj_Encoder;
722 /* High quality Ambisonic decoder */
723 struct BFormatDec *AmbiDecoder;
725 /* Stereo-to-binaural filter */
726 struct bs2b *Bs2b;
728 /* First-order ambisonic upsampler for higher-order output */
729 struct AmbiUpsampler *AmbiUp;
731 /* Rendering mode. */
732 enum RenderMode Render_Mode;
734 // Device flags
735 ALuint Flags;
737 ALuint64 ClockBase;
738 ALuint SamplesDone;
740 /* Temp storage used for each source when mixing. */
741 alignas(16) ALfloat SourceData[BUFFERSIZE];
742 alignas(16) ALfloat ResampledData[BUFFERSIZE];
743 alignas(16) ALfloat FilteredData[BUFFERSIZE];
744 alignas(16) ALfloat NFCtrlData[BUFFERSIZE];
746 /* The "dry" path corresponds to the main output. */
747 struct {
748 AmbiConfig Ambi;
749 /* Number of coefficients in each Ambi.Coeffs to mix together (4 for
750 * first-order, 9 for second-order, etc). If the count is 0, Ambi.Map
751 * is used instead to map each output to a coefficient index.
753 ALsizei CoeffCount;
755 ALfloat (*Buffer)[BUFFERSIZE];
756 ALsizei NumChannels;
757 ALsizei NumChannelsPerOrder[MAX_AMBI_ORDER+1];
758 } Dry;
760 /* First-order ambisonics output, to be upsampled to the dry buffer if different. */
761 struct {
762 AmbiConfig Ambi;
763 /* Will only be 4 or 0. */
764 ALsizei CoeffCount;
766 ALfloat (*Buffer)[BUFFERSIZE];
767 ALsizei NumChannels;
768 } FOAOut;
770 /* "Real" output, which will be written to the device buffer. May alias the
771 * dry buffer.
773 struct {
774 enum Channel ChannelName[MAX_OUTPUT_CHANNELS];
776 ALfloat (*Buffer)[BUFFERSIZE];
777 ALsizei NumChannels;
778 } RealOut;
780 struct Compressor *Limiter;
782 /* The average speaker distance as determined by the ambdec configuration
783 * (or alternatively, by the NFC-HOA reference delay). Only used for NFC.
785 ALfloat AvgSpeakerDist;
787 /* Delay buffers used to compensate for speaker distances. */
788 DistanceComp ChannelDelay[MAX_OUTPUT_CHANNELS];
790 /* Dithering control. */
791 ALfloat DitherDepth;
792 ALuint DitherSeed;
794 /* Running count of the mixer invocations, in 31.1 fixed point. This
795 * actually increments *twice* when mixing, first at the start and then at
796 * the end, so the bottom bit indicates if the device is currently mixing
797 * and the upper bits indicates how many mixes have been done.
799 RefCount MixCount;
801 /* Default effect slot */
802 struct ALeffectslot *DefaultSlot;
804 // Contexts created on this device
805 ATOMIC(ALCcontext*) ContextList;
807 almtx_t BackendLock;
808 struct ALCbackend *Backend;
810 void *ExtraData; // For the backend's use
812 ALCdevice *volatile next;
814 /* Memory space used by the default slot (Playback devices only) */
815 alignas(16) ALCbyte _slot_mem[];
818 // Frequency was requested by the app or config file
819 #define DEVICE_FREQUENCY_REQUEST (1u<<1)
820 // Channel configuration was requested by the config file
821 #define DEVICE_CHANNELS_REQUEST (1u<<2)
822 // Sample type was requested by the config file
823 #define DEVICE_SAMPLE_TYPE_REQUEST (1u<<3)
825 // Specifies if the DSP is paused at user request
826 #define DEVICE_PAUSED (1u<<30)
828 // Specifies if the device is currently running
829 #define DEVICE_RUNNING (1u<<31)
832 /* Nanosecond resolution for the device clock time. */
833 #define DEVICE_CLOCK_RES U64(1000000000)
836 /* Must be less than 15 characters (16 including terminating null) for
837 * compatibility with pthread_setname_np limitations. */
838 #define MIXER_THREAD_NAME "alsoft-mixer"
840 #define RECORD_THREAD_NAME "alsoft-record"
843 struct ALCcontext_struct {
844 RefCount ref;
846 struct ALlistener *Listener;
848 UIntMap SourceMap;
849 UIntMap EffectSlotMap;
851 ATOMIC(ALenum) LastError;
853 enum DistanceModel DistanceModel;
854 ALboolean SourceDistanceModel;
856 ALfloat DopplerFactor;
857 ALfloat DopplerVelocity;
858 ALfloat SpeedOfSound;
859 ATOMIC(ALenum) DeferUpdates;
861 RWLock PropLock;
863 /* Counter for the pre-mixing updates, in 31.1 fixed point (lowest bit
864 * indicates if updates are currently happening).
866 RefCount UpdateCount;
867 ATOMIC(ALenum) HoldUpdates;
869 ALfloat GainBoost;
871 struct ALvoice **Voices;
872 ALsizei VoiceCount;
873 ALsizei MaxVoices;
875 ATOMIC(struct ALeffectslotArray*) ActiveAuxSlots;
877 ALCdevice *Device;
878 const ALCchar *ExtensionList;
880 ALCcontext *volatile next;
882 /* Memory space used by the listener */
883 alignas(16) ALCbyte _listener_mem[];
886 ALCcontext *GetContextRef(void);
888 void ALCcontext_IncRef(ALCcontext *context);
889 void ALCcontext_DecRef(ALCcontext *context);
891 void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends);
893 void AppendAllDevicesList(const ALCchar *name);
894 void AppendCaptureDeviceList(const ALCchar *name);
896 void ALCdevice_Lock(ALCdevice *device);
897 void ALCdevice_Unlock(ALCdevice *device);
899 void ALCcontext_DeferUpdates(ALCcontext *context);
900 void ALCcontext_ProcessUpdates(ALCcontext *context);
903 typedef struct {
904 #ifdef HAVE_FENV_H
905 DERIVE_FROM_TYPE(fenv_t);
906 #else
907 int state;
908 #endif
909 #ifdef HAVE_SSE
910 int sse_state;
911 #endif
912 } FPUCtl;
913 void SetMixerFPUMode(FPUCtl *ctl);
914 void RestoreFPUMode(const FPUCtl *ctl);
917 typedef struct ll_ringbuffer ll_ringbuffer_t;
918 typedef struct ll_ringbuffer_data {
919 char *buf;
920 size_t len;
921 } ll_ringbuffer_data_t;
922 ll_ringbuffer_t *ll_ringbuffer_create(size_t sz, size_t elem_sz);
923 void ll_ringbuffer_free(ll_ringbuffer_t *rb);
924 void ll_ringbuffer_get_read_vector(const ll_ringbuffer_t *rb, ll_ringbuffer_data_t *vec);
925 void ll_ringbuffer_get_write_vector(const ll_ringbuffer_t *rb, ll_ringbuffer_data_t *vec);
926 size_t ll_ringbuffer_read(ll_ringbuffer_t *rb, char *dest, size_t cnt);
927 size_t ll_ringbuffer_peek(ll_ringbuffer_t *rb, char *dest, size_t cnt);
928 void ll_ringbuffer_read_advance(ll_ringbuffer_t *rb, size_t cnt);
929 size_t ll_ringbuffer_read_space(const ll_ringbuffer_t *rb);
930 int ll_ringbuffer_mlock(ll_ringbuffer_t *rb);
931 void ll_ringbuffer_reset(ll_ringbuffer_t *rb);
932 size_t ll_ringbuffer_write(ll_ringbuffer_t *rb, const char *src, size_t cnt);
933 void ll_ringbuffer_write_advance(ll_ringbuffer_t *rb, size_t cnt);
934 size_t ll_ringbuffer_write_space(const ll_ringbuffer_t *rb);
936 void ReadALConfig(void);
937 void FreeALConfig(void);
938 int ConfigValueExists(const char *devName, const char *blockName, const char *keyName);
939 const char *GetConfigValue(const char *devName, const char *blockName, const char *keyName, const char *def);
940 int GetConfigValueBool(const char *devName, const char *blockName, const char *keyName, int def);
941 int ConfigValueStr(const char *devName, const char *blockName, const char *keyName, const char **ret);
942 int ConfigValueInt(const char *devName, const char *blockName, const char *keyName, int *ret);
943 int ConfigValueUInt(const char *devName, const char *blockName, const char *keyName, unsigned int *ret);
944 int ConfigValueFloat(const char *devName, const char *blockName, const char *keyName, float *ret);
945 int ConfigValueBool(const char *devName, const char *blockName, const char *keyName, int *ret);
947 void SetRTPriority(void);
949 void SetDefaultChannelOrder(ALCdevice *device);
950 void SetDefaultWFXChannelOrder(ALCdevice *device);
952 const ALCchar *DevFmtTypeString(enum DevFmtType type);
953 const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans);
956 * GetChannelIdxByName
958 * Returns the index for the given channel name (e.g. FrontCenter), or -1 if it
959 * doesn't exist.
961 inline ALint GetChannelIndex(const enum Channel names[MAX_OUTPUT_CHANNELS], enum Channel chan)
963 ALint i;
964 for(i = 0;i < MAX_OUTPUT_CHANNELS;i++)
966 if(names[i] == chan)
967 return i;
969 return -1;
971 #define GetChannelIdxByName(x, c) GetChannelIndex((x).ChannelName, (c))
973 extern FILE *LogFile;
975 #if defined(__GNUC__) && !defined(_WIN32) && !defined(IN_IDE_PARSER)
976 #define AL_PRINT(T, MSG, ...) fprintf(LogFile, "AL lib: %s %s: "MSG, T, __FUNCTION__ , ## __VA_ARGS__)
977 #else
978 void al_print(const char *type, const char *func, const char *fmt, ...) DECL_FORMAT(printf, 3,4);
979 #define AL_PRINT(T, ...) al_print((T), __FUNCTION__, __VA_ARGS__)
980 #endif
982 #ifdef __ANDROID__
983 #include <android/log.h>
984 #define LOG_ANDROID(T, MSG, ...) __android_log_print(T, "openal", "AL lib: %s: "MSG, __FUNCTION__ , ## __VA_ARGS__)
985 #else
986 #define LOG_ANDROID(T, MSG, ...) ((void)0)
987 #endif
989 enum LogLevel {
990 NoLog,
991 LogError,
992 LogWarning,
993 LogTrace,
994 LogRef
996 extern enum LogLevel LogLevel;
998 #define TRACEREF(...) do { \
999 if(LogLevel >= LogRef) \
1000 AL_PRINT("(--)", __VA_ARGS__); \
1001 } while(0)
1003 #define TRACE(...) do { \
1004 if(LogLevel >= LogTrace) \
1005 AL_PRINT("(II)", __VA_ARGS__); \
1006 LOG_ANDROID(ANDROID_LOG_DEBUG, __VA_ARGS__); \
1007 } while(0)
1009 #define WARN(...) do { \
1010 if(LogLevel >= LogWarning) \
1011 AL_PRINT("(WW)", __VA_ARGS__); \
1012 LOG_ANDROID(ANDROID_LOG_WARN, __VA_ARGS__); \
1013 } while(0)
1015 #define ERR(...) do { \
1016 if(LogLevel >= LogError) \
1017 AL_PRINT("(EE)", __VA_ARGS__); \
1018 LOG_ANDROID(ANDROID_LOG_ERROR, __VA_ARGS__); \
1019 } while(0)
1022 extern ALint RTPrioLevel;
1025 extern ALuint CPUCapFlags;
1026 enum {
1027 CPU_CAP_SSE = 1<<0,
1028 CPU_CAP_SSE2 = 1<<1,
1029 CPU_CAP_SSE3 = 1<<2,
1030 CPU_CAP_SSE4_1 = 1<<3,
1031 CPU_CAP_NEON = 1<<4,
1034 void FillCPUCaps(ALuint capfilter);
1036 vector_al_string SearchDataFiles(const char *match, const char *subdir);
1038 /* Small hack to use a pointer-to-array types as a normal argument type.
1039 * Shouldn't be used directly.
1041 typedef ALfloat ALfloatBUFFERSIZE[BUFFERSIZE];
1042 typedef ALfloat ALfloat2[2];
1045 /* The compressor requires the following information for proper
1046 * initialization:
1048 * PreGainDb - Gain applied before detection (in dB).
1049 * PostGainDb - Gain applied after compression (in dB).
1050 * SummedLink - Whether to use summed (true) or maxed (false) linking.
1051 * RmsSensing - Whether to use RMS (true) or Peak (false) sensing.
1052 * AttackTimeMin - Minimum attack time (in seconds).
1053 * AttackTimeMax - Maximum attack time. Automates when min != max.
1054 * ReleaseTimeMin - Minimum release time (in seconds).
1055 * ReleaseTimeMax - Maximum release time. Automates when min != max.
1056 * Ratio - Compression ratio (x:1). Set to 0 for true limiter.
1057 * ThresholdDb - Triggering threshold (in dB).
1058 * KneeDb - Knee width (below threshold; in dB).
1059 * SampleRate - Sample rate to process.
1061 struct Compressor *CompressorInit(const ALfloat PreGainDb, const ALfloat PostGainDb,
1062 const ALboolean SummedLink, const ALboolean RmsSensing, const ALfloat AttackTimeMin,
1063 const ALfloat AttackTimeMax, const ALfloat ReleaseTimeMin, const ALfloat ReleaseTimeMax,
1064 const ALfloat Ratio, const ALfloat ThresholdDb, const ALfloat KneeDb,
1065 const ALuint SampleRate);
1067 ALuint GetCompressorSampleRate(const struct Compressor *Comp);
1069 void ApplyCompression(struct Compressor *Comp, const ALsizei NumChans, const ALsizei SamplesToDo,
1070 ALfloat (*restrict OutBuffer)[BUFFERSIZE]);
1072 #ifdef __cplusplus
1074 #endif
1076 #endif