Fix a type conversion warning
[openal-soft.git] / Alc / helpers.c
blobd99a70e6baa15aaeacccf69853b50f76e51395e2
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 #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 #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 #endif
125 #ifdef HAVE_NEON
126 /* Assume Neon support if compiled with it */
127 caps |= CPU_CAP_NEON;
128 #endif
130 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
131 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
132 ((!caps)?" -none-":""));
133 CPUCapFlags = caps & capfilter;
137 void *al_malloc(size_t alignment, size_t size)
139 #if defined(HAVE_ALIGNED_ALLOC)
140 size = (size+(alignment-1))&~(alignment-1);
141 return aligned_alloc(alignment, size);
142 #elif defined(HAVE_POSIX_MEMALIGN)
143 void *ret;
144 if(posix_memalign(&ret, alignment, size) == 0)
145 return ret;
146 return NULL;
147 #elif defined(HAVE__ALIGNED_MALLOC)
148 return _aligned_malloc(size, alignment);
149 #else
150 char *ret = malloc(size+alignment);
151 if(ret != NULL)
153 *(ret++) = 0x00;
154 while(((ALintptrEXT)ret&(alignment-1)) != 0)
155 *(ret++) = 0x55;
157 return ret;
158 #endif
161 void *al_calloc(size_t alignment, size_t size)
163 void *ret = al_malloc(alignment, size);
164 if(ret) memset(ret, 0, size);
165 return ret;
168 void al_free(void *ptr)
170 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
171 free(ptr);
172 #elif defined(HAVE__ALIGNED_MALLOC)
173 _aligned_free(ptr);
174 #else
175 if(ptr != NULL)
177 char *finder = ptr;
178 do {
179 --finder;
180 } while(*finder == 0x55);
181 free(finder);
183 #endif
187 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
188 /* Win64 doesn't allow us to set the precision control. */
189 #undef _MCW_PC
190 #define _MCW_PC 0
191 #endif
193 void SetMixerFPUMode(FPUCtl *ctl)
195 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
196 unsigned short fpuState;
197 __asm__ __volatile__("fnstcw %0" : "=m" (*&fpuState));
198 ctl->state = fpuState;
199 fpuState &= ~0x300; /* clear precision to single */
200 fpuState |= 0xC00; /* set round-to-zero */
201 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
202 #ifdef HAVE_SSE
203 if((CPUCapFlags&CPU_CAP_SSE))
205 int sseState;
206 __asm__ __volatile__("stmxcsr %0" : "=m" (*&sseState));
207 ctl->sse_state = sseState;
208 sseState |= 0x0C00; /* set round-to-zero */
209 sseState |= 0x8000; /* set flush-to-zero */
210 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
212 #endif
213 #elif defined(HAVE___CONTROL87_2)
214 int mode;
215 __control87_2(0, 0, &ctl->state, &ctl->sse_state);
216 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
217 #ifdef HAVE_SSE
218 if((CPUCapFlags&CPU_CAP_SSE))
219 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
220 #endif
221 #elif defined(HAVE__CONTROLFP)
222 ctl->state = _controlfp(0, 0);
223 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
224 #elif defined(HAVE_FESETROUND)
225 ctl->state = fegetround();
226 #ifdef FE_TOWARDZERO
227 fesetround(FE_TOWARDZERO);
228 #endif
229 #endif
232 void RestoreFPUMode(const FPUCtl *ctl)
234 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
235 unsigned short fpuState = ctl->state;
236 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
237 #ifdef HAVE_SSE
238 if((CPUCapFlags&CPU_CAP_SSE))
239 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
240 #endif
241 #elif defined(HAVE___CONTROL87_2)
242 int mode;
243 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
244 #ifdef HAVE_SSE
245 if((CPUCapFlags&CPU_CAP_SSE))
246 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
247 #endif
248 #elif defined(HAVE__CONTROLFP)
249 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
250 #elif defined(HAVE_FESETROUND)
251 fesetround(ctl->state);
252 #endif
256 #ifdef _WIN32
257 void pthread_once(pthread_once_t *once, void (*callback)(void))
259 LONG ret;
260 while((ret=InterlockedExchange(once, 1)) == 1)
261 sched_yield();
262 if(ret == 0)
263 callback();
264 InterlockedExchange(once, 2);
268 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
270 *key = TlsAlloc();
271 if(callback)
272 InsertUIntMapEntry(&TlsDestructor, *key, callback);
273 return 0;
276 int pthread_key_delete(pthread_key_t key)
278 InsertUIntMapEntry(&TlsDestructor, key, NULL);
279 TlsFree(key);
280 return 0;
283 void *pthread_getspecific(pthread_key_t key)
284 { return TlsGetValue(key); }
286 int pthread_setspecific(pthread_key_t key, void *val)
288 TlsSetValue(key, val);
289 return 0;
293 void *LoadLib(const char *name)
294 { return LoadLibraryA(name); }
295 void CloseLib(void *handle)
296 { FreeLibrary((HANDLE)handle); }
297 void *GetSymbol(void *handle, const char *name)
299 void *ret;
301 ret = (void*)GetProcAddress((HANDLE)handle, name);
302 if(ret == NULL)
303 ERR("Failed to load %s\n", name);
304 return ret;
307 WCHAR *strdupW(const WCHAR *str)
309 const WCHAR *n;
310 WCHAR *ret;
311 size_t len;
313 n = str;
314 while(*n) n++;
315 len = n - str;
317 ret = calloc(sizeof(WCHAR), len+1);
318 if(ret != NULL)
319 memcpy(ret, str, sizeof(WCHAR)*len);
320 return ret;
323 #else
325 #include <pthread.h>
326 #ifdef HAVE_PTHREAD_NP_H
327 #include <pthread_np.h>
328 #endif
329 #include <sched.h>
331 void InitializeCriticalSection(CRITICAL_SECTION *cs)
333 pthread_mutexattr_t attrib;
334 int ret;
336 ret = pthread_mutexattr_init(&attrib);
337 assert(ret == 0);
339 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
340 #ifdef HAVE_PTHREAD_NP_H
341 if(ret != 0)
342 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
343 #endif
344 assert(ret == 0);
345 ret = pthread_mutex_init(cs, &attrib);
346 assert(ret == 0);
348 pthread_mutexattr_destroy(&attrib);
350 void DeleteCriticalSection(CRITICAL_SECTION *cs)
352 int ret;
353 ret = pthread_mutex_destroy(cs);
354 assert(ret == 0);
356 void EnterCriticalSection(CRITICAL_SECTION *cs)
358 int ret;
359 ret = pthread_mutex_lock(cs);
360 assert(ret == 0);
362 void LeaveCriticalSection(CRITICAL_SECTION *cs)
364 int ret;
365 ret = pthread_mutex_unlock(cs);
366 assert(ret == 0);
369 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
370 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
371 * Additionally, Win32 is supposed to measure the time since Windows started,
372 * as opposed to the actual time. */
373 ALuint timeGetTime(void)
375 #if _POSIX_TIMERS > 0
376 struct timespec ts;
377 int ret = -1;
379 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
380 #if _POSIX_MONOTONIC_CLOCK == 0
381 static int hasmono = 0;
382 if(hasmono > 0 || (hasmono == 0 &&
383 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
384 #endif
385 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
386 #endif
387 if(ret != 0)
388 ret = clock_gettime(CLOCK_REALTIME, &ts);
389 assert(ret == 0);
391 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
392 #else
393 struct timeval tv;
394 int ret;
396 ret = gettimeofday(&tv, NULL);
397 assert(ret == 0);
399 return tv.tv_usec/1000 + tv.tv_sec*1000;
400 #endif
403 void Sleep(ALuint t)
405 struct timespec tv, rem;
406 tv.tv_nsec = (t*1000000)%1000000000;
407 tv.tv_sec = t/1000;
409 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
410 tv = rem;
413 #ifdef HAVE_DLFCN_H
415 void *LoadLib(const char *name)
417 const char *err;
418 void *handle;
420 dlerror();
421 handle = dlopen(name, RTLD_NOW);
422 if((err=dlerror()) != NULL)
423 handle = NULL;
424 return handle;
426 void CloseLib(void *handle)
427 { dlclose(handle); }
428 void *GetSymbol(void *handle, const char *name)
430 const char *err;
431 void *sym;
433 dlerror();
434 sym = dlsym(handle, name);
435 if((err=dlerror()) != NULL)
437 WARN("Failed to load %s: %s\n", name, err);
438 sym = NULL;
440 return sym;
443 #endif
444 #endif
447 void al_print(const char *type, const char *func, const char *fmt, ...)
449 char str[256];
450 int i;
452 i = snprintf(str, sizeof(str), "AL lib: %s %s: ", type, func);
453 if(i > 0 && (unsigned int)i < sizeof(str))
455 va_list ap;
456 va_start(ap, fmt);
457 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
458 va_end(ap);
460 str[sizeof(str)-1] = 0;
462 fprintf(LogFile, "%s", str);
463 fflush(LogFile);
467 void SetRTPriority(void)
469 ALboolean failed = AL_FALSE;
471 #ifdef _WIN32
472 if(RTPrioLevel > 0)
473 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
474 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
475 if(RTPrioLevel > 0)
477 struct sched_param param;
478 /* Use the minimum real-time priority possible for now (on Linux this
479 * should be 1 for SCHED_RR) */
480 param.sched_priority = sched_get_priority_min(SCHED_RR);
481 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
483 #else
484 /* Real-time priority not available */
485 failed = (RTPrioLevel>0);
486 #endif
487 if(failed)
488 ERR("Failed to set priority level for thread\n");
492 static void Lock(volatile ALenum *l)
494 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
495 sched_yield();
498 static void Unlock(volatile ALenum *l)
500 ExchangeInt(l, AL_FALSE);
503 void RWLockInit(RWLock *lock)
505 lock->read_count = 0;
506 lock->write_count = 0;
507 lock->read_lock = AL_FALSE;
508 lock->read_entry_lock = AL_FALSE;
509 lock->write_lock = AL_FALSE;
512 void ReadLock(RWLock *lock)
514 Lock(&lock->read_entry_lock);
515 Lock(&lock->read_lock);
516 if(IncrementRef(&lock->read_count) == 1)
517 Lock(&lock->write_lock);
518 Unlock(&lock->read_lock);
519 Unlock(&lock->read_entry_lock);
522 void ReadUnlock(RWLock *lock)
524 if(DecrementRef(&lock->read_count) == 0)
525 Unlock(&lock->write_lock);
528 void WriteLock(RWLock *lock)
530 if(IncrementRef(&lock->write_count) == 1)
531 Lock(&lock->read_lock);
532 Lock(&lock->write_lock);
535 void WriteUnlock(RWLock *lock)
537 Unlock(&lock->write_lock);
538 if(DecrementRef(&lock->write_count) == 0)
539 Unlock(&lock->read_lock);
543 void InitUIntMap(UIntMap *map, ALsizei limit)
545 map->array = NULL;
546 map->size = 0;
547 map->maxsize = 0;
548 map->limit = limit;
549 RWLockInit(&map->lock);
552 void ResetUIntMap(UIntMap *map)
554 WriteLock(&map->lock);
555 free(map->array);
556 map->array = NULL;
557 map->size = 0;
558 map->maxsize = 0;
559 WriteUnlock(&map->lock);
562 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
564 ALsizei pos = 0;
566 WriteLock(&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 low++;
581 pos = low;
584 if(pos == map->size || map->array[pos].key != key)
586 if(map->size == map->limit)
588 WriteUnlock(&map->lock);
589 return AL_OUT_OF_MEMORY;
592 if(map->size == map->maxsize)
594 ALvoid *temp = NULL;
595 ALsizei newsize;
597 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
598 if(newsize >= map->maxsize)
599 temp = realloc(map->array, newsize*sizeof(map->array[0]));
600 if(!temp)
602 WriteUnlock(&map->lock);
603 return AL_OUT_OF_MEMORY;
605 map->array = temp;
606 map->maxsize = newsize;
609 if(pos < map->size)
610 memmove(&map->array[pos+1], &map->array[pos],
611 (map->size-pos)*sizeof(map->array[0]));
612 map->size++;
614 map->array[pos].key = key;
615 map->array[pos].value = value;
616 WriteUnlock(&map->lock);
618 return AL_NO_ERROR;
621 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
623 ALvoid *ptr = NULL;
624 WriteLock(&map->lock);
625 if(map->size > 0)
627 ALsizei low = 0;
628 ALsizei high = map->size - 1;
629 while(low < high)
631 ALsizei mid = low + (high-low)/2;
632 if(map->array[mid].key < key)
633 low = mid + 1;
634 else
635 high = mid;
637 if(map->array[low].key == key)
639 ptr = map->array[low].value;
640 if(low < map->size-1)
641 memmove(&map->array[low], &map->array[low+1],
642 (map->size-1-low)*sizeof(map->array[0]));
643 map->size--;
646 WriteUnlock(&map->lock);
647 return ptr;
650 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
652 ALvoid *ptr = NULL;
653 ReadLock(&map->lock);
654 if(map->size > 0)
656 ALsizei low = 0;
657 ALsizei high = map->size - 1;
658 while(low < high)
660 ALsizei mid = low + (high-low)/2;
661 if(map->array[mid].key < key)
662 low = mid + 1;
663 else
664 high = mid;
666 if(map->array[low].key == key)
667 ptr = map->array[low].value;
669 ReadUnlock(&map->lock);
670 return ptr;