Return the integer from fastf2i with MSVC
[openal-soft.git] / Alc / helpers.c
blob859e6c3dbd398dcc4c04f39360cd6dfa5a0bbca1
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 <malloc.h>
24 #include <stdlib.h>
25 #include <time.h>
26 #include <errno.h>
27 #include <stdarg.h>
29 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
30 #define INITGUID
31 #include <windows.h>
32 #ifdef HAVE_GUIDDEF_H
33 #include <guiddef.h>
34 #else
35 #include <initguid.h>
36 #endif
38 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
39 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
41 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
43 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
44 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
45 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
46 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
48 #ifdef HAVE_MMDEVAPI
49 #include <devpropdef.h>
50 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
51 #endif
52 #endif
53 #ifdef HAVE_DLFCN_H
54 #include <dlfcn.h>
55 #endif
56 #ifdef HAVE_CPUID_H
57 #include <cpuid.h>
58 #endif
59 #ifdef HAVE_FLOAT_H
60 #include <float.h>
61 #endif
62 #ifdef HAVE_IEEEFP_H
63 #include <ieeefp.h>
64 #endif
66 #include "alMain.h"
68 ALuint CPUCapFlags = 0;
71 void FillCPUCaps(ALuint capfilter)
73 ALuint caps = 0;
75 /* FIXME: We really should get this for all available CPUs in case different
76 * CPUs have different caps (is that possible on one machine?). */
77 #if defined(HAVE_CPUID_H) && (defined(__i386__) || defined(__x86_64__) || \
78 defined(_M_IX86) || defined(_M_X64))
79 union {
80 unsigned int regs[4];
81 char str[sizeof(unsigned int[4])];
82 } cpuinf[3];
84 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
85 ERR("Failed to get CPUID\n");
86 else
88 unsigned int maxfunc = cpuinf[0].regs[0];
89 unsigned int maxextfunc = 0;
91 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
92 maxextfunc = cpuinf[0].regs[0];
93 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
95 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
96 if(maxextfunc >= 0x80000004 &&
97 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
98 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
99 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
100 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
102 if(maxfunc >= 1 &&
103 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
105 #ifdef bit_SSE
106 if((cpuinf[0].regs[3]&bit_SSE))
107 caps |= CPU_CAP_SSE;
108 #endif
111 #elif defined(HAVE_WINDOWS_H)
112 HMODULE k32 = GetModuleHandleA("kernel32.dll");
113 BOOL (WINAPI*IsProcessorFeaturePresent)(DWORD ProcessorFeature);
114 IsProcessorFeaturePresent = (BOOL(WINAPI*)(DWORD))GetProcAddress(k32, "IsProcessorFeaturePresent");
115 if(!IsProcessorFeaturePresent)
116 ERR("IsProcessorFeaturePresent not available; CPU caps not detected\n");
117 else
119 if(IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
120 caps |= CPU_CAP_SSE;
122 #endif
123 #ifdef HAVE_NEON
124 /* Assume Neon support if compiled with it */
125 caps |= CPU_CAP_NEON;
126 #endif
128 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
129 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
130 ((!caps)?" -none-":""));
131 CPUCapFlags = caps & capfilter;
135 void *al_malloc(size_t alignment, size_t size)
137 #if defined(HAVE_ALIGNED_ALLOC)
138 size = (size+(alignment-1))&~(alignment-1);
139 return aligned_alloc(alignment, size);
140 #elif defined(HAVE_POSIX_MEMALIGN)
141 void *ret;
142 if(posix_memalign(&ret, alignment, size) == 0)
143 return ret;
144 return NULL;
145 #elif defined(HAVE__ALIGNED_MALLOC)
146 return _aligned_malloc(size, alignment);
147 #else
148 char *ret = malloc(size+alignment);
149 if(ret != NULL)
151 *(ret++) = 0x00;
152 while(((ALintptrEXT)ret&(alignment-1)) != 0)
153 *(ret++) = 0x55;
155 return ret;
156 #endif
159 void *al_calloc(size_t alignment, size_t size)
161 void *ret = al_malloc(alignment, size);
162 if(ret) memset(ret, 0, size);
163 return ret;
166 void al_free(void *ptr)
168 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
169 free(ptr);
170 #elif defined(HAVE__ALIGNED_MALLOC)
171 _aligned_free(ptr);
172 #else
173 if(ptr != NULL)
175 char *finder = ptr;
176 do {
177 --finder;
178 } while(*finder == 0x55);
179 free(finder);
181 #endif
185 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
186 /* Win64 doesn't allow us to set the precision control. */
187 #undef _MCW_PC
188 #define _MCW_PC 0
189 #endif
191 void SetMixerFPUMode(FPUCtl *ctl)
193 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
194 unsigned short fpuState;
195 __asm__ __volatile__("fnstcw %0" : "=m" (*&fpuState));
196 ctl->state = fpuState;
197 fpuState &= ~0x300; /* clear precision to single */
198 fpuState |= 0xC00; /* set round-to-zero */
199 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
200 #ifdef HAVE_SSE
201 if((CPUCapFlags&CPU_CAP_SSE))
203 int sseState;
204 __asm__ __volatile__("stmxcsr %0" : "=m" (*&sseState));
205 ctl->sse_state = sseState;
206 sseState |= 0x0C00; /* set round-to-zero */
207 sseState |= 0x8000; /* set flush-to-zero */
208 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
210 #endif
211 #elif defined(HAVE___CONTROL87_2)
212 int mode;
213 __control87_2(0, 0, &ctl->state, &ctl->sse_state);
214 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
215 #ifdef HAVE_SSE
216 if((CPUCapFlags&CPU_CAP_SSE))
217 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
218 #endif
219 #elif defined(HAVE__CONTROLFP)
220 ctl->state = _controlfp(0, 0);
221 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
222 #elif defined(HAVE_FESETROUND)
223 ctl->state = fegetround();
224 #ifdef FE_TOWARDZERO
225 fesetround(FE_TOWARDZERO);
226 #endif
227 #endif
230 void RestoreFPUMode(const FPUCtl *ctl)
232 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
233 unsigned short fpuState = ctl->state;
234 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
235 #ifdef HAVE_SSE
236 if((CPUCapFlags&CPU_CAP_SSE))
237 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
238 #endif
239 #elif defined(HAVE___CONTROL87_2)
240 int mode;
241 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
242 #ifdef HAVE_SSE
243 if((CPUCapFlags&CPU_CAP_SSE))
244 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
245 #endif
246 #elif defined(HAVE__CONTROLFP)
247 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
248 #elif defined(HAVE_FESETROUND)
249 fesetround(ctl->state);
250 #endif
254 #ifdef _WIN32
255 void pthread_once(pthread_once_t *once, void (*callback)(void))
257 LONG ret;
258 while((ret=InterlockedExchange(once, 1)) == 1)
259 sched_yield();
260 if(ret == 0)
261 callback();
262 InterlockedExchange(once, 2);
266 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
268 *key = TlsAlloc();
269 if(callback)
270 InsertUIntMapEntry(&TlsDestructor, *key, callback);
271 return 0;
274 int pthread_key_delete(pthread_key_t key)
276 InsertUIntMapEntry(&TlsDestructor, key, NULL);
277 TlsFree(key);
278 return 0;
281 void *pthread_getspecific(pthread_key_t key)
282 { return TlsGetValue(key); }
284 int pthread_setspecific(pthread_key_t key, void *val)
286 TlsSetValue(key, val);
287 return 0;
291 void *LoadLib(const char *name)
292 { return LoadLibraryA(name); }
293 void CloseLib(void *handle)
294 { FreeLibrary((HANDLE)handle); }
295 void *GetSymbol(void *handle, const char *name)
297 void *ret;
299 ret = (void*)GetProcAddress((HANDLE)handle, name);
300 if(ret == NULL)
301 ERR("Failed to load %s\n", name);
302 return ret;
305 WCHAR *strdupW(const WCHAR *str)
307 const WCHAR *n;
308 WCHAR *ret;
309 size_t len;
311 n = str;
312 while(*n) n++;
313 len = n - str;
315 ret = calloc(sizeof(WCHAR), len+1);
316 if(ret != NULL)
317 memcpy(ret, str, sizeof(WCHAR)*len);
318 return ret;
321 #else
323 #include <pthread.h>
324 #ifdef HAVE_PTHREAD_NP_H
325 #include <pthread_np.h>
326 #endif
327 #include <sched.h>
329 void InitializeCriticalSection(CRITICAL_SECTION *cs)
331 pthread_mutexattr_t attrib;
332 int ret;
334 ret = pthread_mutexattr_init(&attrib);
335 assert(ret == 0);
337 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
338 #ifdef HAVE_PTHREAD_NP_H
339 if(ret != 0)
340 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
341 #endif
342 assert(ret == 0);
343 ret = pthread_mutex_init(cs, &attrib);
344 assert(ret == 0);
346 pthread_mutexattr_destroy(&attrib);
348 void DeleteCriticalSection(CRITICAL_SECTION *cs)
350 int ret;
351 ret = pthread_mutex_destroy(cs);
352 assert(ret == 0);
354 void EnterCriticalSection(CRITICAL_SECTION *cs)
356 int ret;
357 ret = pthread_mutex_lock(cs);
358 assert(ret == 0);
360 void LeaveCriticalSection(CRITICAL_SECTION *cs)
362 int ret;
363 ret = pthread_mutex_unlock(cs);
364 assert(ret == 0);
367 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
368 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
369 * Additionally, Win32 is supposed to measure the time since Windows started,
370 * as opposed to the actual time. */
371 ALuint timeGetTime(void)
373 #if _POSIX_TIMERS > 0
374 struct timespec ts;
375 int ret = -1;
377 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
378 #if _POSIX_MONOTONIC_CLOCK == 0
379 static int hasmono = 0;
380 if(hasmono > 0 || (hasmono == 0 &&
381 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
382 #endif
383 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
384 #endif
385 if(ret != 0)
386 ret = clock_gettime(CLOCK_REALTIME, &ts);
387 assert(ret == 0);
389 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
390 #else
391 struct timeval tv;
392 int ret;
394 ret = gettimeofday(&tv, NULL);
395 assert(ret == 0);
397 return tv.tv_usec/1000 + tv.tv_sec*1000;
398 #endif
401 void Sleep(ALuint t)
403 struct timespec tv, rem;
404 tv.tv_nsec = (t*1000000)%1000000000;
405 tv.tv_sec = t/1000;
407 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
408 tv = rem;
411 #ifdef HAVE_DLFCN_H
413 void *LoadLib(const char *name)
415 const char *err;
416 void *handle;
418 dlerror();
419 handle = dlopen(name, RTLD_NOW);
420 if((err=dlerror()) != NULL)
421 handle = NULL;
422 return handle;
424 void CloseLib(void *handle)
425 { dlclose(handle); }
426 void *GetSymbol(void *handle, const char *name)
428 const char *err;
429 void *sym;
431 dlerror();
432 sym = dlsym(handle, name);
433 if((err=dlerror()) != NULL)
435 WARN("Failed to load %s: %s\n", name, err);
436 sym = NULL;
438 return sym;
441 #endif
442 #endif
445 void al_print(const char *type, const char *func, const char *fmt, ...)
447 char str[256];
448 int i;
450 i = snprintf(str, sizeof(str), "AL lib: %s %s: ", type, func);
451 if(i > 0 && (unsigned int)i < sizeof(str))
453 va_list ap;
454 va_start(ap, fmt);
455 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
456 va_end(ap);
458 str[sizeof(str)-1] = 0;
460 fprintf(LogFile, "%s", str);
461 fflush(LogFile);
465 void SetRTPriority(void)
467 ALboolean failed = AL_FALSE;
469 #ifdef _WIN32
470 if(RTPrioLevel > 0)
471 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
472 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
473 if(RTPrioLevel > 0)
475 struct sched_param param;
476 /* Use the minimum real-time priority possible for now (on Linux this
477 * should be 1 for SCHED_RR) */
478 param.sched_priority = sched_get_priority_min(SCHED_RR);
479 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
481 #else
482 /* Real-time priority not available */
483 failed = (RTPrioLevel>0);
484 #endif
485 if(failed)
486 ERR("Failed to set priority level for thread\n");
490 static void Lock(volatile ALenum *l)
492 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
493 sched_yield();
496 static void Unlock(volatile ALenum *l)
498 ExchangeInt(l, AL_FALSE);
501 void RWLockInit(RWLock *lock)
503 lock->read_count = 0;
504 lock->write_count = 0;
505 lock->read_lock = AL_FALSE;
506 lock->read_entry_lock = AL_FALSE;
507 lock->write_lock = AL_FALSE;
510 void ReadLock(RWLock *lock)
512 Lock(&lock->read_entry_lock);
513 Lock(&lock->read_lock);
514 if(IncrementRef(&lock->read_count) == 1)
515 Lock(&lock->write_lock);
516 Unlock(&lock->read_lock);
517 Unlock(&lock->read_entry_lock);
520 void ReadUnlock(RWLock *lock)
522 if(DecrementRef(&lock->read_count) == 0)
523 Unlock(&lock->write_lock);
526 void WriteLock(RWLock *lock)
528 if(IncrementRef(&lock->write_count) == 1)
529 Lock(&lock->read_lock);
530 Lock(&lock->write_lock);
533 void WriteUnlock(RWLock *lock)
535 Unlock(&lock->write_lock);
536 if(DecrementRef(&lock->write_count) == 0)
537 Unlock(&lock->read_lock);
541 void InitUIntMap(UIntMap *map, ALsizei limit)
543 map->array = NULL;
544 map->size = 0;
545 map->maxsize = 0;
546 map->limit = limit;
547 RWLockInit(&map->lock);
550 void ResetUIntMap(UIntMap *map)
552 WriteLock(&map->lock);
553 free(map->array);
554 map->array = NULL;
555 map->size = 0;
556 map->maxsize = 0;
557 WriteUnlock(&map->lock);
560 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
562 ALsizei pos = 0;
564 WriteLock(&map->lock);
565 if(map->size > 0)
567 ALsizei low = 0;
568 ALsizei high = map->size - 1;
569 while(low < high)
571 ALsizei mid = low + (high-low)/2;
572 if(map->array[mid].key < key)
573 low = mid + 1;
574 else
575 high = mid;
577 if(map->array[low].key < key)
578 low++;
579 pos = low;
582 if(pos == map->size || map->array[pos].key != key)
584 if(map->size == map->limit)
586 WriteUnlock(&map->lock);
587 return AL_OUT_OF_MEMORY;
590 if(map->size == map->maxsize)
592 ALvoid *temp = NULL;
593 ALsizei newsize;
595 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
596 if(newsize >= map->maxsize)
597 temp = realloc(map->array, newsize*sizeof(map->array[0]));
598 if(!temp)
600 WriteUnlock(&map->lock);
601 return AL_OUT_OF_MEMORY;
603 map->array = temp;
604 map->maxsize = newsize;
607 if(pos < map->size)
608 memmove(&map->array[pos+1], &map->array[pos],
609 (map->size-pos)*sizeof(map->array[0]));
610 map->size++;
612 map->array[pos].key = key;
613 map->array[pos].value = value;
614 WriteUnlock(&map->lock);
616 return AL_NO_ERROR;
619 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
621 ALvoid *ptr = NULL;
622 WriteLock(&map->lock);
623 if(map->size > 0)
625 ALsizei low = 0;
626 ALsizei high = map->size - 1;
627 while(low < high)
629 ALsizei mid = low + (high-low)/2;
630 if(map->array[mid].key < key)
631 low = mid + 1;
632 else
633 high = mid;
635 if(map->array[low].key == key)
637 ptr = map->array[low].value;
638 if(low < map->size-1)
639 memmove(&map->array[low], &map->array[low+1],
640 (map->size-1-low)*sizeof(map->array[0]));
641 map->size--;
644 WriteUnlock(&map->lock);
645 return ptr;
648 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
650 ALvoid *ptr = NULL;
651 ReadLock(&map->lock);
652 if(map->size > 0)
654 ALsizei low = 0;
655 ALsizei high = map->size - 1;
656 while(low < high)
658 ALsizei mid = low + (high-low)/2;
659 if(map->array[mid].key < key)
660 low = mid + 1;
661 else
662 high = mid;
664 if(map->array[low].key == key)
665 ptr = map->array[low].value;
667 ReadUnlock(&map->lock);
668 return ptr;