Add an al_string type and use it for the device lists
[openal-soft.git] / Alc / helpers.c
blob77bfb3532556dcd0de15c3883cf3f9509bd3871a
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 #ifdef _WIN32
22 #ifdef __MINGW32__
23 #define _WIN32_IE 0x501
24 #else
25 #define _WIN32_IE 0x400
26 #endif
27 #endif
29 #include "config.h"
31 #include <stdlib.h>
32 #include <time.h>
33 #include <errno.h>
34 #include <stdarg.h>
35 #ifdef HAVE_MALLOC_H
36 #include <malloc.h>
37 #endif
39 #ifndef AL_NO_UID_DEFS
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>
61 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
62 #endif
63 #endif
64 #endif /* AL_NO_UID_DEFS */
66 #ifdef HAVE_DLFCN_H
67 #include <dlfcn.h>
68 #endif
69 #ifdef HAVE_CPUID_H
70 #include <cpuid.h>
71 #endif
72 #ifdef HAVE_SYS_SYSCONF_H
73 #include <sys/sysconf.h>
74 #endif
75 #ifdef HAVE_FLOAT_H
76 #include <float.h>
77 #endif
78 #ifdef HAVE_IEEEFP_H
79 #include <ieeefp.h>
80 #endif
82 #ifdef _WIN32_IE
83 #include <shlobj.h>
84 #endif
86 #include "alMain.h"
87 #include "atomic.h"
88 #include "uintmap.h"
89 #include "vector.h"
90 #include "alstring.h"
91 #include "compat.h"
94 extern inline RefCount IncrementRef(volatile RefCount *ptr);
95 extern inline RefCount DecrementRef(volatile RefCount *ptr);
96 extern inline int ExchangeInt(volatile int *ptr, int newval);
97 extern inline void *ExchangePtr(XchgPtr *ptr, void *newval);
98 extern inline int CompExchangeInt(volatile int *ptr, int oldval, int newval);
99 extern inline void *CompExchangePtr(XchgPtr *ptr, void *oldval, void *newval);
101 extern inline void LockUIntMapRead(UIntMap *map);
102 extern inline void UnlockUIntMapRead(UIntMap *map);
103 extern inline void LockUIntMapWrite(UIntMap *map);
104 extern inline void UnlockUIntMapWrite(UIntMap *map);
106 extern inline ALuint NextPowerOf2(ALuint value);
107 extern inline ALint fastf2i(ALfloat f);
108 extern inline ALuint fastf2u(ALfloat f);
111 ALuint CPUCapFlags = 0;
114 void FillCPUCaps(ALuint capfilter)
116 ALuint caps = 0;
118 /* FIXME: We really should get this for all available CPUs in case different
119 * CPUs have different caps (is that possible on one machine?). */
120 #if defined(HAVE_CPUID_H) && (defined(__i386__) || defined(__x86_64__) || \
121 defined(_M_IX86) || defined(_M_X64))
122 union {
123 unsigned int regs[4];
124 char str[sizeof(unsigned int[4])];
125 } cpuinf[3];
127 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
128 ERR("Failed to get CPUID\n");
129 else
131 unsigned int maxfunc = cpuinf[0].regs[0];
132 unsigned int maxextfunc = 0;
134 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
135 maxextfunc = cpuinf[0].regs[0];
136 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
138 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
139 if(maxextfunc >= 0x80000004 &&
140 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
141 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
142 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
143 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
145 if(maxfunc >= 1 &&
146 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
148 if((cpuinf[0].regs[3]&(1<<25)))
150 caps |= CPU_CAP_SSE;
151 if((cpuinf[0].regs[3]&(1<<26)))
152 caps |= CPU_CAP_SSE2;
156 #elif defined(HAVE_WINDOWS_H)
157 HMODULE k32 = GetModuleHandleA("kernel32.dll");
158 BOOL (WINAPI*IsProcessorFeaturePresent)(DWORD ProcessorFeature);
159 IsProcessorFeaturePresent = (BOOL(WINAPI*)(DWORD))GetProcAddress(k32, "IsProcessorFeaturePresent");
160 if(!IsProcessorFeaturePresent)
161 ERR("IsProcessorFeaturePresent not available; CPU caps not detected\n");
162 else
164 if(IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
166 caps |= CPU_CAP_SSE;
167 if(IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE))
168 caps |= CPU_CAP_SSE2;
171 #endif
172 #ifdef HAVE_NEON
173 /* Assume Neon support if compiled with it */
174 caps |= CPU_CAP_NEON;
175 #endif
177 TRACE("Got caps:%s%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
178 ((caps&CPU_CAP_SSE2)?((capfilter&CPU_CAP_SSE2)?" SSE2":" (SSE2)"):""),
179 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
180 ((!caps)?" -none-":""));
181 CPUCapFlags = caps & capfilter;
185 void *al_malloc(size_t alignment, size_t size)
187 #if defined(HAVE_ALIGNED_ALLOC)
188 size = (size+(alignment-1))&~(alignment-1);
189 return aligned_alloc(alignment, size);
190 #elif defined(HAVE_POSIX_MEMALIGN)
191 void *ret;
192 if(posix_memalign(&ret, alignment, size) == 0)
193 return ret;
194 return NULL;
195 #elif defined(HAVE__ALIGNED_MALLOC)
196 return _aligned_malloc(size, alignment);
197 #else
198 char *ret = malloc(size+alignment);
199 if(ret != NULL)
201 *(ret++) = 0x00;
202 while(((ALintptrEXT)ret&(alignment-1)) != 0)
203 *(ret++) = 0x55;
205 return ret;
206 #endif
209 void *al_calloc(size_t alignment, size_t size)
211 void *ret = al_malloc(alignment, size);
212 if(ret) memset(ret, 0, size);
213 return ret;
216 void al_free(void *ptr)
218 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
219 free(ptr);
220 #elif defined(HAVE__ALIGNED_MALLOC)
221 _aligned_free(ptr);
222 #else
223 if(ptr != NULL)
225 char *finder = ptr;
226 do {
227 --finder;
228 } while(*finder == 0x55);
229 free(finder);
231 #endif
235 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
236 /* Win64 doesn't allow us to set the precision control. */
237 #undef _MCW_PC
238 #define _MCW_PC 0
239 #endif
241 void SetMixerFPUMode(FPUCtl *ctl)
243 #ifdef HAVE_FENV_H
244 fegetenv(STATIC_CAST(fenv_t, ctl));
245 #if defined(__GNUC__) && defined(HAVE_SSE)
246 if((CPUCapFlags&CPU_CAP_SSE))
247 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
248 #endif
250 #ifdef FE_TOWARDZERO
251 fesetround(FE_TOWARDZERO);
252 #endif
253 #if defined(__GNUC__) && defined(HAVE_SSE)
254 if((CPUCapFlags&CPU_CAP_SSE))
256 int sseState = ctl->sse_state;
257 sseState |= 0x6000; /* set round-to-zero */
258 sseState |= 0x8000; /* set flush-to-zero */
259 if((CPUCapFlags&CPU_CAP_SSE2))
260 sseState |= 0x0040; /* set denormals-are-zero */
261 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
263 #endif
265 #elif defined(HAVE___CONTROL87_2)
267 int mode;
268 __control87_2(0, 0, &ctl->state, NULL);
269 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
270 #ifdef HAVE_SSE
271 if((CPUCapFlags&CPU_CAP_SSE))
273 __control87_2(0, 0, NULL, &ctl->sse_state);
274 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
276 #endif
278 #elif defined(HAVE__CONTROLFP)
280 ctl->state = _controlfp(0, 0);
281 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
282 #endif
285 void RestoreFPUMode(const FPUCtl *ctl)
287 #ifdef HAVE_FENV_H
288 fesetenv(STATIC_CAST(fenv_t, ctl));
289 #if defined(__GNUC__) && defined(HAVE_SSE)
290 if((CPUCapFlags&CPU_CAP_SSE))
291 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
292 #endif
294 #elif defined(HAVE___CONTROL87_2)
296 int mode;
297 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
298 #ifdef HAVE_SSE
299 if((CPUCapFlags&CPU_CAP_SSE))
300 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
301 #endif
303 #elif defined(HAVE__CONTROLFP)
305 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
306 #endif
310 #ifdef _WIN32
311 extern inline int alsched_yield(void);
313 void althread_once(althread_once_t *once, void (*callback)(void))
315 LONG ret;
316 while((ret=InterlockedExchange(once, 1)) == 1)
317 alsched_yield();
318 if(ret == 0)
319 callback();
320 InterlockedExchange(once, 2);
324 int althread_key_create(althread_key_t *key, void (*callback)(void*))
326 *key = TlsAlloc();
327 if(callback)
328 InsertUIntMapEntry(&TlsDestructor, *key, callback);
329 return 0;
332 int althread_key_delete(althread_key_t key)
334 InsertUIntMapEntry(&TlsDestructor, key, NULL);
335 TlsFree(key);
336 return 0;
339 void *althread_getspecific(althread_key_t key)
340 { return TlsGetValue(key); }
342 int althread_setspecific(althread_key_t key, void *val)
344 TlsSetValue(key, val);
345 return 0;
349 void *LoadLib(const char *name)
350 { return LoadLibraryA(name); }
351 void CloseLib(void *handle)
352 { FreeLibrary((HANDLE)handle); }
353 void *GetSymbol(void *handle, const char *name)
355 void *ret;
357 ret = (void*)GetProcAddress((HANDLE)handle, name);
358 if(ret == NULL)
359 ERR("Failed to load %s\n", name);
360 return ret;
363 WCHAR *strdupW(const WCHAR *str)
365 const WCHAR *n;
366 WCHAR *ret;
367 size_t len;
369 n = str;
370 while(*n) n++;
371 len = n - str;
373 ret = calloc(sizeof(WCHAR), len+1);
374 if(ret != NULL)
375 memcpy(ret, str, sizeof(WCHAR)*len);
376 return ret;
379 static WCHAR *FromUTF8(const char *str)
381 WCHAR *out = NULL;
382 int len;
384 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
386 out = calloc(sizeof(WCHAR), len);
387 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
389 return out;
392 FILE *al_fopen(const char *fname, const char *mode)
394 WCHAR *wname=NULL, *wmode=NULL;
395 FILE *file = NULL;
397 wname = FromUTF8(fname);
398 wmode = FromUTF8(mode);
399 if(!wname)
400 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
401 else if(!wmode)
402 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
403 else
404 file = _wfopen(wname, wmode);
406 free(wname);
407 free(wmode);
409 return file;
412 #else
414 #include <pthread.h>
415 #ifdef HAVE_PTHREAD_NP_H
416 #include <pthread_np.h>
417 #endif
418 #include <sched.h>
419 #include <time.h>
420 #include <sys/time.h>
422 void InitializeCriticalSection(CRITICAL_SECTION *cs)
424 pthread_mutexattr_t attrib;
425 int ret;
427 ret = pthread_mutexattr_init(&attrib);
428 assert(ret == 0);
430 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
431 #ifdef HAVE_PTHREAD_NP_H
432 if(ret != 0)
433 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
434 #endif
435 assert(ret == 0);
436 ret = pthread_mutex_init(cs, &attrib);
437 assert(ret == 0);
439 pthread_mutexattr_destroy(&attrib);
441 void DeleteCriticalSection(CRITICAL_SECTION *cs)
443 int ret;
444 ret = pthread_mutex_destroy(cs);
445 assert(ret == 0);
447 void EnterCriticalSection(CRITICAL_SECTION *cs)
449 int ret;
450 ret = pthread_mutex_lock(cs);
451 assert(ret == 0);
453 void LeaveCriticalSection(CRITICAL_SECTION *cs)
455 int ret;
456 ret = pthread_mutex_unlock(cs);
457 assert(ret == 0);
460 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
461 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
462 * Additionally, Win32 is supposed to measure the time since Windows started,
463 * as opposed to the actual time. */
464 ALuint timeGetTime(void)
466 #if _POSIX_TIMERS > 0
467 struct timespec ts;
468 int ret = -1;
470 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
471 #if _POSIX_MONOTONIC_CLOCK == 0
472 static int hasmono = 0;
473 if(hasmono > 0 || (hasmono == 0 &&
474 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
475 #endif
476 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
477 #endif
478 if(ret != 0)
479 ret = clock_gettime(CLOCK_REALTIME, &ts);
480 assert(ret == 0);
482 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
483 #else
484 struct timeval tv;
485 int ret;
487 ret = gettimeofday(&tv, NULL);
488 assert(ret == 0);
490 return tv.tv_usec/1000 + tv.tv_sec*1000;
491 #endif
494 void Sleep(ALuint t)
496 struct timespec tv, rem;
497 tv.tv_nsec = (t*1000000)%1000000000;
498 tv.tv_sec = t/1000;
500 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
501 tv = rem;
504 #ifdef HAVE_DLFCN_H
506 void *LoadLib(const char *name)
508 const char *err;
509 void *handle;
511 dlerror();
512 handle = dlopen(name, RTLD_NOW);
513 if((err=dlerror()) != NULL)
514 handle = NULL;
515 return handle;
517 void CloseLib(void *handle)
518 { dlclose(handle); }
519 void *GetSymbol(void *handle, const char *name)
521 const char *err;
522 void *sym;
524 dlerror();
525 sym = dlsym(handle, name);
526 if((err=dlerror()) != NULL)
528 WARN("Failed to load %s: %s\n", name, err);
529 sym = NULL;
531 return sym;
534 #endif
535 #endif
538 void al_print(const char *type, const char *func, const char *fmt, ...)
540 va_list ap;
542 va_start(ap, fmt);
543 fprintf(LogFile, "AL lib: %s %s: ", type, func);
544 vfprintf(LogFile, fmt, ap);
545 va_end(ap);
547 fflush(LogFile);
550 #ifdef _WIN32
551 FILE *OpenDataFile(const char *fname, const char *subdir)
553 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
554 WCHAR *wname=NULL, *wsubdir=NULL;
555 int i;
557 /* If the path is absolute, open it directly. */
558 if(fname[0] != '\0' && fname[1] == ':' && (fname[2] == '\\' || fname[2] == '/'))
560 FILE *f;
561 if((f=al_fopen(fname, "rb")) != NULL)
563 TRACE("Opened %s\n", fname);
564 return f;
566 WARN("Could not open %s\n", fname);
567 return NULL;
570 wname = FromUTF8(fname);
571 wsubdir = FromUTF8(subdir);
572 if(!wname)
573 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
574 else if(!wsubdir)
575 ERR("Failed to convert UTF-8 subdir: \"%s\"\n", subdir);
576 else for(i = 0;i < 2;i++)
578 WCHAR buffer[PATH_MAX];
579 size_t len;
580 FILE *f;
582 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) == FALSE)
583 continue;
585 len = lstrlenW(buffer);
586 if(len > 0 && (buffer[len-1] == '\\' || buffer[len-1] == '/'))
587 buffer[--len] = '\0';
588 _snwprintf(buffer+len, PATH_MAX-len, L"/%ls/%ls", wsubdir, wname);
589 len = lstrlenW(buffer);
590 while(len > 0)
592 --len;
593 if(buffer[len] == '/')
594 buffer[len] = '\\';
597 if((f=_wfopen(buffer, L"rb")) != NULL)
599 TRACE("Opened %ls\n", buffer);
600 return f;
602 WARN("Could not open %ls\n", buffer);
604 free(wname);
605 free(wsubdir);
607 return NULL;
609 #else
610 FILE *OpenDataFile(const char *fname, const char *subdir)
612 char buffer[PATH_MAX] = "";
613 const char *str, *next;
614 FILE *f;
616 if(fname[0] == '/')
618 if((f=al_fopen(fname, "rb")) != NULL)
620 TRACE("Opened %s\n", fname);
621 return f;
623 WARN("Could not open %s\n", fname);
624 return NULL;
627 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
628 snprintf(buffer, sizeof(buffer), "%s/%s/%s", str, subdir, fname);
629 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
630 snprintf(buffer, sizeof(buffer), "%s/.local/share/%s/%s", str, subdir, fname);
631 if(buffer[0])
633 if((f=al_fopen(buffer, "rb")) != NULL)
635 TRACE("Opened %s\n", buffer);
636 return f;
638 WARN("Could not open %s\n", buffer);
641 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
642 str = " /usr/local/share/:/usr/share/";
644 next = str;
645 while((str=next) != NULL && str[0] != '\0')
647 size_t len;
648 next = strchr(str, ':');
650 if(!next)
651 len = strlen(str);
652 else
654 len = next - str;
655 next++;
658 if(len > sizeof(buffer)-1)
659 len = sizeof(buffer)-1;
660 strncpy(buffer, str, len);
661 buffer[len] = '\0';
662 snprintf(buffer+len, sizeof(buffer)-len, "/%s/%s", subdir, fname);
664 if((f=al_fopen(buffer, "rb")) != NULL)
666 TRACE("Opened %s\n", buffer);
667 return f;
669 WARN("Could not open %s\n", buffer);
672 return NULL;
674 #endif
677 void SetRTPriority(void)
679 ALboolean failed = AL_FALSE;
681 #ifdef _WIN32
682 if(RTPrioLevel > 0)
683 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
684 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
685 if(RTPrioLevel > 0)
687 struct sched_param param;
688 /* Use the minimum real-time priority possible for now (on Linux this
689 * should be 1 for SCHED_RR) */
690 param.sched_priority = sched_get_priority_min(SCHED_RR);
691 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
693 #else
694 /* Real-time priority not available */
695 failed = (RTPrioLevel>0);
696 #endif
697 if(failed)
698 ERR("Failed to set priority level for thread\n");
702 static void Lock(volatile ALenum *l)
704 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
705 alsched_yield();
708 static void Unlock(volatile ALenum *l)
710 ExchangeInt(l, AL_FALSE);
713 void RWLockInit(RWLock *lock)
715 lock->read_count = 0;
716 lock->write_count = 0;
717 lock->read_lock = AL_FALSE;
718 lock->read_entry_lock = AL_FALSE;
719 lock->write_lock = AL_FALSE;
722 void ReadLock(RWLock *lock)
724 Lock(&lock->read_entry_lock);
725 Lock(&lock->read_lock);
726 if(IncrementRef(&lock->read_count) == 1)
727 Lock(&lock->write_lock);
728 Unlock(&lock->read_lock);
729 Unlock(&lock->read_entry_lock);
732 void ReadUnlock(RWLock *lock)
734 if(DecrementRef(&lock->read_count) == 0)
735 Unlock(&lock->write_lock);
738 void WriteLock(RWLock *lock)
740 if(IncrementRef(&lock->write_count) == 1)
741 Lock(&lock->read_lock);
742 Lock(&lock->write_lock);
745 void WriteUnlock(RWLock *lock)
747 Unlock(&lock->write_lock);
748 if(DecrementRef(&lock->write_count) == 0)
749 Unlock(&lock->read_lock);
753 ALboolean vector_reserve(void *ptr, size_t orig_count, size_t base_size, size_t obj_count, size_t obj_size, ALboolean exact)
755 if(orig_count < obj_count)
757 vector_ *vecptr = ptr;
758 void *temp;
760 /* Limit vector sizes to the greatest power-of-two value that an
761 * ALsizei can hold. */
762 if(obj_count > (INT_MAX>>1)+1)
763 return AL_FALSE;
765 /* Use the next power-of-2 size if we don't need to allocate the exact
766 * amount. This is preferred when regularly increasing the vector since
767 * it means fewer reallocations. Though it means it also wastes some
768 * memory. */
769 if(exact == AL_FALSE)
770 obj_count = NextPowerOf2((ALuint)obj_count);
772 /* Need to be explicit with the caller type's base size, because it
773 * could have extra padding before the start of the array (that is,
774 * sizeof(*vector_) may not equal base_size). */
775 temp = realloc(*vecptr, base_size + obj_size*obj_count);
776 if(temp == NULL) return AL_FALSE;
778 *vecptr = temp;
779 (*vecptr)->Capacity = (ALsizei)obj_count;
781 return AL_TRUE;
784 ALboolean vector_resize(void *ptr, size_t base_size, size_t obj_count, size_t obj_size)
786 vector_ *vecptr = ptr;
787 if(!vector_reserve(vecptr, (*vecptr)->Capacity, base_size, obj_count, obj_size, AL_TRUE))
788 return AL_FALSE;
789 (*vecptr)->Size = (ALsizei)obj_count;
790 return AL_TRUE;
794 extern inline ALsizei al_string_length(const_al_string str);
795 extern inline ALsizei al_string_empty(const_al_string str);
796 extern inline const al_string_char_type *al_string_get_cstr(const_al_string str);
798 void al_string_clear(al_string *str)
800 /* Reserve one more character than the total size of the string. This is to
801 * ensure we have space to add a null terminator in the string data so it
802 * can be used as a C-style string. */
803 VECTOR_RESERVE(*str, 1);
804 VECTOR_RESIZE(*str, 0);
805 *VECTOR_ITER_END(*str) = 0;
808 void al_string_copy(al_string *str, const_al_string from)
810 ALsizei len = VECTOR_SIZE(from);
811 VECTOR_RESERVE(*str, len+1);
812 VECTOR_RESIZE(*str, len);
813 memcpy(&VECTOR_FRONT(*str), &VECTOR_FRONT(from),
814 len*sizeof(al_string_char_type));
815 *VECTOR_ITER_END(*str) = 0;
818 void al_string_copy_cstr(al_string *str, const al_string_char_type *from)
820 ALsizei len = strlen(from);
821 VECTOR_RESERVE(*str, len+1);
822 VECTOR_RESIZE(*str, len);
823 memcpy(&VECTOR_FRONT(*str), from, len*sizeof(al_string_char_type));
824 *VECTOR_ITER_END(*str) = 0;
827 void al_string_append_char(al_string *str, const al_string_char_type c)
829 VECTOR_RESERVE(*str, al_string_length(*str)+2);
830 VECTOR_PUSH_BACK(*str, c);
831 *VECTOR_ITER_END(*str) = 0;
834 void al_string_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
836 ptrdiff_t len = to - from;
837 if(len != 0)
839 VECTOR_RESERVE(*str, al_string_length(*str)+len+1);
840 VECTOR_RESIZE(*str, al_string_length(*str)+len);
841 memcpy(VECTOR_ITER_END(*str)-len, from, len);
842 *VECTOR_ITER_END(*str) = 0;
848 void InitUIntMap(UIntMap *map, ALsizei limit)
850 map->array = NULL;
851 map->size = 0;
852 map->maxsize = 0;
853 map->limit = limit;
854 RWLockInit(&map->lock);
857 void ResetUIntMap(UIntMap *map)
859 WriteLock(&map->lock);
860 free(map->array);
861 map->array = NULL;
862 map->size = 0;
863 map->maxsize = 0;
864 WriteUnlock(&map->lock);
867 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
869 ALsizei pos = 0;
871 WriteLock(&map->lock);
872 if(map->size > 0)
874 ALsizei low = 0;
875 ALsizei high = map->size - 1;
876 while(low < high)
878 ALsizei mid = low + (high-low)/2;
879 if(map->array[mid].key < key)
880 low = mid + 1;
881 else
882 high = mid;
884 if(map->array[low].key < key)
885 low++;
886 pos = low;
889 if(pos == map->size || map->array[pos].key != key)
891 if(map->size == map->limit)
893 WriteUnlock(&map->lock);
894 return AL_OUT_OF_MEMORY;
897 if(map->size == map->maxsize)
899 ALvoid *temp = NULL;
900 ALsizei newsize;
902 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
903 if(newsize >= map->maxsize)
904 temp = realloc(map->array, newsize*sizeof(map->array[0]));
905 if(!temp)
907 WriteUnlock(&map->lock);
908 return AL_OUT_OF_MEMORY;
910 map->array = temp;
911 map->maxsize = newsize;
914 if(pos < map->size)
915 memmove(&map->array[pos+1], &map->array[pos],
916 (map->size-pos)*sizeof(map->array[0]));
917 map->size++;
919 map->array[pos].key = key;
920 map->array[pos].value = value;
921 WriteUnlock(&map->lock);
923 return AL_NO_ERROR;
926 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
928 ALvoid *ptr = NULL;
929 WriteLock(&map->lock);
930 if(map->size > 0)
932 ALsizei low = 0;
933 ALsizei high = map->size - 1;
934 while(low < high)
936 ALsizei mid = low + (high-low)/2;
937 if(map->array[mid].key < key)
938 low = mid + 1;
939 else
940 high = mid;
942 if(map->array[low].key == key)
944 ptr = map->array[low].value;
945 if(low < map->size-1)
946 memmove(&map->array[low], &map->array[low+1],
947 (map->size-1-low)*sizeof(map->array[0]));
948 map->size--;
951 WriteUnlock(&map->lock);
952 return ptr;
955 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
957 ALvoid *ptr = NULL;
958 ReadLock(&map->lock);
959 if(map->size > 0)
961 ALsizei low = 0;
962 ALsizei high = map->size - 1;
963 while(low < high)
965 ALsizei mid = low + (high-low)/2;
966 if(map->array[mid].key < key)
967 low = mid + 1;
968 else
969 high = mid;
971 if(map->array[low].key == key)
972 ptr = map->array[low].value;
974 ReadUnlock(&map->lock);
975 return ptr;