Rename the vector's Max field to Capacity
[openal-soft.git] / Alc / helpers.c
blob69c49db106087cd4069f4eb4ec1e108360cdf993
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 "compat.h"
93 extern inline RefCount IncrementRef(volatile RefCount *ptr);
94 extern inline RefCount DecrementRef(volatile RefCount *ptr);
95 extern inline int ExchangeInt(volatile int *ptr, int newval);
96 extern inline void *ExchangePtr(XchgPtr *ptr, void *newval);
97 extern inline int CompExchangeInt(volatile int *ptr, int oldval, int newval);
98 extern inline void *CompExchangePtr(XchgPtr *ptr, void *oldval, void *newval);
100 extern inline void LockUIntMapRead(UIntMap *map);
101 extern inline void UnlockUIntMapRead(UIntMap *map);
102 extern inline void LockUIntMapWrite(UIntMap *map);
103 extern inline void UnlockUIntMapWrite(UIntMap *map);
105 extern inline ALuint NextPowerOf2(ALuint value);
106 extern inline ALint fastf2i(ALfloat f);
107 extern inline ALuint fastf2u(ALfloat f);
110 ALuint CPUCapFlags = 0;
113 void FillCPUCaps(ALuint capfilter)
115 ALuint caps = 0;
117 /* FIXME: We really should get this for all available CPUs in case different
118 * CPUs have different caps (is that possible on one machine?). */
119 #if defined(HAVE_CPUID_H) && (defined(__i386__) || defined(__x86_64__) || \
120 defined(_M_IX86) || defined(_M_X64))
121 union {
122 unsigned int regs[4];
123 char str[sizeof(unsigned int[4])];
124 } cpuinf[3];
126 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
127 ERR("Failed to get CPUID\n");
128 else
130 unsigned int maxfunc = cpuinf[0].regs[0];
131 unsigned int maxextfunc = 0;
133 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
134 maxextfunc = cpuinf[0].regs[0];
135 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
137 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
138 if(maxextfunc >= 0x80000004 &&
139 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
140 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
141 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
142 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
144 if(maxfunc >= 1 &&
145 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
147 if((cpuinf[0].regs[3]&(1<<25)))
149 caps |= CPU_CAP_SSE;
150 if((cpuinf[0].regs[3]&(1<<26)))
151 caps |= CPU_CAP_SSE2;
155 #elif defined(HAVE_WINDOWS_H)
156 HMODULE k32 = GetModuleHandleA("kernel32.dll");
157 BOOL (WINAPI*IsProcessorFeaturePresent)(DWORD ProcessorFeature);
158 IsProcessorFeaturePresent = (BOOL(WINAPI*)(DWORD))GetProcAddress(k32, "IsProcessorFeaturePresent");
159 if(!IsProcessorFeaturePresent)
160 ERR("IsProcessorFeaturePresent not available; CPU caps not detected\n");
161 else
163 if(IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
165 caps |= CPU_CAP_SSE;
166 if(IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE))
167 caps |= CPU_CAP_SSE2;
170 #endif
171 #ifdef HAVE_NEON
172 /* Assume Neon support if compiled with it */
173 caps |= CPU_CAP_NEON;
174 #endif
176 TRACE("Got caps:%s%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
177 ((caps&CPU_CAP_SSE2)?((capfilter&CPU_CAP_SSE2)?" SSE2":" (SSE2)"):""),
178 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
179 ((!caps)?" -none-":""));
180 CPUCapFlags = caps & capfilter;
184 void *al_malloc(size_t alignment, size_t size)
186 #if defined(HAVE_ALIGNED_ALLOC)
187 size = (size+(alignment-1))&~(alignment-1);
188 return aligned_alloc(alignment, size);
189 #elif defined(HAVE_POSIX_MEMALIGN)
190 void *ret;
191 if(posix_memalign(&ret, alignment, size) == 0)
192 return ret;
193 return NULL;
194 #elif defined(HAVE__ALIGNED_MALLOC)
195 return _aligned_malloc(size, alignment);
196 #else
197 char *ret = malloc(size+alignment);
198 if(ret != NULL)
200 *(ret++) = 0x00;
201 while(((ALintptrEXT)ret&(alignment-1)) != 0)
202 *(ret++) = 0x55;
204 return ret;
205 #endif
208 void *al_calloc(size_t alignment, size_t size)
210 void *ret = al_malloc(alignment, size);
211 if(ret) memset(ret, 0, size);
212 return ret;
215 void al_free(void *ptr)
217 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
218 free(ptr);
219 #elif defined(HAVE__ALIGNED_MALLOC)
220 _aligned_free(ptr);
221 #else
222 if(ptr != NULL)
224 char *finder = ptr;
225 do {
226 --finder;
227 } while(*finder == 0x55);
228 free(finder);
230 #endif
234 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
235 /* Win64 doesn't allow us to set the precision control. */
236 #undef _MCW_PC
237 #define _MCW_PC 0
238 #endif
240 void SetMixerFPUMode(FPUCtl *ctl)
242 #ifdef HAVE_FENV_H
243 fegetenv(STATIC_CAST(fenv_t, ctl));
244 #if defined(__GNUC__) && defined(HAVE_SSE)
245 if((CPUCapFlags&CPU_CAP_SSE))
246 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
247 #endif
249 #ifdef FE_TOWARDZERO
250 fesetround(FE_TOWARDZERO);
251 #endif
252 #if defined(__GNUC__) && defined(HAVE_SSE)
253 if((CPUCapFlags&CPU_CAP_SSE))
255 int sseState = ctl->sse_state;
256 sseState |= 0x6000; /* set round-to-zero */
257 sseState |= 0x8000; /* set flush-to-zero */
258 if((CPUCapFlags&CPU_CAP_SSE2))
259 sseState |= 0x0040; /* set denormals-are-zero */
260 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
262 #endif
264 #elif defined(HAVE___CONTROL87_2)
266 int mode;
267 __control87_2(0, 0, &ctl->state, NULL);
268 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
269 #ifdef HAVE_SSE
270 if((CPUCapFlags&CPU_CAP_SSE))
272 __control87_2(0, 0, NULL, &ctl->sse_state);
273 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
275 #endif
277 #elif defined(HAVE__CONTROLFP)
279 ctl->state = _controlfp(0, 0);
280 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
281 #endif
284 void RestoreFPUMode(const FPUCtl *ctl)
286 #ifdef HAVE_FENV_H
287 fesetenv(STATIC_CAST(fenv_t, ctl));
288 #if defined(__GNUC__) && defined(HAVE_SSE)
289 if((CPUCapFlags&CPU_CAP_SSE))
290 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
291 #endif
293 #elif defined(HAVE___CONTROL87_2)
295 int mode;
296 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
297 #ifdef HAVE_SSE
298 if((CPUCapFlags&CPU_CAP_SSE))
299 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
300 #endif
302 #elif defined(HAVE__CONTROLFP)
304 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
305 #endif
309 #ifdef _WIN32
310 extern inline int alsched_yield(void);
312 void althread_once(althread_once_t *once, void (*callback)(void))
314 LONG ret;
315 while((ret=InterlockedExchange(once, 1)) == 1)
316 alsched_yield();
317 if(ret == 0)
318 callback();
319 InterlockedExchange(once, 2);
323 int althread_key_create(althread_key_t *key, void (*callback)(void*))
325 *key = TlsAlloc();
326 if(callback)
327 InsertUIntMapEntry(&TlsDestructor, *key, callback);
328 return 0;
331 int althread_key_delete(althread_key_t key)
333 InsertUIntMapEntry(&TlsDestructor, key, NULL);
334 TlsFree(key);
335 return 0;
338 void *althread_getspecific(althread_key_t key)
339 { return TlsGetValue(key); }
341 int althread_setspecific(althread_key_t key, void *val)
343 TlsSetValue(key, val);
344 return 0;
348 void *LoadLib(const char *name)
349 { return LoadLibraryA(name); }
350 void CloseLib(void *handle)
351 { FreeLibrary((HANDLE)handle); }
352 void *GetSymbol(void *handle, const char *name)
354 void *ret;
356 ret = (void*)GetProcAddress((HANDLE)handle, name);
357 if(ret == NULL)
358 ERR("Failed to load %s\n", name);
359 return ret;
362 WCHAR *strdupW(const WCHAR *str)
364 const WCHAR *n;
365 WCHAR *ret;
366 size_t len;
368 n = str;
369 while(*n) n++;
370 len = n - str;
372 ret = calloc(sizeof(WCHAR), len+1);
373 if(ret != NULL)
374 memcpy(ret, str, sizeof(WCHAR)*len);
375 return ret;
378 #else
380 #include <pthread.h>
381 #ifdef HAVE_PTHREAD_NP_H
382 #include <pthread_np.h>
383 #endif
384 #include <sched.h>
385 #include <time.h>
386 #include <sys/time.h>
388 void InitializeCriticalSection(CRITICAL_SECTION *cs)
390 pthread_mutexattr_t attrib;
391 int ret;
393 ret = pthread_mutexattr_init(&attrib);
394 assert(ret == 0);
396 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
397 #ifdef HAVE_PTHREAD_NP_H
398 if(ret != 0)
399 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
400 #endif
401 assert(ret == 0);
402 ret = pthread_mutex_init(cs, &attrib);
403 assert(ret == 0);
405 pthread_mutexattr_destroy(&attrib);
407 void DeleteCriticalSection(CRITICAL_SECTION *cs)
409 int ret;
410 ret = pthread_mutex_destroy(cs);
411 assert(ret == 0);
413 void EnterCriticalSection(CRITICAL_SECTION *cs)
415 int ret;
416 ret = pthread_mutex_lock(cs);
417 assert(ret == 0);
419 void LeaveCriticalSection(CRITICAL_SECTION *cs)
421 int ret;
422 ret = pthread_mutex_unlock(cs);
423 assert(ret == 0);
426 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
427 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
428 * Additionally, Win32 is supposed to measure the time since Windows started,
429 * as opposed to the actual time. */
430 ALuint timeGetTime(void)
432 #if _POSIX_TIMERS > 0
433 struct timespec ts;
434 int ret = -1;
436 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
437 #if _POSIX_MONOTONIC_CLOCK == 0
438 static int hasmono = 0;
439 if(hasmono > 0 || (hasmono == 0 &&
440 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
441 #endif
442 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
443 #endif
444 if(ret != 0)
445 ret = clock_gettime(CLOCK_REALTIME, &ts);
446 assert(ret == 0);
448 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
449 #else
450 struct timeval tv;
451 int ret;
453 ret = gettimeofday(&tv, NULL);
454 assert(ret == 0);
456 return tv.tv_usec/1000 + tv.tv_sec*1000;
457 #endif
460 void Sleep(ALuint t)
462 struct timespec tv, rem;
463 tv.tv_nsec = (t*1000000)%1000000000;
464 tv.tv_sec = t/1000;
466 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
467 tv = rem;
470 #ifdef HAVE_DLFCN_H
472 void *LoadLib(const char *name)
474 const char *err;
475 void *handle;
477 dlerror();
478 handle = dlopen(name, RTLD_NOW);
479 if((err=dlerror()) != NULL)
480 handle = NULL;
481 return handle;
483 void CloseLib(void *handle)
484 { dlclose(handle); }
485 void *GetSymbol(void *handle, const char *name)
487 const char *err;
488 void *sym;
490 dlerror();
491 sym = dlsym(handle, name);
492 if((err=dlerror()) != NULL)
494 WARN("Failed to load %s: %s\n", name, err);
495 sym = NULL;
497 return sym;
500 #endif
501 #endif
504 void al_print(const char *type, const char *func, const char *fmt, ...)
506 va_list ap;
508 va_start(ap, fmt);
509 fprintf(LogFile, "AL lib: %s %s: ", type, func);
510 vfprintf(LogFile, fmt, ap);
511 va_end(ap);
513 fflush(LogFile);
517 FILE *OpenDataFile(const char *fname, const char *subdir)
519 char buffer[PATH_MAX] = "";
520 FILE *f;
522 #ifdef _WIN32
523 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
524 int i;
526 /* If the path is absolute, open it directly. */
527 if(fname[0] != '\0' && fname[1] == ':' && (fname[2] == '\\' || fname[2] == '/'))
529 if((f=fopen(fname, "rb")) != NULL)
531 TRACE("Opened %s\n", fname);
532 return f;
534 WARN("Could not open %s\n", fname);
535 return NULL;
538 for(i = 0;i < 2;i++)
540 size_t len;
542 if(SHGetSpecialFolderPathA(NULL, buffer, ids[i], FALSE) == FALSE)
543 continue;
545 len = strlen(buffer);
546 if(len > 0 && (buffer[len-1] == '\\' || buffer[len-1] == '/'))
547 buffer[--len] = '\0';
548 snprintf(buffer+len, sizeof(buffer)-len, "/%s/%s", subdir, fname);
549 len = strlen(buffer);
550 while(len > 0)
552 --len;
553 if(buffer[len] == '/')
554 buffer[len] = '\\';
557 if((f=fopen(buffer, "rb")) != NULL)
559 TRACE("Opened %s\n", buffer);
560 return f;
562 WARN("Could not open %s\n", buffer);
564 #else
565 const char *str, *next;
567 if(fname[0] == '/')
569 if((f=fopen(fname, "rb")) != NULL)
571 TRACE("Opened %s\n", fname);
572 return f;
574 WARN("Could not open %s\n", fname);
575 return NULL;
578 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
579 snprintf(buffer, sizeof(buffer), "%s/%s/%s", str, subdir, fname);
580 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
581 snprintf(buffer, sizeof(buffer), "%s/.local/share/%s/%s", str, subdir, fname);
582 if(buffer[0])
584 if((f=fopen(buffer, "rb")) != NULL)
586 TRACE("Opened %s\n", buffer);
587 return f;
589 WARN("Could not open %s\n", buffer);
592 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
593 str = " /usr/local/share/:/usr/share/";
595 next = str;
596 while((str=next) != NULL && str[0] != '\0')
598 size_t len;
599 next = strchr(str, ':');
601 if(!next)
602 len = strlen(str);
603 else
605 len = next - str;
606 next++;
609 if(len > sizeof(buffer)-1)
610 len = sizeof(buffer)-1;
611 strncpy(buffer, str, len);
612 buffer[len] = '\0';
613 snprintf(buffer+len, sizeof(buffer)-len, "/%s/%s", subdir, fname);
615 if((f=fopen(buffer, "rb")) != NULL)
617 TRACE("Opened %s\n", buffer);
618 return f;
620 WARN("Could not open %s\n", buffer);
622 #endif
624 return NULL;
628 void SetRTPriority(void)
630 ALboolean failed = AL_FALSE;
632 #ifdef _WIN32
633 if(RTPrioLevel > 0)
634 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
635 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
636 if(RTPrioLevel > 0)
638 struct sched_param param;
639 /* Use the minimum real-time priority possible for now (on Linux this
640 * should be 1 for SCHED_RR) */
641 param.sched_priority = sched_get_priority_min(SCHED_RR);
642 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
644 #else
645 /* Real-time priority not available */
646 failed = (RTPrioLevel>0);
647 #endif
648 if(failed)
649 ERR("Failed to set priority level for thread\n");
653 static void Lock(volatile ALenum *l)
655 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
656 alsched_yield();
659 static void Unlock(volatile ALenum *l)
661 ExchangeInt(l, AL_FALSE);
664 void RWLockInit(RWLock *lock)
666 lock->read_count = 0;
667 lock->write_count = 0;
668 lock->read_lock = AL_FALSE;
669 lock->read_entry_lock = AL_FALSE;
670 lock->write_lock = AL_FALSE;
673 void ReadLock(RWLock *lock)
675 Lock(&lock->read_entry_lock);
676 Lock(&lock->read_lock);
677 if(IncrementRef(&lock->read_count) == 1)
678 Lock(&lock->write_lock);
679 Unlock(&lock->read_lock);
680 Unlock(&lock->read_entry_lock);
683 void ReadUnlock(RWLock *lock)
685 if(DecrementRef(&lock->read_count) == 0)
686 Unlock(&lock->write_lock);
689 void WriteLock(RWLock *lock)
691 if(IncrementRef(&lock->write_count) == 1)
692 Lock(&lock->read_lock);
693 Lock(&lock->write_lock);
696 void WriteUnlock(RWLock *lock)
698 Unlock(&lock->write_lock);
699 if(DecrementRef(&lock->write_count) == 0)
700 Unlock(&lock->read_lock);
704 ALboolean vector_reserve(void *ptr, size_t orig_count, size_t base_size, size_t obj_count, size_t obj_size)
706 if(orig_count < obj_count)
708 vector_ *vecptr = ptr;
709 void *temp;
711 /* Need to be explicit with the caller type's base size, because it
712 * could have extra padding before the start of the array (that is,
713 * sizeof(*vector_) may not equal base_size). */
714 temp = realloc(*vecptr, base_size + obj_size*obj_count);
715 if(temp == NULL) return AL_FALSE;
717 *vecptr = temp;
718 (*vecptr)->Capacity = obj_count;
720 return AL_TRUE;
724 void InitUIntMap(UIntMap *map, ALsizei limit)
726 map->array = NULL;
727 map->size = 0;
728 map->maxsize = 0;
729 map->limit = limit;
730 RWLockInit(&map->lock);
733 void ResetUIntMap(UIntMap *map)
735 WriteLock(&map->lock);
736 free(map->array);
737 map->array = NULL;
738 map->size = 0;
739 map->maxsize = 0;
740 WriteUnlock(&map->lock);
743 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
745 ALsizei pos = 0;
747 WriteLock(&map->lock);
748 if(map->size > 0)
750 ALsizei low = 0;
751 ALsizei high = map->size - 1;
752 while(low < high)
754 ALsizei mid = low + (high-low)/2;
755 if(map->array[mid].key < key)
756 low = mid + 1;
757 else
758 high = mid;
760 if(map->array[low].key < key)
761 low++;
762 pos = low;
765 if(pos == map->size || map->array[pos].key != key)
767 if(map->size == map->limit)
769 WriteUnlock(&map->lock);
770 return AL_OUT_OF_MEMORY;
773 if(map->size == map->maxsize)
775 ALvoid *temp = NULL;
776 ALsizei newsize;
778 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
779 if(newsize >= map->maxsize)
780 temp = realloc(map->array, newsize*sizeof(map->array[0]));
781 if(!temp)
783 WriteUnlock(&map->lock);
784 return AL_OUT_OF_MEMORY;
786 map->array = temp;
787 map->maxsize = newsize;
790 if(pos < map->size)
791 memmove(&map->array[pos+1], &map->array[pos],
792 (map->size-pos)*sizeof(map->array[0]));
793 map->size++;
795 map->array[pos].key = key;
796 map->array[pos].value = value;
797 WriteUnlock(&map->lock);
799 return AL_NO_ERROR;
802 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
804 ALvoid *ptr = NULL;
805 WriteLock(&map->lock);
806 if(map->size > 0)
808 ALsizei low = 0;
809 ALsizei high = map->size - 1;
810 while(low < high)
812 ALsizei mid = low + (high-low)/2;
813 if(map->array[mid].key < key)
814 low = mid + 1;
815 else
816 high = mid;
818 if(map->array[low].key == key)
820 ptr = map->array[low].value;
821 if(low < map->size-1)
822 memmove(&map->array[low], &map->array[low+1],
823 (map->size-1-low)*sizeof(map->array[0]));
824 map->size--;
827 WriteUnlock(&map->lock);
828 return ptr;
831 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
833 ALvoid *ptr = NULL;
834 ReadLock(&map->lock);
835 if(map->size > 0)
837 ALsizei low = 0;
838 ALsizei high = map->size - 1;
839 while(low < high)
841 ALsizei mid = low + (high-low)/2;
842 if(map->array[mid].key < key)
843 low = mid + 1;
844 else
845 high = mid;
847 if(map->array[low].key == key)
848 ptr = map->array[low].value;
850 ReadUnlock(&map->lock);
851 return ptr;