Add wrapper methods to ensure aligned allocations
[openal-soft/openal-hmr.git] / Alc / helpers.c
blob26a32b692966e84ef4317f2ab17a7001b7f4cd73
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 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
84 if(__get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
85 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
86 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
87 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
89 if(!__get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
90 ERR("Failed to get CPU features\n");
91 else
93 #ifdef bit_SSE
94 if((cpuinf[0].regs[3]&bit_SSE))
95 caps |= CPU_CAP_SSE;
96 #endif
99 #endif
100 #endif
101 #ifdef HAVE_NEON
102 /* Assume Neon support if compiled with it */
103 caps |= CPU_CAP_NEON;
104 #endif
106 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
107 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
108 ((!caps)?" -none-":""));
109 CPUCapFlags = caps & capfilter;
113 void *al_malloc(size_t alignment, size_t size)
115 #if defined(HAVE_ALIGNED_ALLOC)
116 size = (size+(alignment-1))&~(alignment-1);
117 return aligned_alloc(alignment, size);
118 #elif defined(HAVE_POSIX_MEMALIGN)
119 void *ret;
120 if(posix_memalign(&ret, alignment, size) == 0)
121 return ret;
122 return NULL;
123 #elif defined(HAVE__ALIGNED_MALLOC)
124 return _aligned_malloc(size, alignment);
125 #else
126 char *ret = malloc(size+alignment);
127 if(ret != NULL)
129 *(ret++) = 0x00;
130 while(((ALintptrEXT)ret&(alignment-1)) != 0)
131 *(ret++) = 0xAA;
133 return ret;
134 #endif
137 void *al_calloc(size_t alignment, size_t size)
139 void *ret = al_malloc(alignment, size);
140 if(ret) memset(ret, 0, size);
141 return ret;
144 void al_free(void *ptr)
146 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN) || defined(HAVE__ALIGNED_MALLOC)
147 free(ptr);
148 #else
149 if(ptr != NULL)
151 char *finder = ptr;
152 do {
153 --finder;
154 } while(*finder == 0xAA);
155 free(finder);
157 return ret;
158 #endif
161 #ifdef _WIN32
162 void pthread_once(pthread_once_t *once, void (*callback)(void))
164 LONG ret;
165 while((ret=InterlockedExchange(once, 1)) == 1)
166 sched_yield();
167 if(ret == 0)
168 callback();
169 InterlockedExchange(once, 2);
173 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
175 *key = TlsAlloc();
176 if(callback)
177 InsertUIntMapEntry(&TlsDestructor, *key, callback);
178 return 0;
181 int pthread_key_delete(pthread_key_t key)
183 InsertUIntMapEntry(&TlsDestructor, key, NULL);
184 TlsFree(key);
185 return 0;
188 void *pthread_getspecific(pthread_key_t key)
189 { return TlsGetValue(key); }
191 int pthread_setspecific(pthread_key_t key, void *val)
193 TlsSetValue(key, val);
194 return 0;
198 void *LoadLib(const char *name)
199 { return LoadLibraryA(name); }
200 void CloseLib(void *handle)
201 { FreeLibrary((HANDLE)handle); }
202 void *GetSymbol(void *handle, const char *name)
204 void *ret;
206 ret = (void*)GetProcAddress((HANDLE)handle, name);
207 if(ret == NULL)
208 ERR("Failed to load %s\n", name);
209 return ret;
212 WCHAR *strdupW(const WCHAR *str)
214 const WCHAR *n;
215 WCHAR *ret;
216 size_t len;
218 n = str;
219 while(*n) n++;
220 len = n - str;
222 ret = calloc(sizeof(WCHAR), len+1);
223 if(ret != NULL)
224 memcpy(ret, str, sizeof(WCHAR)*len);
225 return ret;
228 #else
230 #include <pthread.h>
231 #ifdef HAVE_PTHREAD_NP_H
232 #include <pthread_np.h>
233 #endif
234 #include <sched.h>
236 void InitializeCriticalSection(CRITICAL_SECTION *cs)
238 pthread_mutexattr_t attrib;
239 int ret;
241 ret = pthread_mutexattr_init(&attrib);
242 assert(ret == 0);
244 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
245 #ifdef HAVE_PTHREAD_NP_H
246 if(ret != 0)
247 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
248 #endif
249 assert(ret == 0);
250 ret = pthread_mutex_init(cs, &attrib);
251 assert(ret == 0);
253 pthread_mutexattr_destroy(&attrib);
255 void DeleteCriticalSection(CRITICAL_SECTION *cs)
257 int ret;
258 ret = pthread_mutex_destroy(cs);
259 assert(ret == 0);
261 void EnterCriticalSection(CRITICAL_SECTION *cs)
263 int ret;
264 ret = pthread_mutex_lock(cs);
265 assert(ret == 0);
267 void LeaveCriticalSection(CRITICAL_SECTION *cs)
269 int ret;
270 ret = pthread_mutex_unlock(cs);
271 assert(ret == 0);
274 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
275 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
276 * Additionally, Win32 is supposed to measure the time since Windows started,
277 * as opposed to the actual time. */
278 ALuint timeGetTime(void)
280 #if _POSIX_TIMERS > 0
281 struct timespec ts;
282 int ret = -1;
284 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
285 #if _POSIX_MONOTONIC_CLOCK == 0
286 static int hasmono = 0;
287 if(hasmono > 0 || (hasmono == 0 &&
288 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
289 #endif
290 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
291 #endif
292 if(ret != 0)
293 ret = clock_gettime(CLOCK_REALTIME, &ts);
294 assert(ret == 0);
296 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
297 #else
298 struct timeval tv;
299 int ret;
301 ret = gettimeofday(&tv, NULL);
302 assert(ret == 0);
304 return tv.tv_usec/1000 + tv.tv_sec*1000;
305 #endif
308 void Sleep(ALuint t)
310 struct timespec tv, rem;
311 tv.tv_nsec = (t*1000000)%1000000000;
312 tv.tv_sec = t/1000;
314 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
315 tv = rem;
318 #ifdef HAVE_DLFCN_H
320 void *LoadLib(const char *name)
322 const char *err;
323 void *handle;
325 dlerror();
326 handle = dlopen(name, RTLD_NOW);
327 if((err=dlerror()) != NULL)
328 handle = NULL;
329 return handle;
331 void CloseLib(void *handle)
332 { dlclose(handle); }
333 void *GetSymbol(void *handle, const char *name)
335 const char *err;
336 void *sym;
338 dlerror();
339 sym = dlsym(handle, name);
340 if((err=dlerror()) != NULL)
342 WARN("Failed to load %s: %s\n", name, err);
343 sym = NULL;
345 return sym;
348 #endif
349 #endif
352 void al_print(const char *func, const char *fmt, ...)
354 char str[256];
355 int i;
357 i = snprintf(str, sizeof(str), "AL lib: %s: ", func);
358 if(i < (int)sizeof(str) && i > 0)
360 va_list ap;
361 va_start(ap, fmt);
362 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
363 va_end(ap);
365 str[sizeof(str)-1] = 0;
367 fprintf(LogFile, "%s", str);
368 fflush(LogFile);
372 void SetRTPriority(void)
374 ALboolean failed = AL_FALSE;
376 #ifdef _WIN32
377 if(RTPrioLevel > 0)
378 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
379 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
380 if(RTPrioLevel > 0)
382 struct sched_param param;
383 /* Use the minimum real-time priority possible for now (on Linux this
384 * should be 1 for SCHED_RR) */
385 param.sched_priority = sched_get_priority_min(SCHED_RR);
386 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
388 #else
389 /* Real-time priority not available */
390 failed = (RTPrioLevel>0);
391 #endif
392 if(failed)
393 ERR("Failed to set priority level for thread\n");
397 static void Lock(volatile ALenum *l)
399 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
400 sched_yield();
403 static void Unlock(volatile ALenum *l)
405 ExchangeInt(l, AL_FALSE);
408 void RWLockInit(RWLock *lock)
410 lock->read_count = 0;
411 lock->write_count = 0;
412 lock->read_lock = AL_FALSE;
413 lock->read_entry_lock = AL_FALSE;
414 lock->write_lock = AL_FALSE;
417 void ReadLock(RWLock *lock)
419 Lock(&lock->read_entry_lock);
420 Lock(&lock->read_lock);
421 if(IncrementRef(&lock->read_count) == 1)
422 Lock(&lock->write_lock);
423 Unlock(&lock->read_lock);
424 Unlock(&lock->read_entry_lock);
427 void ReadUnlock(RWLock *lock)
429 if(DecrementRef(&lock->read_count) == 0)
430 Unlock(&lock->write_lock);
433 void WriteLock(RWLock *lock)
435 if(IncrementRef(&lock->write_count) == 1)
436 Lock(&lock->read_lock);
437 Lock(&lock->write_lock);
440 void WriteUnlock(RWLock *lock)
442 Unlock(&lock->write_lock);
443 if(DecrementRef(&lock->write_count) == 0)
444 Unlock(&lock->read_lock);
448 void InitUIntMap(UIntMap *map, ALsizei limit)
450 map->array = NULL;
451 map->size = 0;
452 map->maxsize = 0;
453 map->limit = limit;
454 RWLockInit(&map->lock);
457 void ResetUIntMap(UIntMap *map)
459 WriteLock(&map->lock);
460 free(map->array);
461 map->array = NULL;
462 map->size = 0;
463 map->maxsize = 0;
464 WriteUnlock(&map->lock);
467 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
469 ALsizei pos = 0;
471 WriteLock(&map->lock);
472 if(map->size > 0)
474 ALsizei low = 0;
475 ALsizei high = map->size - 1;
476 while(low < high)
478 ALsizei mid = low + (high-low)/2;
479 if(map->array[mid].key < key)
480 low = mid + 1;
481 else
482 high = mid;
484 if(map->array[low].key < key)
485 low++;
486 pos = low;
489 if(pos == map->size || map->array[pos].key != key)
491 if(map->size == map->limit)
493 WriteUnlock(&map->lock);
494 return AL_OUT_OF_MEMORY;
497 if(map->size == map->maxsize)
499 ALvoid *temp = NULL;
500 ALsizei newsize;
502 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
503 if(newsize >= map->maxsize)
504 temp = realloc(map->array, newsize*sizeof(map->array[0]));
505 if(!temp)
507 WriteUnlock(&map->lock);
508 return AL_OUT_OF_MEMORY;
510 map->array = temp;
511 map->maxsize = newsize;
514 if(pos < map->size)
515 memmove(&map->array[pos+1], &map->array[pos],
516 (map->size-pos)*sizeof(map->array[0]));
517 map->size++;
519 map->array[pos].key = key;
520 map->array[pos].value = value;
521 WriteUnlock(&map->lock);
523 return AL_NO_ERROR;
526 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
528 ALvoid *ptr = NULL;
529 WriteLock(&map->lock);
530 if(map->size > 0)
532 ALsizei low = 0;
533 ALsizei high = map->size - 1;
534 while(low < high)
536 ALsizei mid = low + (high-low)/2;
537 if(map->array[mid].key < key)
538 low = mid + 1;
539 else
540 high = mid;
542 if(map->array[low].key == key)
544 ptr = map->array[low].value;
545 if(low < map->size-1)
546 memmove(&map->array[low], &map->array[low+1],
547 (map->size-1-low)*sizeof(map->array[0]));
548 map->size--;
551 WriteUnlock(&map->lock);
552 return ptr;
555 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
557 ALvoid *ptr = NULL;
558 ReadLock(&map->lock);
559 if(map->size > 0)
561 ALsizei low = 0;
562 ALsizei high = map->size - 1;
563 while(low < high)
565 ALsizei mid = low + (high-low)/2;
566 if(map->array[mid].key < key)
567 low = mid + 1;
568 else
569 high = mid;
571 if(map->array[low].key == key)
572 ptr = map->array[low].value;
574 ReadUnlock(&map->lock);
575 return ptr;