Check the max CPUID functions before calling them
[openal-soft/openal-hmr.git] / Alc / helpers.c
blobbf83bcbf8e06e7185cef51ec9211fa527297da47
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++) = 0xAA;
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) || defined(HAVE__ALIGNED_MALLOC)
154 free(ptr);
155 #else
156 if(ptr != NULL)
158 char *finder = ptr;
159 do {
160 --finder;
161 } while(*finder == 0xAA);
162 free(finder);
164 return ret;
165 #endif
168 #ifdef _WIN32
169 void pthread_once(pthread_once_t *once, void (*callback)(void))
171 LONG ret;
172 while((ret=InterlockedExchange(once, 1)) == 1)
173 sched_yield();
174 if(ret == 0)
175 callback();
176 InterlockedExchange(once, 2);
180 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
182 *key = TlsAlloc();
183 if(callback)
184 InsertUIntMapEntry(&TlsDestructor, *key, callback);
185 return 0;
188 int pthread_key_delete(pthread_key_t key)
190 InsertUIntMapEntry(&TlsDestructor, key, NULL);
191 TlsFree(key);
192 return 0;
195 void *pthread_getspecific(pthread_key_t key)
196 { return TlsGetValue(key); }
198 int pthread_setspecific(pthread_key_t key, void *val)
200 TlsSetValue(key, val);
201 return 0;
205 void *LoadLib(const char *name)
206 { return LoadLibraryA(name); }
207 void CloseLib(void *handle)
208 { FreeLibrary((HANDLE)handle); }
209 void *GetSymbol(void *handle, const char *name)
211 void *ret;
213 ret = (void*)GetProcAddress((HANDLE)handle, name);
214 if(ret == NULL)
215 ERR("Failed to load %s\n", name);
216 return ret;
219 WCHAR *strdupW(const WCHAR *str)
221 const WCHAR *n;
222 WCHAR *ret;
223 size_t len;
225 n = str;
226 while(*n) n++;
227 len = n - str;
229 ret = calloc(sizeof(WCHAR), len+1);
230 if(ret != NULL)
231 memcpy(ret, str, sizeof(WCHAR)*len);
232 return ret;
235 #else
237 #include <pthread.h>
238 #ifdef HAVE_PTHREAD_NP_H
239 #include <pthread_np.h>
240 #endif
241 #include <sched.h>
243 void InitializeCriticalSection(CRITICAL_SECTION *cs)
245 pthread_mutexattr_t attrib;
246 int ret;
248 ret = pthread_mutexattr_init(&attrib);
249 assert(ret == 0);
251 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
252 #ifdef HAVE_PTHREAD_NP_H
253 if(ret != 0)
254 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
255 #endif
256 assert(ret == 0);
257 ret = pthread_mutex_init(cs, &attrib);
258 assert(ret == 0);
260 pthread_mutexattr_destroy(&attrib);
262 void DeleteCriticalSection(CRITICAL_SECTION *cs)
264 int ret;
265 ret = pthread_mutex_destroy(cs);
266 assert(ret == 0);
268 void EnterCriticalSection(CRITICAL_SECTION *cs)
270 int ret;
271 ret = pthread_mutex_lock(cs);
272 assert(ret == 0);
274 void LeaveCriticalSection(CRITICAL_SECTION *cs)
276 int ret;
277 ret = pthread_mutex_unlock(cs);
278 assert(ret == 0);
281 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
282 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
283 * Additionally, Win32 is supposed to measure the time since Windows started,
284 * as opposed to the actual time. */
285 ALuint timeGetTime(void)
287 #if _POSIX_TIMERS > 0
288 struct timespec ts;
289 int ret = -1;
291 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
292 #if _POSIX_MONOTONIC_CLOCK == 0
293 static int hasmono = 0;
294 if(hasmono > 0 || (hasmono == 0 &&
295 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
296 #endif
297 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
298 #endif
299 if(ret != 0)
300 ret = clock_gettime(CLOCK_REALTIME, &ts);
301 assert(ret == 0);
303 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
304 #else
305 struct timeval tv;
306 int ret;
308 ret = gettimeofday(&tv, NULL);
309 assert(ret == 0);
311 return tv.tv_usec/1000 + tv.tv_sec*1000;
312 #endif
315 void Sleep(ALuint t)
317 struct timespec tv, rem;
318 tv.tv_nsec = (t*1000000)%1000000000;
319 tv.tv_sec = t/1000;
321 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
322 tv = rem;
325 #ifdef HAVE_DLFCN_H
327 void *LoadLib(const char *name)
329 const char *err;
330 void *handle;
332 dlerror();
333 handle = dlopen(name, RTLD_NOW);
334 if((err=dlerror()) != NULL)
335 handle = NULL;
336 return handle;
338 void CloseLib(void *handle)
339 { dlclose(handle); }
340 void *GetSymbol(void *handle, const char *name)
342 const char *err;
343 void *sym;
345 dlerror();
346 sym = dlsym(handle, name);
347 if((err=dlerror()) != NULL)
349 WARN("Failed to load %s: %s\n", name, err);
350 sym = NULL;
352 return sym;
355 #endif
356 #endif
359 void al_print(const char *func, const char *fmt, ...)
361 char str[256];
362 int i;
364 i = snprintf(str, sizeof(str), "AL lib: %s: ", func);
365 if(i < (int)sizeof(str) && i > 0)
367 va_list ap;
368 va_start(ap, fmt);
369 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
370 va_end(ap);
372 str[sizeof(str)-1] = 0;
374 fprintf(LogFile, "%s", str);
375 fflush(LogFile);
379 void SetRTPriority(void)
381 ALboolean failed = AL_FALSE;
383 #ifdef _WIN32
384 if(RTPrioLevel > 0)
385 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
386 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
387 if(RTPrioLevel > 0)
389 struct sched_param param;
390 /* Use the minimum real-time priority possible for now (on Linux this
391 * should be 1 for SCHED_RR) */
392 param.sched_priority = sched_get_priority_min(SCHED_RR);
393 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
395 #else
396 /* Real-time priority not available */
397 failed = (RTPrioLevel>0);
398 #endif
399 if(failed)
400 ERR("Failed to set priority level for thread\n");
404 static void Lock(volatile ALenum *l)
406 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
407 sched_yield();
410 static void Unlock(volatile ALenum *l)
412 ExchangeInt(l, AL_FALSE);
415 void RWLockInit(RWLock *lock)
417 lock->read_count = 0;
418 lock->write_count = 0;
419 lock->read_lock = AL_FALSE;
420 lock->read_entry_lock = AL_FALSE;
421 lock->write_lock = AL_FALSE;
424 void ReadLock(RWLock *lock)
426 Lock(&lock->read_entry_lock);
427 Lock(&lock->read_lock);
428 if(IncrementRef(&lock->read_count) == 1)
429 Lock(&lock->write_lock);
430 Unlock(&lock->read_lock);
431 Unlock(&lock->read_entry_lock);
434 void ReadUnlock(RWLock *lock)
436 if(DecrementRef(&lock->read_count) == 0)
437 Unlock(&lock->write_lock);
440 void WriteLock(RWLock *lock)
442 if(IncrementRef(&lock->write_count) == 1)
443 Lock(&lock->read_lock);
444 Lock(&lock->write_lock);
447 void WriteUnlock(RWLock *lock)
449 Unlock(&lock->write_lock);
450 if(DecrementRef(&lock->write_count) == 0)
451 Unlock(&lock->read_lock);
455 void InitUIntMap(UIntMap *map, ALsizei limit)
457 map->array = NULL;
458 map->size = 0;
459 map->maxsize = 0;
460 map->limit = limit;
461 RWLockInit(&map->lock);
464 void ResetUIntMap(UIntMap *map)
466 WriteLock(&map->lock);
467 free(map->array);
468 map->array = NULL;
469 map->size = 0;
470 map->maxsize = 0;
471 WriteUnlock(&map->lock);
474 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
476 ALsizei pos = 0;
478 WriteLock(&map->lock);
479 if(map->size > 0)
481 ALsizei low = 0;
482 ALsizei high = map->size - 1;
483 while(low < high)
485 ALsizei mid = low + (high-low)/2;
486 if(map->array[mid].key < key)
487 low = mid + 1;
488 else
489 high = mid;
491 if(map->array[low].key < key)
492 low++;
493 pos = low;
496 if(pos == map->size || map->array[pos].key != key)
498 if(map->size == map->limit)
500 WriteUnlock(&map->lock);
501 return AL_OUT_OF_MEMORY;
504 if(map->size == map->maxsize)
506 ALvoid *temp = NULL;
507 ALsizei newsize;
509 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
510 if(newsize >= map->maxsize)
511 temp = realloc(map->array, newsize*sizeof(map->array[0]));
512 if(!temp)
514 WriteUnlock(&map->lock);
515 return AL_OUT_OF_MEMORY;
517 map->array = temp;
518 map->maxsize = newsize;
521 if(pos < map->size)
522 memmove(&map->array[pos+1], &map->array[pos],
523 (map->size-pos)*sizeof(map->array[0]));
524 map->size++;
526 map->array[pos].key = key;
527 map->array[pos].value = value;
528 WriteUnlock(&map->lock);
530 return AL_NO_ERROR;
533 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
535 ALvoid *ptr = NULL;
536 WriteLock(&map->lock);
537 if(map->size > 0)
539 ALsizei low = 0;
540 ALsizei high = map->size - 1;
541 while(low < high)
543 ALsizei mid = low + (high-low)/2;
544 if(map->array[mid].key < key)
545 low = mid + 1;
546 else
547 high = mid;
549 if(map->array[low].key == key)
551 ptr = map->array[low].value;
552 if(low < map->size-1)
553 memmove(&map->array[low], &map->array[low+1],
554 (map->size-1-low)*sizeof(map->array[0]));
555 map->size--;
558 WriteUnlock(&map->lock);
559 return ptr;
562 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
564 ALvoid *ptr = NULL;
565 ReadLock(&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 ptr = map->array[low].value;
581 ReadUnlock(&map->lock);
582 return ptr;