helpers.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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.
  8. *
  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.
  13. *
  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
  19. */
  20. #include "config.h"
  21. #include <stdlib.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include <stdarg.h>
  25. #ifdef HAVE_MALLOC_H
  26. #include <malloc.h>
  27. #endif
  28. #ifndef AL_NO_UID_DEFS
  29. #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
  30. #define INITGUID
  31. #include <windows.h>
  32. #ifdef HAVE_GUIDDEF_H
  33. #include <guiddef.h>
  34. #else
  35. #include <initguid.h>
  36. #endif
  37. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
  38. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
  39. DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
  40. DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
  41. DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
  42. DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
  43. DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
  44. #ifdef HAVE_MMDEVAPI
  45. #include <devpropdef.h>
  46. DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
  47. #endif
  48. #endif
  49. #endif /* AL_NO_UID_DEFS */
  50. #ifdef HAVE_DLFCN_H
  51. #include <dlfcn.h>
  52. #endif
  53. #ifdef HAVE_CPUID_H
  54. #include <cpuid.h>
  55. #endif
  56. #ifdef HAVE_SYS_SYSCONF_H
  57. #include <sys/sysconf.h>
  58. #endif
  59. #ifdef HAVE_FLOAT_H
  60. #include <float.h>
  61. #endif
  62. #ifdef HAVE_IEEEFP_H
  63. #include <ieeefp.h>
  64. #endif
  65. #include "alMain.h"
  66. #include "atomic.h"
  67. #include "uintmap.h"
  68. #include "compat.h"
  69. extern inline RefCount IncrementRef(volatile RefCount *ptr);
  70. extern inline RefCount DecrementRef(volatile RefCount *ptr);
  71. extern inline int ExchangeInt(volatile int *ptr, int newval);
  72. extern inline void *ExchangePtr(XchgPtr *ptr, void *newval);
  73. extern inline ALboolean CompExchangeInt(volatile int *ptr, int oldval, int newval);
  74. extern inline ALboolean CompExchangePtr(XchgPtr *ptr, void *oldval, void *newval);
  75. extern inline void LockUIntMapRead(UIntMap *map);
  76. extern inline void UnlockUIntMapRead(UIntMap *map);
  77. extern inline void LockUIntMapWrite(UIntMap *map);
  78. extern inline void UnlockUIntMapWrite(UIntMap *map);
  79. extern inline ALuint NextPowerOf2(ALuint value);
  80. extern inline ALint fastf2i(ALfloat f);
  81. extern inline ALuint fastf2u(ALfloat f);
  82. ALuint CPUCapFlags = 0;
  83. void FillCPUCaps(ALuint capfilter)
  84. {
  85. ALuint caps = 0;
  86. /* FIXME: We really should get this for all available CPUs in case different
  87. * CPUs have different caps (is that possible on one machine?). */
  88. #if defined(HAVE_CPUID_H) && (defined(__i386__) || defined(__x86_64__) || \
  89. defined(_M_IX86) || defined(_M_X64))
  90. union {
  91. unsigned int regs[4];
  92. char str[sizeof(unsigned int[4])];
  93. } cpuinf[3];
  94. if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
  95. ERR("Failed to get CPUID\n");
  96. else
  97. {
  98. unsigned int maxfunc = cpuinf[0].regs[0];
  99. unsigned int maxextfunc = 0;
  100. if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
  101. maxextfunc = cpuinf[0].regs[0];
  102. TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
  103. TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
  104. if(maxextfunc >= 0x80000004 &&
  105. __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
  106. __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
  107. __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
  108. TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
  109. if(maxfunc >= 1 &&
  110. __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
  111. {
  112. if((cpuinf[0].regs[3]&(1<<25)))
  113. {
  114. caps |= CPU_CAP_SSE;
  115. if((cpuinf[0].regs[3]&(1<<26)))
  116. caps |= CPU_CAP_SSE2;
  117. }
  118. }
  119. }
  120. #elif defined(HAVE_WINDOWS_H)
  121. HMODULE k32 = GetModuleHandleA("kernel32.dll");
  122. BOOL (WINAPI*IsProcessorFeaturePresent)(DWORD ProcessorFeature);
  123. IsProcessorFeaturePresent = (BOOL(WINAPI*)(DWORD))GetProcAddress(k32, "IsProcessorFeaturePresent");
  124. if(!IsProcessorFeaturePresent)
  125. ERR("IsProcessorFeaturePresent not available; CPU caps not detected\n");
  126. else
  127. {
  128. if(IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
  129. {
  130. caps |= CPU_CAP_SSE;
  131. if(IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE))
  132. caps |= CPU_CAP_SSE2;
  133. }
  134. }
  135. #endif
  136. #ifdef HAVE_NEON
  137. /* Assume Neon support if compiled with it */
  138. caps |= CPU_CAP_NEON;
  139. #endif
  140. TRACE("Got caps:%s%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
  141. ((caps&CPU_CAP_SSE2)?((capfilter&CPU_CAP_SSE2)?" SSE2":" (SSE2)"):""),
  142. ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
  143. ((!caps)?" -none-":""));
  144. CPUCapFlags = caps & capfilter;
  145. }
  146. void *al_malloc(size_t alignment, size_t size)
  147. {
  148. #if defined(HAVE_ALIGNED_ALLOC)
  149. size = (size+(alignment-1))&~(alignment-1);
  150. return aligned_alloc(alignment, size);
  151. #elif defined(HAVE_POSIX_MEMALIGN)
  152. void *ret;
  153. if(posix_memalign(&ret, alignment, size) == 0)
  154. return ret;
  155. return NULL;
  156. #elif defined(HAVE__ALIGNED_MALLOC)
  157. return _aligned_malloc(size, alignment);
  158. #else
  159. char *ret = malloc(size+alignment);
  160. if(ret != NULL)
  161. {
  162. *(ret++) = 0x00;
  163. while(((ALintptrEXT)ret&(alignment-1)) != 0)
  164. *(ret++) = 0x55;
  165. }
  166. return ret;
  167. #endif
  168. }
  169. void *al_calloc(size_t alignment, size_t size)
  170. {
  171. void *ret = al_malloc(alignment, size);
  172. if(ret) memset(ret, 0, size);
  173. return ret;
  174. }
  175. void al_free(void *ptr)
  176. {
  177. #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
  178. free(ptr);
  179. #elif defined(HAVE__ALIGNED_MALLOC)
  180. _aligned_free(ptr);
  181. #else
  182. if(ptr != NULL)
  183. {
  184. char *finder = ptr;
  185. do {
  186. --finder;
  187. } while(*finder == 0x55);
  188. free(finder);
  189. }
  190. #endif
  191. }
  192. #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
  193. /* Win64 doesn't allow us to set the precision control. */
  194. #undef _MCW_PC
  195. #define _MCW_PC 0
  196. #endif
  197. void SetMixerFPUMode(FPUCtl *ctl)
  198. {
  199. #ifdef HAVE_FENV_H
  200. fegetenv(STATIC_CAST(fenv_t, ctl));
  201. #if defined(__GNUC__) && defined(HAVE_SSE)
  202. if((CPUCapFlags&CPU_CAP_SSE))
  203. __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
  204. #endif
  205. #ifdef FE_TOWARDZERO
  206. fesetround(FE_TOWARDZERO);
  207. #endif
  208. #if defined(__GNUC__) && defined(HAVE_SSE)
  209. if((CPUCapFlags&CPU_CAP_SSE))
  210. {
  211. int sseState = ctl->sse_state;
  212. sseState |= 0x6000; /* set round-to-zero */
  213. sseState |= 0x8000; /* set flush-to-zero */
  214. if((CPUCapFlags&CPU_CAP_SSE2))
  215. sseState |= 0x0040; /* set denormals-are-zero */
  216. __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
  217. }
  218. #endif
  219. #elif defined(HAVE___CONTROL87_2)
  220. int mode;
  221. __control87_2(0, 0, &ctl->state, NULL);
  222. __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
  223. #ifdef HAVE_SSE
  224. if((CPUCapFlags&CPU_CAP_SSE))
  225. {
  226. __control87_2(0, 0, NULL, &ctl->sse_state);
  227. __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
  228. }
  229. #endif
  230. #elif defined(HAVE__CONTROLFP)
  231. ctl->state = _controlfp(0, 0);
  232. (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
  233. #endif
  234. }
  235. void RestoreFPUMode(const FPUCtl *ctl)
  236. {
  237. #ifdef HAVE_FENV_H
  238. fesetenv(STATIC_CAST(fenv_t, ctl));
  239. #if defined(__GNUC__) && defined(HAVE_SSE)
  240. if((CPUCapFlags&CPU_CAP_SSE))
  241. __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
  242. #endif
  243. #elif defined(HAVE___CONTROL87_2)
  244. int mode;
  245. __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
  246. #ifdef HAVE_SSE
  247. if((CPUCapFlags&CPU_CAP_SSE))
  248. __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
  249. #endif
  250. #elif defined(HAVE__CONTROLFP)
  251. _controlfp(ctl->state, _MCW_RC|_MCW_PC);
  252. #endif
  253. }
  254. #ifdef _WIN32
  255. extern inline int alsched_yield(void);
  256. void althread_once(althread_once_t *once, void (*callback)(void))
  257. {
  258. LONG ret;
  259. while((ret=InterlockedExchange(once, 1)) == 1)
  260. alsched_yield();
  261. if(ret == 0)
  262. callback();
  263. InterlockedExchange(once, 2);
  264. }
  265. int althread_key_create(althread_key_t *key, void (*callback)(void*))
  266. {
  267. *key = TlsAlloc();
  268. if(callback)
  269. InsertUIntMapEntry(&TlsDestructor, *key, callback);
  270. return 0;
  271. }
  272. int althread_key_delete(althread_key_t key)
  273. {
  274. InsertUIntMapEntry(&TlsDestructor, key, NULL);
  275. TlsFree(key);
  276. return 0;
  277. }
  278. void *althread_getspecific(althread_key_t key)
  279. { return TlsGetValue(key); }
  280. int althread_setspecific(althread_key_t key, void *val)
  281. {
  282. TlsSetValue(key, val);
  283. return 0;
  284. }
  285. void *LoadLib(const char *name)
  286. { return LoadLibraryA(name); }
  287. void CloseLib(void *handle)
  288. { FreeLibrary((HANDLE)handle); }
  289. void *GetSymbol(void *handle, const char *name)
  290. {
  291. void *ret;
  292. ret = (void*)GetProcAddress((HANDLE)handle, name);
  293. if(ret == NULL)
  294. ERR("Failed to load %s\n", name);
  295. return ret;
  296. }
  297. WCHAR *strdupW(const WCHAR *str)
  298. {
  299. const WCHAR *n;
  300. WCHAR *ret;
  301. size_t len;
  302. n = str;
  303. while(*n) n++;
  304. len = n - str;
  305. ret = calloc(sizeof(WCHAR), len+1);
  306. if(ret != NULL)
  307. memcpy(ret, str, sizeof(WCHAR)*len);
  308. return ret;
  309. }
  310. #else
  311. #include <pthread.h>
  312. #ifdef HAVE_PTHREAD_NP_H
  313. #include <pthread_np.h>
  314. #endif
  315. #include <sched.h>
  316. #include <time.h>
  317. #include <sys/time.h>
  318. void InitializeCriticalSection(CRITICAL_SECTION *cs)
  319. {
  320. pthread_mutexattr_t attrib;
  321. int ret;
  322. ret = pthread_mutexattr_init(&attrib);
  323. assert(ret == 0);
  324. ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
  325. #ifdef HAVE_PTHREAD_NP_H
  326. if(ret != 0)
  327. ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
  328. #endif
  329. assert(ret == 0);
  330. ret = pthread_mutex_init(cs, &attrib);
  331. assert(ret == 0);
  332. pthread_mutexattr_destroy(&attrib);
  333. }
  334. void DeleteCriticalSection(CRITICAL_SECTION *cs)
  335. {
  336. int ret;
  337. ret = pthread_mutex_destroy(cs);
  338. assert(ret == 0);
  339. }
  340. void EnterCriticalSection(CRITICAL_SECTION *cs)
  341. {
  342. int ret;
  343. ret = pthread_mutex_lock(cs);
  344. assert(ret == 0);
  345. }
  346. void LeaveCriticalSection(CRITICAL_SECTION *cs)
  347. {
  348. int ret;
  349. ret = pthread_mutex_unlock(cs);
  350. assert(ret == 0);
  351. }
  352. /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
  353. * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
  354. * Additionally, Win32 is supposed to measure the time since Windows started,
  355. * as opposed to the actual time. */
  356. ALuint timeGetTime(void)
  357. {
  358. #if _POSIX_TIMERS > 0
  359. struct timespec ts;
  360. int ret = -1;
  361. #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
  362. #if _POSIX_MONOTONIC_CLOCK == 0
  363. static int hasmono = 0;
  364. if(hasmono > 0 || (hasmono == 0 &&
  365. (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
  366. #endif
  367. ret = clock_gettime(CLOCK_MONOTONIC, &ts);
  368. #endif
  369. if(ret != 0)
  370. ret = clock_gettime(CLOCK_REALTIME, &ts);
  371. assert(ret == 0);
  372. return ts.tv_nsec/1000000 + ts.tv_sec*1000;
  373. #else
  374. struct timeval tv;
  375. int ret;
  376. ret = gettimeofday(&tv, NULL);
  377. assert(ret == 0);
  378. return tv.tv_usec/1000 + tv.tv_sec*1000;
  379. #endif
  380. }
  381. void Sleep(ALuint t)
  382. {
  383. struct timespec tv, rem;
  384. tv.tv_nsec = (t*1000000)%1000000000;
  385. tv.tv_sec = t/1000;
  386. while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
  387. tv = rem;
  388. }
  389. #ifdef HAVE_DLFCN_H
  390. void *LoadLib(const char *name)
  391. {
  392. const char *err;
  393. void *handle;
  394. dlerror();
  395. handle = dlopen(name, RTLD_NOW);
  396. if((err=dlerror()) != NULL)
  397. handle = NULL;
  398. return handle;
  399. }
  400. void CloseLib(void *handle)
  401. { dlclose(handle); }
  402. void *GetSymbol(void *handle, const char *name)
  403. {
  404. const char *err;
  405. void *sym;
  406. dlerror();
  407. sym = dlsym(handle, name);
  408. if((err=dlerror()) != NULL)
  409. {
  410. WARN("Failed to load %s: %s\n", name, err);
  411. sym = NULL;
  412. }
  413. return sym;
  414. }
  415. #endif
  416. #endif
  417. void al_print(const char *type, const char *func, const char *fmt, ...)
  418. {
  419. va_list ap;
  420. va_start(ap, fmt);
  421. fprintf(LogFile, "AL lib: %s %s: ", type, func);
  422. vfprintf(LogFile, fmt, ap);
  423. va_end(ap);
  424. fflush(LogFile);
  425. }
  426. void SetRTPriority(void)
  427. {
  428. ALboolean failed = AL_FALSE;
  429. #ifdef _WIN32
  430. if(RTPrioLevel > 0)
  431. failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  432. #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  433. if(RTPrioLevel > 0)
  434. {
  435. struct sched_param param;
  436. /* Use the minimum real-time priority possible for now (on Linux this
  437. * should be 1 for SCHED_RR) */
  438. param.sched_priority = sched_get_priority_min(SCHED_RR);
  439. failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
  440. }
  441. #else
  442. /* Real-time priority not available */
  443. failed = (RTPrioLevel>0);
  444. #endif
  445. if(failed)
  446. ERR("Failed to set priority level for thread\n");
  447. }
  448. static void Lock(volatile ALenum *l)
  449. {
  450. while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
  451. alsched_yield();
  452. }
  453. static void Unlock(volatile ALenum *l)
  454. {
  455. ExchangeInt(l, AL_FALSE);
  456. }
  457. void RWLockInit(RWLock *lock)
  458. {
  459. lock->read_count = 0;
  460. lock->write_count = 0;
  461. lock->read_lock = AL_FALSE;
  462. lock->read_entry_lock = AL_FALSE;
  463. lock->write_lock = AL_FALSE;
  464. }
  465. void ReadLock(RWLock *lock)
  466. {
  467. Lock(&lock->read_entry_lock);
  468. Lock(&lock->read_lock);
  469. if(IncrementRef(&lock->read_count) == 1)
  470. Lock(&lock->write_lock);
  471. Unlock(&lock->read_lock);
  472. Unlock(&lock->read_entry_lock);
  473. }
  474. void ReadUnlock(RWLock *lock)
  475. {
  476. if(DecrementRef(&lock->read_count) == 0)
  477. Unlock(&lock->write_lock);
  478. }
  479. void WriteLock(RWLock *lock)
  480. {
  481. if(IncrementRef(&lock->write_count) == 1)
  482. Lock(&lock->read_lock);
  483. Lock(&lock->write_lock);
  484. }
  485. void WriteUnlock(RWLock *lock)
  486. {
  487. Unlock(&lock->write_lock);
  488. if(DecrementRef(&lock->write_count) == 0)
  489. Unlock(&lock->read_lock);
  490. }
  491. void InitUIntMap(UIntMap *map, ALsizei limit)
  492. {
  493. map->array = NULL;
  494. map->size = 0;
  495. map->maxsize = 0;
  496. map->limit = limit;
  497. RWLockInit(&map->lock);
  498. }
  499. void ResetUIntMap(UIntMap *map)
  500. {
  501. WriteLock(&map->lock);
  502. free(map->array);
  503. map->array = NULL;
  504. map->size = 0;
  505. map->maxsize = 0;
  506. WriteUnlock(&map->lock);
  507. }
  508. ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
  509. {
  510. ALsizei pos = 0;
  511. WriteLock(&map->lock);
  512. if(map->size > 0)
  513. {
  514. ALsizei low = 0;
  515. ALsizei high = map->size - 1;
  516. while(low < high)
  517. {
  518. ALsizei mid = low + (high-low)/2;
  519. if(map->array[mid].key < key)
  520. low = mid + 1;
  521. else
  522. high = mid;
  523. }
  524. if(map->array[low].key < key)
  525. low++;
  526. pos = low;
  527. }
  528. if(pos == map->size || map->array[pos].key != key)
  529. {
  530. if(map->size == map->limit)
  531. {
  532. WriteUnlock(&map->lock);
  533. return AL_OUT_OF_MEMORY;
  534. }
  535. if(map->size == map->maxsize)
  536. {
  537. ALvoid *temp = NULL;
  538. ALsizei newsize;
  539. newsize = (map->maxsize ? (map->maxsize<<1) : 4);
  540. if(newsize >= map->maxsize)
  541. temp = realloc(map->array, newsize*sizeof(map->array[0]));
  542. if(!temp)
  543. {
  544. WriteUnlock(&map->lock);
  545. return AL_OUT_OF_MEMORY;
  546. }
  547. map->array = temp;
  548. map->maxsize = newsize;
  549. }
  550. if(pos < map->size)
  551. memmove(&map->array[pos+1], &map->array[pos],
  552. (map->size-pos)*sizeof(map->array[0]));
  553. map->size++;
  554. }
  555. map->array[pos].key = key;
  556. map->array[pos].value = value;
  557. WriteUnlock(&map->lock);
  558. return AL_NO_ERROR;
  559. }
  560. ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
  561. {
  562. ALvoid *ptr = NULL;
  563. WriteLock(&map->lock);
  564. if(map->size > 0)
  565. {
  566. ALsizei low = 0;
  567. ALsizei high = map->size - 1;
  568. while(low < high)
  569. {
  570. ALsizei mid = low + (high-low)/2;
  571. if(map->array[mid].key < key)
  572. low = mid + 1;
  573. else
  574. high = mid;
  575. }
  576. if(map->array[low].key == key)
  577. {
  578. ptr = map->array[low].value;
  579. if(low < map->size-1)
  580. memmove(&map->array[low], &map->array[low+1],
  581. (map->size-1-low)*sizeof(map->array[0]));
  582. map->size--;
  583. }
  584. }
  585. WriteUnlock(&map->lock);
  586. return ptr;
  587. }
  588. ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
  589. {
  590. ALvoid *ptr = NULL;
  591. ReadLock(&map->lock);
  592. if(map->size > 0)
  593. {
  594. ALsizei low = 0;
  595. ALsizei high = map->size - 1;
  596. while(low < high)
  597. {
  598. ALsizei mid = low + (high-low)/2;
  599. if(map->array[mid].key < key)
  600. low = mid + 1;
  601. else
  602. high = mid;
  603. }
  604. if(map->array[low].key == key)
  605. ptr = map->array[low].value;
  606. }
  607. ReadUnlock(&map->lock);
  608. return ptr;
  609. }