Don't include alu.h in alMain.h
[openal-soft.git] / Alc / helpers.c
blob9529acec2440fc22c15edd55b001f0fa71a7a5d8
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2011 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 <stdlib.h>
24 #include <time.h>
25 #include <errno.h>
26 #include <stdarg.h>
27 #ifdef HAVE_DLFCN_H
28 #include <dlfcn.h>
29 #endif
30 #ifdef HAVE_CPUID_H
31 #include <cpuid.h>
32 #endif
33 #ifdef HAVE_FLOAT_H
34 #include <float.h>
35 #endif
36 #ifdef HAVE_IEEEFP_H
37 #include <ieeefp.h>
38 #endif
40 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
41 #define INITGUID
42 #include <windows.h>
43 #ifdef HAVE_GUIDDEF_H
44 #include <guiddef.h>
45 #else
46 #include <initguid.h>
47 #endif
49 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
50 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
52 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
54 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
55 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
56 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
57 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
59 #ifdef HAVE_MMDEVAPI
60 #include <devpropdef.h>
62 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
63 #endif
65 #endif
67 #include "alMain.h"
69 ALuint CPUCapFlags = 0;
72 void FillCPUCaps(ALuint capfilter)
74 ALuint caps = 0;
76 #if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)
77 /* FIXME: We really should get this for all available CPUs in case different
78 * CPUs have different caps (is that possible on one machine?). */
79 #ifdef HAVE_CPUID_H
80 union {
81 unsigned int regs[4];
82 char str[sizeof(unsigned int[4])];
83 } cpuinf[3];
85 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
86 ERR("Failed to get CPUID\n");
87 else
89 unsigned int maxfunc = cpuinf[0].regs[0];
90 unsigned int maxextfunc = 0;
92 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
93 maxextfunc = cpuinf[0].regs[0];
94 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
96 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
97 if(maxextfunc >= 0x80000004 &&
98 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
99 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
100 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
101 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
103 if(maxfunc >= 1 &&
104 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
106 #ifdef bit_SSE
107 if((cpuinf[0].regs[3]&bit_SSE))
108 caps |= CPU_CAP_SSE;
109 #endif
112 #endif
113 #endif
114 #ifdef HAVE_NEON
115 /* Assume Neon support if compiled with it */
116 caps |= CPU_CAP_NEON;
117 #endif
119 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
120 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
121 ((!caps)?" -none-":""));
122 CPUCapFlags = caps & capfilter;
126 void *al_malloc(size_t alignment, size_t size)
128 #if defined(HAVE_ALIGNED_ALLOC)
129 size = (size+(alignment-1))&~(alignment-1);
130 return aligned_alloc(alignment, size);
131 #elif defined(HAVE_POSIX_MEMALIGN)
132 void *ret;
133 if(posix_memalign(&ret, alignment, size) == 0)
134 return ret;
135 return NULL;
136 #elif defined(HAVE__ALIGNED_MALLOC)
137 return _aligned_malloc(size, alignment);
138 #else
139 char *ret = malloc(size+alignment);
140 if(ret != NULL)
142 *(ret++) = 0x00;
143 while(((ALintptrEXT)ret&(alignment-1)) != 0)
144 *(ret++) = 0x55;
146 return ret;
147 #endif
150 void *al_calloc(size_t alignment, size_t size)
152 void *ret = al_malloc(alignment, size);
153 if(ret) memset(ret, 0, size);
154 return ret;
157 void al_free(void *ptr)
159 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
160 free(ptr);
161 #elif defined(HAVE__ALIGNED_MALLOC)
162 _aligned_free(ptr);
163 #else
164 if(ptr != NULL)
166 char *finder = ptr;
167 do {
168 --finder;
169 } while(*finder == 0x55);
170 free(finder);
172 #endif
176 int SetMixerFPUMode(void)
178 #if defined(_FPU_GETCW) && defined(_FPU_SETCW) && (defined(__i386__) || defined(__x86_64__))
179 fpu_control_t fpuState, newState;
180 _FPU_GETCW(fpuState);
181 newState = fpuState&~(_FPU_EXTENDED|_FPU_DOUBLE|_FPU_SINGLE |
182 _FPU_RC_NEAREST|_FPU_RC_DOWN|_FPU_RC_UP|_FPU_RC_ZERO);
183 newState |= _FPU_SINGLE | _FPU_RC_ZERO;
184 if((CPUCapFlags&CPU_CAP_SSE))
185 newState |= 0x8000; /* flush-to-zero */
186 _FPU_SETCW(newState);
187 #else
188 int fpuState;
189 #if defined(HAVE__CONTROLFP)
190 fpuState = _controlfp(0, 0);
191 (void)_controlfp(_RC_CHOP|_DN_FLUSH|_PC_24, _MCW_RC|_MCW_DN|_MCW_PC);
192 #elif defined(HAVE_FESETROUND)
193 fpuState = fegetround();
194 #ifdef FE_TOWARDZERO
195 fesetround(FE_TOWARDZERO);
196 #endif
197 #endif
198 #endif
199 return fpuState;
202 void RestoreFPUMode(int state)
204 #if defined(_FPU_GETCW) && defined(_FPU_SETCW) && (defined(__i386__) || defined(__x86_64__))
205 fpu_control_t fpuState = state;
206 _FPU_SETCW(fpuState);
207 #elif defined(HAVE__CONTROLFP)
208 _controlfp(state, _MCW_RC|_MCW_DN|_MCW_PC);
209 #elif defined(HAVE_FESETROUND)
210 fesetround(state);
211 #endif
215 #ifdef _WIN32
216 void pthread_once(pthread_once_t *once, void (*callback)(void))
218 LONG ret;
219 while((ret=InterlockedExchange(once, 1)) == 1)
220 sched_yield();
221 if(ret == 0)
222 callback();
223 InterlockedExchange(once, 2);
227 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
229 *key = TlsAlloc();
230 if(callback)
231 InsertUIntMapEntry(&TlsDestructor, *key, callback);
232 return 0;
235 int pthread_key_delete(pthread_key_t key)
237 InsertUIntMapEntry(&TlsDestructor, key, NULL);
238 TlsFree(key);
239 return 0;
242 void *pthread_getspecific(pthread_key_t key)
243 { return TlsGetValue(key); }
245 int pthread_setspecific(pthread_key_t key, void *val)
247 TlsSetValue(key, val);
248 return 0;
252 void *LoadLib(const char *name)
253 { return LoadLibraryA(name); }
254 void CloseLib(void *handle)
255 { FreeLibrary((HANDLE)handle); }
256 void *GetSymbol(void *handle, const char *name)
258 void *ret;
260 ret = (void*)GetProcAddress((HANDLE)handle, name);
261 if(ret == NULL)
262 ERR("Failed to load %s\n", name);
263 return ret;
266 WCHAR *strdupW(const WCHAR *str)
268 const WCHAR *n;
269 WCHAR *ret;
270 size_t len;
272 n = str;
273 while(*n) n++;
274 len = n - str;
276 ret = calloc(sizeof(WCHAR), len+1);
277 if(ret != NULL)
278 memcpy(ret, str, sizeof(WCHAR)*len);
279 return ret;
282 #else
284 #include <pthread.h>
285 #ifdef HAVE_PTHREAD_NP_H
286 #include <pthread_np.h>
287 #endif
288 #include <sched.h>
290 void InitializeCriticalSection(CRITICAL_SECTION *cs)
292 pthread_mutexattr_t attrib;
293 int ret;
295 ret = pthread_mutexattr_init(&attrib);
296 assert(ret == 0);
298 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
299 #ifdef HAVE_PTHREAD_NP_H
300 if(ret != 0)
301 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
302 #endif
303 assert(ret == 0);
304 ret = pthread_mutex_init(cs, &attrib);
305 assert(ret == 0);
307 pthread_mutexattr_destroy(&attrib);
309 void DeleteCriticalSection(CRITICAL_SECTION *cs)
311 int ret;
312 ret = pthread_mutex_destroy(cs);
313 assert(ret == 0);
315 void EnterCriticalSection(CRITICAL_SECTION *cs)
317 int ret;
318 ret = pthread_mutex_lock(cs);
319 assert(ret == 0);
321 void LeaveCriticalSection(CRITICAL_SECTION *cs)
323 int ret;
324 ret = pthread_mutex_unlock(cs);
325 assert(ret == 0);
328 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
329 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
330 * Additionally, Win32 is supposed to measure the time since Windows started,
331 * as opposed to the actual time. */
332 ALuint timeGetTime(void)
334 #if _POSIX_TIMERS > 0
335 struct timespec ts;
336 int ret = -1;
338 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
339 #if _POSIX_MONOTONIC_CLOCK == 0
340 static int hasmono = 0;
341 if(hasmono > 0 || (hasmono == 0 &&
342 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
343 #endif
344 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
345 #endif
346 if(ret != 0)
347 ret = clock_gettime(CLOCK_REALTIME, &ts);
348 assert(ret == 0);
350 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
351 #else
352 struct timeval tv;
353 int ret;
355 ret = gettimeofday(&tv, NULL);
356 assert(ret == 0);
358 return tv.tv_usec/1000 + tv.tv_sec*1000;
359 #endif
362 void Sleep(ALuint t)
364 struct timespec tv, rem;
365 tv.tv_nsec = (t*1000000)%1000000000;
366 tv.tv_sec = t/1000;
368 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
369 tv = rem;
372 #ifdef HAVE_DLFCN_H
374 void *LoadLib(const char *name)
376 const char *err;
377 void *handle;
379 dlerror();
380 handle = dlopen(name, RTLD_NOW);
381 if((err=dlerror()) != NULL)
382 handle = NULL;
383 return handle;
385 void CloseLib(void *handle)
386 { dlclose(handle); }
387 void *GetSymbol(void *handle, const char *name)
389 const char *err;
390 void *sym;
392 dlerror();
393 sym = dlsym(handle, name);
394 if((err=dlerror()) != NULL)
396 WARN("Failed to load %s: %s\n", name, err);
397 sym = NULL;
399 return sym;
402 #endif
403 #endif
406 void al_print(const char *func, const char *fmt, ...)
408 char str[256];
409 int i;
411 i = snprintf(str, sizeof(str), "AL lib: %s: ", func);
412 if(i < (int)sizeof(str) && i > 0)
414 va_list ap;
415 va_start(ap, fmt);
416 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
417 va_end(ap);
419 str[sizeof(str)-1] = 0;
421 fprintf(LogFile, "%s", str);
422 fflush(LogFile);
426 void SetRTPriority(void)
428 ALboolean failed = AL_FALSE;
430 #ifdef _WIN32
431 if(RTPrioLevel > 0)
432 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
433 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
434 if(RTPrioLevel > 0)
436 struct sched_param param;
437 /* Use the minimum real-time priority possible for now (on Linux this
438 * should be 1 for SCHED_RR) */
439 param.sched_priority = sched_get_priority_min(SCHED_RR);
440 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
442 #else
443 /* Real-time priority not available */
444 failed = (RTPrioLevel>0);
445 #endif
446 if(failed)
447 ERR("Failed to set priority level for thread\n");
451 static void Lock(volatile ALenum *l)
453 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
454 sched_yield();
457 static void Unlock(volatile ALenum *l)
459 ExchangeInt(l, AL_FALSE);
462 void RWLockInit(RWLock *lock)
464 lock->read_count = 0;
465 lock->write_count = 0;
466 lock->read_lock = AL_FALSE;
467 lock->read_entry_lock = AL_FALSE;
468 lock->write_lock = AL_FALSE;
471 void ReadLock(RWLock *lock)
473 Lock(&lock->read_entry_lock);
474 Lock(&lock->read_lock);
475 if(IncrementRef(&lock->read_count) == 1)
476 Lock(&lock->write_lock);
477 Unlock(&lock->read_lock);
478 Unlock(&lock->read_entry_lock);
481 void ReadUnlock(RWLock *lock)
483 if(DecrementRef(&lock->read_count) == 0)
484 Unlock(&lock->write_lock);
487 void WriteLock(RWLock *lock)
489 if(IncrementRef(&lock->write_count) == 1)
490 Lock(&lock->read_lock);
491 Lock(&lock->write_lock);
494 void WriteUnlock(RWLock *lock)
496 Unlock(&lock->write_lock);
497 if(DecrementRef(&lock->write_count) == 0)
498 Unlock(&lock->read_lock);
502 void InitUIntMap(UIntMap *map, ALsizei limit)
504 map->array = NULL;
505 map->size = 0;
506 map->maxsize = 0;
507 map->limit = limit;
508 RWLockInit(&map->lock);
511 void ResetUIntMap(UIntMap *map)
513 WriteLock(&map->lock);
514 free(map->array);
515 map->array = NULL;
516 map->size = 0;
517 map->maxsize = 0;
518 WriteUnlock(&map->lock);
521 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
523 ALsizei pos = 0;
525 WriteLock(&map->lock);
526 if(map->size > 0)
528 ALsizei low = 0;
529 ALsizei high = map->size - 1;
530 while(low < high)
532 ALsizei mid = low + (high-low)/2;
533 if(map->array[mid].key < key)
534 low = mid + 1;
535 else
536 high = mid;
538 if(map->array[low].key < key)
539 low++;
540 pos = low;
543 if(pos == map->size || map->array[pos].key != key)
545 if(map->size == map->limit)
547 WriteUnlock(&map->lock);
548 return AL_OUT_OF_MEMORY;
551 if(map->size == map->maxsize)
553 ALvoid *temp = NULL;
554 ALsizei newsize;
556 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
557 if(newsize >= map->maxsize)
558 temp = realloc(map->array, newsize*sizeof(map->array[0]));
559 if(!temp)
561 WriteUnlock(&map->lock);
562 return AL_OUT_OF_MEMORY;
564 map->array = temp;
565 map->maxsize = newsize;
568 if(pos < map->size)
569 memmove(&map->array[pos+1], &map->array[pos],
570 (map->size-pos)*sizeof(map->array[0]));
571 map->size++;
573 map->array[pos].key = key;
574 map->array[pos].value = value;
575 WriteUnlock(&map->lock);
577 return AL_NO_ERROR;
580 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
582 ALvoid *ptr = NULL;
583 WriteLock(&map->lock);
584 if(map->size > 0)
586 ALsizei low = 0;
587 ALsizei high = map->size - 1;
588 while(low < high)
590 ALsizei mid = low + (high-low)/2;
591 if(map->array[mid].key < key)
592 low = mid + 1;
593 else
594 high = mid;
596 if(map->array[low].key == key)
598 ptr = map->array[low].value;
599 if(low < map->size-1)
600 memmove(&map->array[low], &map->array[low+1],
601 (map->size-1-low)*sizeof(map->array[0]));
602 map->size--;
605 WriteUnlock(&map->lock);
606 return ptr;
609 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
611 ALvoid *ptr = NULL;
612 ReadLock(&map->lock);
613 if(map->size > 0)
615 ALsizei low = 0;
616 ALsizei high = map->size - 1;
617 while(low < high)
619 ALsizei mid = low + (high-low)/2;
620 if(map->array[mid].key < key)
621 low = mid + 1;
622 else
623 high = mid;
625 if(map->array[low].key == key)
626 ptr = map->array[low].value;
628 ReadUnlock(&map->lock);
629 return ptr;