Properly restore the SSE control word with __control87_2
[openal-soft/openal-hmr.git] / Alc / helpers.c
blob53f4016fce4462a340aa78f7be142d8a35e2e79f
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 void SetMixerFPUMode(FPUCtl *ctl)
178 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
179 unsigned short fpuState;
180 __asm__ __volatile__("fnstcw %0" : "=m" (*&fpuState));
181 ctl->state = fpuState;
182 fpuState &= ~0x300; /* clear precision to single */
183 fpuState |= 0xC00; /* set round-to-zero */
184 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
185 #ifdef HAVE_SSE
186 if((CPUCapFlags&CPU_CAP_SSE))
188 int sseState;
189 __asm__ __volatile__("stmxcsr %0" : "=m" (*&sseState));
190 ctl->sse_state = sseState;
191 sseState &= ~0x300; /* clear precision to single */
192 sseState |= 0xC00; /* set round-to-zero */
193 sseState |= 0x8000; /* set flush-to-zero */
194 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
196 #endif
197 #elif defined(HAVE___CONTROL87_2)
198 int mode;
199 __control87_2(0, 0, &ctl->state, &ctl->sse_state);
200 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
201 #ifdef HAVE_SSE
202 if((CPUCapFlags&CPU_CAP_SSE))
203 __control87_2(_RC_CHOP|_PC_24|_DN_FLUSH, _MCW_RC|_MCW_PC|_MCW_DN, NULL, &mode);
204 #endif
205 #elif defined(HAVE__CONTROLFP)
206 ctl->state = _controlfp(0, 0);
207 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
208 #elif defined(HAVE_FESETROUND)
209 ctl->state = fegetround();
210 #ifdef FE_TOWARDZERO
211 fesetround(FE_TOWARDZERO);
212 #endif
213 #endif
216 void RestoreFPUMode(const FPUCtl *ctl)
218 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
219 unsigned short fpuState = ctl->state;
220 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
221 #ifdef HAVE_SSE
222 if((CPUCapFlags&CPU_CAP_SSE))
223 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
224 #endif
225 #elif defined(HAVE___CONTROL87_2)
226 int mode;
227 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
228 #ifdef HAVE_SSE
229 if((CPUCapFlags&CPU_CAP_SSE))
230 __control87_2(ctl->sse_state, _MCW_RC|_MCW_PC|_MCW_DN, NULL, &mode);
231 #endif
232 #elif defined(HAVE__CONTROLFP)
233 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
234 #elif defined(HAVE_FESETROUND)
235 fesetround(ctl->state);
236 #endif
240 #ifdef _WIN32
241 void pthread_once(pthread_once_t *once, void (*callback)(void))
243 LONG ret;
244 while((ret=InterlockedExchange(once, 1)) == 1)
245 sched_yield();
246 if(ret == 0)
247 callback();
248 InterlockedExchange(once, 2);
252 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
254 *key = TlsAlloc();
255 if(callback)
256 InsertUIntMapEntry(&TlsDestructor, *key, callback);
257 return 0;
260 int pthread_key_delete(pthread_key_t key)
262 InsertUIntMapEntry(&TlsDestructor, key, NULL);
263 TlsFree(key);
264 return 0;
267 void *pthread_getspecific(pthread_key_t key)
268 { return TlsGetValue(key); }
270 int pthread_setspecific(pthread_key_t key, void *val)
272 TlsSetValue(key, val);
273 return 0;
277 void *LoadLib(const char *name)
278 { return LoadLibraryA(name); }
279 void CloseLib(void *handle)
280 { FreeLibrary((HANDLE)handle); }
281 void *GetSymbol(void *handle, const char *name)
283 void *ret;
285 ret = (void*)GetProcAddress((HANDLE)handle, name);
286 if(ret == NULL)
287 ERR("Failed to load %s\n", name);
288 return ret;
291 WCHAR *strdupW(const WCHAR *str)
293 const WCHAR *n;
294 WCHAR *ret;
295 size_t len;
297 n = str;
298 while(*n) n++;
299 len = n - str;
301 ret = calloc(sizeof(WCHAR), len+1);
302 if(ret != NULL)
303 memcpy(ret, str, sizeof(WCHAR)*len);
304 return ret;
307 #else
309 #include <pthread.h>
310 #ifdef HAVE_PTHREAD_NP_H
311 #include <pthread_np.h>
312 #endif
313 #include <sched.h>
315 void InitializeCriticalSection(CRITICAL_SECTION *cs)
317 pthread_mutexattr_t attrib;
318 int ret;
320 ret = pthread_mutexattr_init(&attrib);
321 assert(ret == 0);
323 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
324 #ifdef HAVE_PTHREAD_NP_H
325 if(ret != 0)
326 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
327 #endif
328 assert(ret == 0);
329 ret = pthread_mutex_init(cs, &attrib);
330 assert(ret == 0);
332 pthread_mutexattr_destroy(&attrib);
334 void DeleteCriticalSection(CRITICAL_SECTION *cs)
336 int ret;
337 ret = pthread_mutex_destroy(cs);
338 assert(ret == 0);
340 void EnterCriticalSection(CRITICAL_SECTION *cs)
342 int ret;
343 ret = pthread_mutex_lock(cs);
344 assert(ret == 0);
346 void LeaveCriticalSection(CRITICAL_SECTION *cs)
348 int ret;
349 ret = pthread_mutex_unlock(cs);
350 assert(ret == 0);
353 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
354 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
355 * Additionally, Win32 is supposed to measure the time since Windows started,
356 * as opposed to the actual time. */
357 ALuint timeGetTime(void)
359 #if _POSIX_TIMERS > 0
360 struct timespec ts;
361 int ret = -1;
363 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
364 #if _POSIX_MONOTONIC_CLOCK == 0
365 static int hasmono = 0;
366 if(hasmono > 0 || (hasmono == 0 &&
367 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
368 #endif
369 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
370 #endif
371 if(ret != 0)
372 ret = clock_gettime(CLOCK_REALTIME, &ts);
373 assert(ret == 0);
375 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
376 #else
377 struct timeval tv;
378 int ret;
380 ret = gettimeofday(&tv, NULL);
381 assert(ret == 0);
383 return tv.tv_usec/1000 + tv.tv_sec*1000;
384 #endif
387 void Sleep(ALuint t)
389 struct timespec tv, rem;
390 tv.tv_nsec = (t*1000000)%1000000000;
391 tv.tv_sec = t/1000;
393 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
394 tv = rem;
397 #ifdef HAVE_DLFCN_H
399 void *LoadLib(const char *name)
401 const char *err;
402 void *handle;
404 dlerror();
405 handle = dlopen(name, RTLD_NOW);
406 if((err=dlerror()) != NULL)
407 handle = NULL;
408 return handle;
410 void CloseLib(void *handle)
411 { dlclose(handle); }
412 void *GetSymbol(void *handle, const char *name)
414 const char *err;
415 void *sym;
417 dlerror();
418 sym = dlsym(handle, name);
419 if((err=dlerror()) != NULL)
421 WARN("Failed to load %s: %s\n", name, err);
422 sym = NULL;
424 return sym;
427 #endif
428 #endif
431 void al_print(const char *func, const char *fmt, ...)
433 char str[256];
434 int i;
436 i = snprintf(str, sizeof(str), "AL lib: %s: ", func);
437 if(i < (int)sizeof(str) && i > 0)
439 va_list ap;
440 va_start(ap, fmt);
441 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
442 va_end(ap);
444 str[sizeof(str)-1] = 0;
446 fprintf(LogFile, "%s", str);
447 fflush(LogFile);
451 void SetRTPriority(void)
453 ALboolean failed = AL_FALSE;
455 #ifdef _WIN32
456 if(RTPrioLevel > 0)
457 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
458 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
459 if(RTPrioLevel > 0)
461 struct sched_param param;
462 /* Use the minimum real-time priority possible for now (on Linux this
463 * should be 1 for SCHED_RR) */
464 param.sched_priority = sched_get_priority_min(SCHED_RR);
465 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
467 #else
468 /* Real-time priority not available */
469 failed = (RTPrioLevel>0);
470 #endif
471 if(failed)
472 ERR("Failed to set priority level for thread\n");
476 static void Lock(volatile ALenum *l)
478 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
479 sched_yield();
482 static void Unlock(volatile ALenum *l)
484 ExchangeInt(l, AL_FALSE);
487 void RWLockInit(RWLock *lock)
489 lock->read_count = 0;
490 lock->write_count = 0;
491 lock->read_lock = AL_FALSE;
492 lock->read_entry_lock = AL_FALSE;
493 lock->write_lock = AL_FALSE;
496 void ReadLock(RWLock *lock)
498 Lock(&lock->read_entry_lock);
499 Lock(&lock->read_lock);
500 if(IncrementRef(&lock->read_count) == 1)
501 Lock(&lock->write_lock);
502 Unlock(&lock->read_lock);
503 Unlock(&lock->read_entry_lock);
506 void ReadUnlock(RWLock *lock)
508 if(DecrementRef(&lock->read_count) == 0)
509 Unlock(&lock->write_lock);
512 void WriteLock(RWLock *lock)
514 if(IncrementRef(&lock->write_count) == 1)
515 Lock(&lock->read_lock);
516 Lock(&lock->write_lock);
519 void WriteUnlock(RWLock *lock)
521 Unlock(&lock->write_lock);
522 if(DecrementRef(&lock->write_count) == 0)
523 Unlock(&lock->read_lock);
527 void InitUIntMap(UIntMap *map, ALsizei limit)
529 map->array = NULL;
530 map->size = 0;
531 map->maxsize = 0;
532 map->limit = limit;
533 RWLockInit(&map->lock);
536 void ResetUIntMap(UIntMap *map)
538 WriteLock(&map->lock);
539 free(map->array);
540 map->array = NULL;
541 map->size = 0;
542 map->maxsize = 0;
543 WriteUnlock(&map->lock);
546 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
548 ALsizei pos = 0;
550 WriteLock(&map->lock);
551 if(map->size > 0)
553 ALsizei low = 0;
554 ALsizei high = map->size - 1;
555 while(low < high)
557 ALsizei mid = low + (high-low)/2;
558 if(map->array[mid].key < key)
559 low = mid + 1;
560 else
561 high = mid;
563 if(map->array[low].key < key)
564 low++;
565 pos = low;
568 if(pos == map->size || map->array[pos].key != key)
570 if(map->size == map->limit)
572 WriteUnlock(&map->lock);
573 return AL_OUT_OF_MEMORY;
576 if(map->size == map->maxsize)
578 ALvoid *temp = NULL;
579 ALsizei newsize;
581 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
582 if(newsize >= map->maxsize)
583 temp = realloc(map->array, newsize*sizeof(map->array[0]));
584 if(!temp)
586 WriteUnlock(&map->lock);
587 return AL_OUT_OF_MEMORY;
589 map->array = temp;
590 map->maxsize = newsize;
593 if(pos < map->size)
594 memmove(&map->array[pos+1], &map->array[pos],
595 (map->size-pos)*sizeof(map->array[0]));
596 map->size++;
598 map->array[pos].key = key;
599 map->array[pos].value = value;
600 WriteUnlock(&map->lock);
602 return AL_NO_ERROR;
605 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
607 ALvoid *ptr = NULL;
608 WriteLock(&map->lock);
609 if(map->size > 0)
611 ALsizei low = 0;
612 ALsizei high = map->size - 1;
613 while(low < high)
615 ALsizei mid = low + (high-low)/2;
616 if(map->array[mid].key < key)
617 low = mid + 1;
618 else
619 high = mid;
621 if(map->array[low].key == key)
623 ptr = map->array[low].value;
624 if(low < map->size-1)
625 memmove(&map->array[low], &map->array[low+1],
626 (map->size-1-low)*sizeof(map->array[0]));
627 map->size--;
630 WriteUnlock(&map->lock);
631 return ptr;
634 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
636 ALvoid *ptr = NULL;
637 ReadLock(&map->lock);
638 if(map->size > 0)
640 ALsizei low = 0;
641 ALsizei high = map->size - 1;
642 while(low < high)
644 ALsizei mid = low + (high-low)/2;
645 if(map->array[mid].key < key)
646 low = mid + 1;
647 else
648 high = mid;
650 if(map->array[low].key == key)
651 ptr = map->array[low].value;
653 ReadUnlock(&map->lock);
654 return ptr;