Update HRTF code
[openal-soft.git] / Alc / helpers.c
blob80d8e0e49e24a2c87335a2d922b60bcb0ce5cf64
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
34 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
35 #define INITGUID
36 #include <windows.h>
37 #ifdef HAVE_GUIDDEF_H
38 #include <guiddef.h>
39 #else
40 #include <initguid.h>
41 #endif
43 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
44 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
46 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
48 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
49 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
50 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
51 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
53 #ifdef HAVE_MMDEVAPI
54 #include <devpropdef.h>
56 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
57 #endif
59 #endif
61 #include "alMain.h"
63 ALuint CPUCapFlags = 0;
66 void FillCPUCaps(ALuint capfilter)
68 ALuint caps = 0;
70 #if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)
71 /* FIXME: We really should get this for all available CPUs in case different
72 * CPUs have different caps (is that possible on one machine?). */
73 #ifdef HAVE_CPUID_H
74 union {
75 unsigned int regs[4];
76 char str[sizeof(unsigned int[4])];
77 } cpuinf[3];
79 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
80 ERR("Failed to get CPUID\n");
81 else
83 unsigned int maxfunc = cpuinf[0].regs[0];
84 unsigned int maxextfunc = 0;
86 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
87 maxextfunc = cpuinf[0].regs[0];
88 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
90 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
91 if(maxextfunc >= 0x80000004 &&
92 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
93 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
94 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
95 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
97 if(maxfunc >= 1 &&
98 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
100 #ifdef bit_SSE
101 if((cpuinf[0].regs[3]&bit_SSE))
102 caps |= CPU_CAP_SSE;
103 #endif
106 #endif
107 #endif
108 #ifdef HAVE_NEON
109 /* Assume Neon support if compiled with it */
110 caps |= CPU_CAP_NEON;
111 #endif
113 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
114 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
115 ((!caps)?" -none-":""));
116 CPUCapFlags = caps & capfilter;
120 void *al_malloc(size_t alignment, size_t size)
122 #if defined(HAVE_ALIGNED_ALLOC)
123 size = (size+(alignment-1))&~(alignment-1);
124 return aligned_alloc(alignment, size);
125 #elif defined(HAVE_POSIX_MEMALIGN)
126 void *ret;
127 if(posix_memalign(&ret, alignment, size) == 0)
128 return ret;
129 return NULL;
130 #elif defined(HAVE__ALIGNED_MALLOC)
131 return _aligned_malloc(size, alignment);
132 #else
133 char *ret = malloc(size+alignment);
134 if(ret != NULL)
136 *(ret++) = 0x00;
137 while(((ALintptrEXT)ret&(alignment-1)) != 0)
138 *(ret++) = 0x55;
140 return ret;
141 #endif
144 void *al_calloc(size_t alignment, size_t size)
146 void *ret = al_malloc(alignment, size);
147 if(ret) memset(ret, 0, size);
148 return ret;
151 void al_free(void *ptr)
153 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
154 free(ptr);
155 #elif defined(HAVE__ALIGNED_MALLOC)
156 _aligned_free(ptr);
157 #else
158 if(ptr != NULL)
160 char *finder = ptr;
161 do {
162 --finder;
163 } while(*finder == 0x55);
164 free(finder);
166 #endif
169 #ifdef _WIN32
170 void pthread_once(pthread_once_t *once, void (*callback)(void))
172 LONG ret;
173 while((ret=InterlockedExchange(once, 1)) == 1)
174 sched_yield();
175 if(ret == 0)
176 callback();
177 InterlockedExchange(once, 2);
181 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
183 *key = TlsAlloc();
184 if(callback)
185 InsertUIntMapEntry(&TlsDestructor, *key, callback);
186 return 0;
189 int pthread_key_delete(pthread_key_t key)
191 InsertUIntMapEntry(&TlsDestructor, key, NULL);
192 TlsFree(key);
193 return 0;
196 void *pthread_getspecific(pthread_key_t key)
197 { return TlsGetValue(key); }
199 int pthread_setspecific(pthread_key_t key, void *val)
201 TlsSetValue(key, val);
202 return 0;
206 void *LoadLib(const char *name)
207 { return LoadLibraryA(name); }
208 void CloseLib(void *handle)
209 { FreeLibrary((HANDLE)handle); }
210 void *GetSymbol(void *handle, const char *name)
212 void *ret;
214 ret = (void*)GetProcAddress((HANDLE)handle, name);
215 if(ret == NULL)
216 ERR("Failed to load %s\n", name);
217 return ret;
220 WCHAR *strdupW(const WCHAR *str)
222 const WCHAR *n;
223 WCHAR *ret;
224 size_t len;
226 n = str;
227 while(*n) n++;
228 len = n - str;
230 ret = calloc(sizeof(WCHAR), len+1);
231 if(ret != NULL)
232 memcpy(ret, str, sizeof(WCHAR)*len);
233 return ret;
236 #else
238 #include <pthread.h>
239 #ifdef HAVE_PTHREAD_NP_H
240 #include <pthread_np.h>
241 #endif
242 #include <sched.h>
244 void InitializeCriticalSection(CRITICAL_SECTION *cs)
246 pthread_mutexattr_t attrib;
247 int ret;
249 ret = pthread_mutexattr_init(&attrib);
250 assert(ret == 0);
252 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
253 #ifdef HAVE_PTHREAD_NP_H
254 if(ret != 0)
255 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
256 #endif
257 assert(ret == 0);
258 ret = pthread_mutex_init(cs, &attrib);
259 assert(ret == 0);
261 pthread_mutexattr_destroy(&attrib);
263 void DeleteCriticalSection(CRITICAL_SECTION *cs)
265 int ret;
266 ret = pthread_mutex_destroy(cs);
267 assert(ret == 0);
269 void EnterCriticalSection(CRITICAL_SECTION *cs)
271 int ret;
272 ret = pthread_mutex_lock(cs);
273 assert(ret == 0);
275 void LeaveCriticalSection(CRITICAL_SECTION *cs)
277 int ret;
278 ret = pthread_mutex_unlock(cs);
279 assert(ret == 0);
282 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
283 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
284 * Additionally, Win32 is supposed to measure the time since Windows started,
285 * as opposed to the actual time. */
286 ALuint timeGetTime(void)
288 #if _POSIX_TIMERS > 0
289 struct timespec ts;
290 int ret = -1;
292 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
293 #if _POSIX_MONOTONIC_CLOCK == 0
294 static int hasmono = 0;
295 if(hasmono > 0 || (hasmono == 0 &&
296 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
297 #endif
298 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
299 #endif
300 if(ret != 0)
301 ret = clock_gettime(CLOCK_REALTIME, &ts);
302 assert(ret == 0);
304 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
305 #else
306 struct timeval tv;
307 int ret;
309 ret = gettimeofday(&tv, NULL);
310 assert(ret == 0);
312 return tv.tv_usec/1000 + tv.tv_sec*1000;
313 #endif
316 void Sleep(ALuint t)
318 struct timespec tv, rem;
319 tv.tv_nsec = (t*1000000)%1000000000;
320 tv.tv_sec = t/1000;
322 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
323 tv = rem;
326 #ifdef HAVE_DLFCN_H
328 void *LoadLib(const char *name)
330 const char *err;
331 void *handle;
333 dlerror();
334 handle = dlopen(name, RTLD_NOW);
335 if((err=dlerror()) != NULL)
336 handle = NULL;
337 return handle;
339 void CloseLib(void *handle)
340 { dlclose(handle); }
341 void *GetSymbol(void *handle, const char *name)
343 const char *err;
344 void *sym;
346 dlerror();
347 sym = dlsym(handle, name);
348 if((err=dlerror()) != NULL)
350 WARN("Failed to load %s: %s\n", name, err);
351 sym = NULL;
353 return sym;
356 #endif
357 #endif
360 void al_print(const char *func, const char *fmt, ...)
362 char str[256];
363 int i;
365 i = snprintf(str, sizeof(str), "AL lib: %s: ", func);
366 if(i < (int)sizeof(str) && i > 0)
368 va_list ap;
369 va_start(ap, fmt);
370 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
371 va_end(ap);
373 str[sizeof(str)-1] = 0;
375 fprintf(LogFile, "%s", str);
376 fflush(LogFile);
380 void SetRTPriority(void)
382 ALboolean failed = AL_FALSE;
384 #ifdef _WIN32
385 if(RTPrioLevel > 0)
386 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
387 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
388 if(RTPrioLevel > 0)
390 struct sched_param param;
391 /* Use the minimum real-time priority possible for now (on Linux this
392 * should be 1 for SCHED_RR) */
393 param.sched_priority = sched_get_priority_min(SCHED_RR);
394 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
396 #else
397 /* Real-time priority not available */
398 failed = (RTPrioLevel>0);
399 #endif
400 if(failed)
401 ERR("Failed to set priority level for thread\n");
405 static void Lock(volatile ALenum *l)
407 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
408 sched_yield();
411 static void Unlock(volatile ALenum *l)
413 ExchangeInt(l, AL_FALSE);
416 void RWLockInit(RWLock *lock)
418 lock->read_count = 0;
419 lock->write_count = 0;
420 lock->read_lock = AL_FALSE;
421 lock->read_entry_lock = AL_FALSE;
422 lock->write_lock = AL_FALSE;
425 void ReadLock(RWLock *lock)
427 Lock(&lock->read_entry_lock);
428 Lock(&lock->read_lock);
429 if(IncrementRef(&lock->read_count) == 1)
430 Lock(&lock->write_lock);
431 Unlock(&lock->read_lock);
432 Unlock(&lock->read_entry_lock);
435 void ReadUnlock(RWLock *lock)
437 if(DecrementRef(&lock->read_count) == 0)
438 Unlock(&lock->write_lock);
441 void WriteLock(RWLock *lock)
443 if(IncrementRef(&lock->write_count) == 1)
444 Lock(&lock->read_lock);
445 Lock(&lock->write_lock);
448 void WriteUnlock(RWLock *lock)
450 Unlock(&lock->write_lock);
451 if(DecrementRef(&lock->write_count) == 0)
452 Unlock(&lock->read_lock);
456 void InitUIntMap(UIntMap *map, ALsizei limit)
458 map->array = NULL;
459 map->size = 0;
460 map->maxsize = 0;
461 map->limit = limit;
462 RWLockInit(&map->lock);
465 void ResetUIntMap(UIntMap *map)
467 WriteLock(&map->lock);
468 free(map->array);
469 map->array = NULL;
470 map->size = 0;
471 map->maxsize = 0;
472 WriteUnlock(&map->lock);
475 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
477 ALsizei pos = 0;
479 WriteLock(&map->lock);
480 if(map->size > 0)
482 ALsizei low = 0;
483 ALsizei high = map->size - 1;
484 while(low < high)
486 ALsizei mid = low + (high-low)/2;
487 if(map->array[mid].key < key)
488 low = mid + 1;
489 else
490 high = mid;
492 if(map->array[low].key < key)
493 low++;
494 pos = low;
497 if(pos == map->size || map->array[pos].key != key)
499 if(map->size == map->limit)
501 WriteUnlock(&map->lock);
502 return AL_OUT_OF_MEMORY;
505 if(map->size == map->maxsize)
507 ALvoid *temp = NULL;
508 ALsizei newsize;
510 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
511 if(newsize >= map->maxsize)
512 temp = realloc(map->array, newsize*sizeof(map->array[0]));
513 if(!temp)
515 WriteUnlock(&map->lock);
516 return AL_OUT_OF_MEMORY;
518 map->array = temp;
519 map->maxsize = newsize;
522 if(pos < map->size)
523 memmove(&map->array[pos+1], &map->array[pos],
524 (map->size-pos)*sizeof(map->array[0]));
525 map->size++;
527 map->array[pos].key = key;
528 map->array[pos].value = value;
529 WriteUnlock(&map->lock);
531 return AL_NO_ERROR;
534 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
536 ALvoid *ptr = NULL;
537 WriteLock(&map->lock);
538 if(map->size > 0)
540 ALsizei low = 0;
541 ALsizei high = map->size - 1;
542 while(low < high)
544 ALsizei mid = low + (high-low)/2;
545 if(map->array[mid].key < key)
546 low = mid + 1;
547 else
548 high = mid;
550 if(map->array[low].key == key)
552 ptr = map->array[low].value;
553 if(low < map->size-1)
554 memmove(&map->array[low], &map->array[low+1],
555 (map->size-1-low)*sizeof(map->array[0]));
556 map->size--;
559 WriteUnlock(&map->lock);
560 return ptr;
563 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
565 ALvoid *ptr = NULL;
566 ReadLock(&map->lock);
567 if(map->size > 0)
569 ALsizei low = 0;
570 ALsizei high = map->size - 1;
571 while(low < high)
573 ALsizei mid = low + (high-low)/2;
574 if(map->array[mid].key < key)
575 low = mid + 1;
576 else
577 high = mid;
579 if(map->array[low].key == key)
580 ptr = map->array[low].value;
582 ReadUnlock(&map->lock);
583 return ptr;