Add a couple missing RESTRICTs
[openal-soft.git] / Alc / helpers.c
blob963ead67e3d9d2fe5ea8b62dba4e9b74d267099d
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 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
24 #define INITGUID
25 #include <windows.h>
26 #ifdef HAVE_GUIDDEF_H
27 #include <guiddef.h>
28 #else
29 #include <initguid.h>
30 #endif
32 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
33 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
35 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
37 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
38 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
39 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
40 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
42 #ifdef HAVE_MMDEVAPI
43 #include <devpropdef.h>
45 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
46 #endif
48 #endif
50 #include <stdlib.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <stdarg.h>
54 #ifdef HAVE_DLFCN_H
55 #include <dlfcn.h>
56 #endif
57 #ifdef HAVE_CPUID_H
58 #include <cpuid.h>
59 #endif
60 #ifdef HAVE_FLOAT_H
61 #include <float.h>
62 #endif
63 #ifdef HAVE_IEEEFP_H
64 #include <ieeefp.h>
65 #endif
67 #include "alMain.h"
69 ALuint CPUCapFlags = 0;
72 void FillCPUCaps(ALuint capfilter)
74 ALuint caps = 0;
76 /* FIXME: We really should get this for all available CPUs in case different
77 * CPUs have different caps (is that possible on one machine?). */
78 #if defined(HAVE_CPUID_H) && (defined(__i386__) || defined(__x86_64__) || \
79 defined(_M_IX86) || defined(_M_X64))
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 #elif defined(HAVE_WINDOWS_H)
113 HMODULE k32 = GetModuleHandleA("kernel32.dll");
114 BOOL (WINAPI*IsProcessorFeaturePresent)(DWORD ProcessorFeature);
115 IsProcessorFeaturePresent = (BOOL(WINAPI*)(DWORD))GetProcAddress(k32, "IsProcessorFeaturePresent");
116 if(!IsProcessorFeaturePresent)
117 ERR("IsProcessorFeaturePresent not available; CPU caps not detected\n");
118 else
120 if(IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
121 caps |= CPU_CAP_SSE;
123 #endif
124 #ifdef HAVE_NEON
125 /* Assume Neon support if compiled with it */
126 caps |= CPU_CAP_NEON;
127 #endif
129 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
130 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
131 ((!caps)?" -none-":""));
132 CPUCapFlags = caps & capfilter;
136 void *al_malloc(size_t alignment, size_t size)
138 #if defined(HAVE_ALIGNED_ALLOC)
139 size = (size+(alignment-1))&~(alignment-1);
140 return aligned_alloc(alignment, size);
141 #elif defined(HAVE_POSIX_MEMALIGN)
142 void *ret;
143 if(posix_memalign(&ret, alignment, size) == 0)
144 return ret;
145 return NULL;
146 #elif defined(HAVE__ALIGNED_MALLOC)
147 return _aligned_malloc(size, alignment);
148 #else
149 char *ret = malloc(size+alignment);
150 if(ret != NULL)
152 *(ret++) = 0x00;
153 while(((ALintptrEXT)ret&(alignment-1)) != 0)
154 *(ret++) = 0x55;
156 return ret;
157 #endif
160 void *al_calloc(size_t alignment, size_t size)
162 void *ret = al_malloc(alignment, size);
163 if(ret) memset(ret, 0, size);
164 return ret;
167 void al_free(void *ptr)
169 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
170 free(ptr);
171 #elif defined(HAVE__ALIGNED_MALLOC)
172 _aligned_free(ptr);
173 #else
174 if(ptr != NULL)
176 char *finder = ptr;
177 do {
178 --finder;
179 } while(*finder == 0x55);
180 free(finder);
182 #endif
186 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
187 /* Win64 doesn't allow us to set the precision control. */
188 #undef _MCW_PC
189 #define _MCW_PC 0
190 #endif
192 void SetMixerFPUMode(FPUCtl *ctl)
194 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
195 unsigned short fpuState;
196 __asm__ __volatile__("fnstcw %0" : "=m" (*&fpuState));
197 ctl->state = fpuState;
198 fpuState &= ~0x300; /* clear precision to single */
199 fpuState |= 0xC00; /* set round-to-zero */
200 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
201 #ifdef HAVE_SSE
202 if((CPUCapFlags&CPU_CAP_SSE))
204 int sseState;
205 __asm__ __volatile__("stmxcsr %0" : "=m" (*&sseState));
206 ctl->sse_state = sseState;
207 sseState |= 0x0C00; /* set round-to-zero */
208 sseState |= 0x8000; /* set flush-to-zero */
209 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
211 #endif
212 #elif defined(HAVE___CONTROL87_2)
213 int mode;
214 __control87_2(0, 0, &ctl->state, &ctl->sse_state);
215 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
216 #ifdef HAVE_SSE
217 if((CPUCapFlags&CPU_CAP_SSE))
218 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
219 #endif
220 #elif defined(HAVE__CONTROLFP)
221 ctl->state = _controlfp(0, 0);
222 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
223 #elif defined(HAVE_FESETROUND)
224 ctl->state = fegetround();
225 #ifdef FE_TOWARDZERO
226 fesetround(FE_TOWARDZERO);
227 #endif
228 #endif
231 void RestoreFPUMode(const FPUCtl *ctl)
233 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
234 unsigned short fpuState = ctl->state;
235 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
236 #ifdef HAVE_SSE
237 if((CPUCapFlags&CPU_CAP_SSE))
238 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
239 #endif
240 #elif defined(HAVE___CONTROL87_2)
241 int mode;
242 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
243 #ifdef HAVE_SSE
244 if((CPUCapFlags&CPU_CAP_SSE))
245 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
246 #endif
247 #elif defined(HAVE__CONTROLFP)
248 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
249 #elif defined(HAVE_FESETROUND)
250 fesetround(ctl->state);
251 #endif
255 #ifdef _WIN32
256 void pthread_once(pthread_once_t *once, void (*callback)(void))
258 LONG ret;
259 while((ret=InterlockedExchange(once, 1)) == 1)
260 sched_yield();
261 if(ret == 0)
262 callback();
263 InterlockedExchange(once, 2);
267 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
269 *key = TlsAlloc();
270 if(callback)
271 InsertUIntMapEntry(&TlsDestructor, *key, callback);
272 return 0;
275 int pthread_key_delete(pthread_key_t key)
277 InsertUIntMapEntry(&TlsDestructor, key, NULL);
278 TlsFree(key);
279 return 0;
282 void *pthread_getspecific(pthread_key_t key)
283 { return TlsGetValue(key); }
285 int pthread_setspecific(pthread_key_t key, void *val)
287 TlsSetValue(key, val);
288 return 0;
292 void *LoadLib(const char *name)
293 { return LoadLibraryA(name); }
294 void CloseLib(void *handle)
295 { FreeLibrary((HANDLE)handle); }
296 void *GetSymbol(void *handle, const char *name)
298 void *ret;
300 ret = (void*)GetProcAddress((HANDLE)handle, name);
301 if(ret == NULL)
302 ERR("Failed to load %s\n", name);
303 return ret;
306 WCHAR *strdupW(const WCHAR *str)
308 const WCHAR *n;
309 WCHAR *ret;
310 size_t len;
312 n = str;
313 while(*n) n++;
314 len = n - str;
316 ret = calloc(sizeof(WCHAR), len+1);
317 if(ret != NULL)
318 memcpy(ret, str, sizeof(WCHAR)*len);
319 return ret;
322 #else
324 #include <pthread.h>
325 #ifdef HAVE_PTHREAD_NP_H
326 #include <pthread_np.h>
327 #endif
328 #include <sched.h>
330 void InitializeCriticalSection(CRITICAL_SECTION *cs)
332 pthread_mutexattr_t attrib;
333 int ret;
335 ret = pthread_mutexattr_init(&attrib);
336 assert(ret == 0);
338 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
339 #ifdef HAVE_PTHREAD_NP_H
340 if(ret != 0)
341 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
342 #endif
343 assert(ret == 0);
344 ret = pthread_mutex_init(cs, &attrib);
345 assert(ret == 0);
347 pthread_mutexattr_destroy(&attrib);
349 void DeleteCriticalSection(CRITICAL_SECTION *cs)
351 int ret;
352 ret = pthread_mutex_destroy(cs);
353 assert(ret == 0);
355 void EnterCriticalSection(CRITICAL_SECTION *cs)
357 int ret;
358 ret = pthread_mutex_lock(cs);
359 assert(ret == 0);
361 void LeaveCriticalSection(CRITICAL_SECTION *cs)
363 int ret;
364 ret = pthread_mutex_unlock(cs);
365 assert(ret == 0);
368 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
369 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
370 * Additionally, Win32 is supposed to measure the time since Windows started,
371 * as opposed to the actual time. */
372 ALuint timeGetTime(void)
374 #if _POSIX_TIMERS > 0
375 struct timespec ts;
376 int ret = -1;
378 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
379 #if _POSIX_MONOTONIC_CLOCK == 0
380 static int hasmono = 0;
381 if(hasmono > 0 || (hasmono == 0 &&
382 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
383 #endif
384 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
385 #endif
386 if(ret != 0)
387 ret = clock_gettime(CLOCK_REALTIME, &ts);
388 assert(ret == 0);
390 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
391 #else
392 struct timeval tv;
393 int ret;
395 ret = gettimeofday(&tv, NULL);
396 assert(ret == 0);
398 return tv.tv_usec/1000 + tv.tv_sec*1000;
399 #endif
402 void Sleep(ALuint t)
404 struct timespec tv, rem;
405 tv.tv_nsec = (t*1000000)%1000000000;
406 tv.tv_sec = t/1000;
408 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
409 tv = rem;
412 #ifdef HAVE_DLFCN_H
414 void *LoadLib(const char *name)
416 const char *err;
417 void *handle;
419 dlerror();
420 handle = dlopen(name, RTLD_NOW);
421 if((err=dlerror()) != NULL)
422 handle = NULL;
423 return handle;
425 void CloseLib(void *handle)
426 { dlclose(handle); }
427 void *GetSymbol(void *handle, const char *name)
429 const char *err;
430 void *sym;
432 dlerror();
433 sym = dlsym(handle, name);
434 if((err=dlerror()) != NULL)
436 WARN("Failed to load %s: %s\n", name, err);
437 sym = NULL;
439 return sym;
442 #endif
443 #endif
446 void al_print(const char *type, const char *func, const char *fmt, ...)
448 char str[256];
449 int i;
451 i = snprintf(str, sizeof(str), "AL lib: %s %s: ", type, func);
452 if(i > 0 && (unsigned int)i < sizeof(str))
454 va_list ap;
455 va_start(ap, fmt);
456 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
457 va_end(ap);
459 str[sizeof(str)-1] = 0;
461 fprintf(LogFile, "%s", str);
462 fflush(LogFile);
466 void SetRTPriority(void)
468 ALboolean failed = AL_FALSE;
470 #ifdef _WIN32
471 if(RTPrioLevel > 0)
472 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
473 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
474 if(RTPrioLevel > 0)
476 struct sched_param param;
477 /* Use the minimum real-time priority possible for now (on Linux this
478 * should be 1 for SCHED_RR) */
479 param.sched_priority = sched_get_priority_min(SCHED_RR);
480 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
482 #else
483 /* Real-time priority not available */
484 failed = (RTPrioLevel>0);
485 #endif
486 if(failed)
487 ERR("Failed to set priority level for thread\n");
491 static void Lock(volatile ALenum *l)
493 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
494 sched_yield();
497 static void Unlock(volatile ALenum *l)
499 ExchangeInt(l, AL_FALSE);
502 void RWLockInit(RWLock *lock)
504 lock->read_count = 0;
505 lock->write_count = 0;
506 lock->read_lock = AL_FALSE;
507 lock->read_entry_lock = AL_FALSE;
508 lock->write_lock = AL_FALSE;
511 void ReadLock(RWLock *lock)
513 Lock(&lock->read_entry_lock);
514 Lock(&lock->read_lock);
515 if(IncrementRef(&lock->read_count) == 1)
516 Lock(&lock->write_lock);
517 Unlock(&lock->read_lock);
518 Unlock(&lock->read_entry_lock);
521 void ReadUnlock(RWLock *lock)
523 if(DecrementRef(&lock->read_count) == 0)
524 Unlock(&lock->write_lock);
527 void WriteLock(RWLock *lock)
529 if(IncrementRef(&lock->write_count) == 1)
530 Lock(&lock->read_lock);
531 Lock(&lock->write_lock);
534 void WriteUnlock(RWLock *lock)
536 Unlock(&lock->write_lock);
537 if(DecrementRef(&lock->write_count) == 0)
538 Unlock(&lock->read_lock);
542 void InitUIntMap(UIntMap *map, ALsizei limit)
544 map->array = NULL;
545 map->size = 0;
546 map->maxsize = 0;
547 map->limit = limit;
548 RWLockInit(&map->lock);
551 void ResetUIntMap(UIntMap *map)
553 WriteLock(&map->lock);
554 free(map->array);
555 map->array = NULL;
556 map->size = 0;
557 map->maxsize = 0;
558 WriteUnlock(&map->lock);
561 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
563 ALsizei pos = 0;
565 WriteLock(&map->lock);
566 if(map->size > 0)
568 ALsizei low = 0;
569 ALsizei high = map->size - 1;
570 while(low < high)
572 ALsizei mid = low + (high-low)/2;
573 if(map->array[mid].key < key)
574 low = mid + 1;
575 else
576 high = mid;
578 if(map->array[low].key < key)
579 low++;
580 pos = low;
583 if(pos == map->size || map->array[pos].key != key)
585 if(map->size == map->limit)
587 WriteUnlock(&map->lock);
588 return AL_OUT_OF_MEMORY;
591 if(map->size == map->maxsize)
593 ALvoid *temp = NULL;
594 ALsizei newsize;
596 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
597 if(newsize >= map->maxsize)
598 temp = realloc(map->array, newsize*sizeof(map->array[0]));
599 if(!temp)
601 WriteUnlock(&map->lock);
602 return AL_OUT_OF_MEMORY;
604 map->array = temp;
605 map->maxsize = newsize;
608 if(pos < map->size)
609 memmove(&map->array[pos+1], &map->array[pos],
610 (map->size-pos)*sizeof(map->array[0]));
611 map->size++;
613 map->array[pos].key = key;
614 map->array[pos].value = value;
615 WriteUnlock(&map->lock);
617 return AL_NO_ERROR;
620 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
622 ALvoid *ptr = NULL;
623 WriteLock(&map->lock);
624 if(map->size > 0)
626 ALsizei low = 0;
627 ALsizei high = map->size - 1;
628 while(low < high)
630 ALsizei mid = low + (high-low)/2;
631 if(map->array[mid].key < key)
632 low = mid + 1;
633 else
634 high = mid;
636 if(map->array[low].key == key)
638 ptr = map->array[low].value;
639 if(low < map->size-1)
640 memmove(&map->array[low], &map->array[low+1],
641 (map->size-1-low)*sizeof(map->array[0]));
642 map->size--;
645 WriteUnlock(&map->lock);
646 return ptr;
649 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
651 ALvoid *ptr = NULL;
652 ReadLock(&map->lock);
653 if(map->size > 0)
655 ALsizei low = 0;
656 ALsizei high = map->size - 1;
657 while(low < high)
659 ALsizei mid = low + (high-low)/2;
660 if(map->array[mid].key < key)
661 low = mid + 1;
662 else
663 high = mid;
665 if(map->array[low].key == key)
666 ptr = map->array[low].value;
668 ReadUnlock(&map->lock);
669 return ptr;