alMain.h 35 KB

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