Use separate atomic macros for pointers
[openal-soft.git] / Alc / helpers.c
blob8e685c75b2705922604b7a5df505150de3e39a32
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.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 #include <ctype.h>
36 #ifdef HAVE_MALLOC_H
37 #include <malloc.h>
38 #endif
39 #ifdef HAVE_DIRENT_H
40 #include <dirent.h>
41 #endif
43 #ifndef AL_NO_UID_DEFS
44 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
45 #define INITGUID
46 #include <windows.h>
47 #ifdef HAVE_GUIDDEF_H
48 #include <guiddef.h>
49 #else
50 #include <initguid.h>
51 #endif
53 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
54 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
56 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
58 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
59 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
60 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
61 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
62 DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
64 #ifdef HAVE_MMDEVAPI
65 #include <wtypes.h>
66 #include <devpropdef.h>
67 #include <propkeydef.h>
68 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
69 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
70 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
71 #endif
72 #endif
73 #endif /* AL_NO_UID_DEFS */
75 #ifdef HAVE_DLFCN_H
76 #include <dlfcn.h>
77 #endif
78 #ifdef HAVE_INTRIN_H
79 #include <intrin.h>
80 #endif
81 #ifdef HAVE_CPUID_H
82 #include <cpuid.h>
83 #endif
84 #ifdef HAVE_SYS_SYSCONF_H
85 #include <sys/sysconf.h>
86 #endif
87 #ifdef HAVE_FLOAT_H
88 #include <float.h>
89 #endif
90 #ifdef HAVE_IEEEFP_H
91 #include <ieeefp.h>
92 #endif
94 #ifndef _WIN32
95 #include <sys/types.h>
96 #include <sys/stat.h>
97 #include <sys/mman.h>
98 #include <fcntl.h>
99 #include <unistd.h>
100 #elif defined(_WIN32_IE)
101 #include <shlobj.h>
102 #endif
104 #include "alMain.h"
105 #include "alu.h"
106 #include "atomic.h"
107 #include "uintmap.h"
108 #include "vector.h"
109 #include "alstring.h"
110 #include "compat.h"
111 #include "threads.h"
114 extern inline ALuint NextPowerOf2(ALuint value);
115 extern inline size_t RoundUp(size_t value, size_t r);
116 extern inline ALint fastf2i(ALfloat f);
117 extern inline ALuint fastf2u(ALfloat f);
120 ALuint CPUCapFlags = 0;
123 void FillCPUCaps(ALuint capfilter)
125 ALuint caps = 0;
127 /* FIXME: We really should get this for all available CPUs in case different
128 * CPUs have different caps (is that possible on one machine?). */
129 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
130 defined(_M_IX86) || defined(_M_X64))
131 union {
132 unsigned int regs[4];
133 char str[sizeof(unsigned int[4])];
134 } cpuinf[3];
136 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
137 ERR("Failed to get CPUID\n");
138 else
140 unsigned int maxfunc = cpuinf[0].regs[0];
141 unsigned int maxextfunc = 0;
143 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
144 maxextfunc = cpuinf[0].regs[0];
145 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
147 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
148 if(maxextfunc >= 0x80000004 &&
149 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
150 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
151 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
152 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
154 if(maxfunc >= 1 &&
155 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
157 if((cpuinf[0].regs[3]&(1<<25)))
159 caps |= CPU_CAP_SSE;
160 if((cpuinf[0].regs[3]&(1<<26)))
162 caps |= CPU_CAP_SSE2;
163 if((cpuinf[0].regs[2]&(1<<0)))
165 caps |= CPU_CAP_SSE3;
166 if((cpuinf[0].regs[2]&(1<<19)))
167 caps |= CPU_CAP_SSE4_1;
173 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
174 defined(_M_IX86) || defined(_M_X64))
175 union {
176 int regs[4];
177 char str[sizeof(int[4])];
178 } cpuinf[3];
180 (__cpuid)(cpuinf[0].regs, 0);
181 if(cpuinf[0].regs[0] == 0)
182 ERR("Failed to get CPUID\n");
183 else
185 unsigned int maxfunc = cpuinf[0].regs[0];
186 unsigned int maxextfunc;
188 (__cpuid)(cpuinf[0].regs, 0x80000000);
189 maxextfunc = cpuinf[0].regs[0];
191 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
193 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
194 if(maxextfunc >= 0x80000004)
196 (__cpuid)(cpuinf[0].regs, 0x80000002);
197 (__cpuid)(cpuinf[1].regs, 0x80000003);
198 (__cpuid)(cpuinf[2].regs, 0x80000004);
199 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
202 if(maxfunc >= 1)
204 (__cpuid)(cpuinf[0].regs, 1);
205 if((cpuinf[0].regs[3]&(1<<25)))
207 caps |= CPU_CAP_SSE;
208 if((cpuinf[0].regs[3]&(1<<26)))
210 caps |= CPU_CAP_SSE2;
211 if((cpuinf[0].regs[2]&(1<<0)))
213 caps |= CPU_CAP_SSE3;
214 if((cpuinf[0].regs[2]&(1<<19)))
215 caps |= CPU_CAP_SSE4_1;
221 #else
222 /* Assume support for whatever's supported if we can't check for it */
223 #if defined(HAVE_SSE4_1)
224 #warning "Assuming SSE 4.1 run-time support!"
225 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
226 #elif defined(HAVE_SSE3)
227 #warning "Assuming SSE 3 run-time support!"
228 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
229 #elif defined(HAVE_SSE2)
230 #warning "Assuming SSE 2 run-time support!"
231 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
232 #elif defined(HAVE_SSE)
233 #warning "Assuming SSE run-time support!"
234 caps |= CPU_CAP_SSE;
235 #endif
236 #endif
237 #ifdef HAVE_NEON
238 FILE *file = fopen("/proc/cpuinfo", "rt");
239 if(!file)
240 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
241 else
243 char buf[256];
244 while(fgets(buf, sizeof(buf), file) != NULL)
246 size_t len;
247 char *str;
249 if(strncmp(buf, "Features\t:", 10) != 0)
250 continue;
252 len = strlen(buf);
253 while(len > 0 && isspace(buf[len-1]))
254 buf[--len] = 0;
256 TRACE("Got features string:%s\n", buf+10);
258 str = buf;
259 while((str=strstr(str, "neon")) != NULL)
261 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
263 caps |= CPU_CAP_NEON;
264 break;
266 str++;
268 break;
271 fclose(file);
272 file = NULL;
274 #endif
276 TRACE("Extensions:%s%s%s%s%s%s\n",
277 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
278 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
279 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
280 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
281 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
282 ((!capfilter) ? " -none-" : "")
284 CPUCapFlags = caps & capfilter;
288 void SetMixerFPUMode(FPUCtl *ctl)
290 #ifdef HAVE_FENV_H
291 fegetenv(STATIC_CAST(fenv_t, ctl));
292 #if defined(__GNUC__) && defined(HAVE_SSE)
293 /* FIXME: Some fegetenv implementations can get the SSE environment too?
294 * How to tell when it does? */
295 if((CPUCapFlags&CPU_CAP_SSE))
296 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
297 #endif
299 #ifdef FE_TOWARDZERO
300 fesetround(FE_TOWARDZERO);
301 #endif
302 #if defined(__GNUC__) && defined(HAVE_SSE)
303 if((CPUCapFlags&CPU_CAP_SSE))
305 int sseState = ctl->sse_state;
306 sseState |= 0x6000; /* set round-to-zero */
307 sseState |= 0x8000; /* set flush-to-zero */
308 if((CPUCapFlags&CPU_CAP_SSE2))
309 sseState |= 0x0040; /* set denormals-are-zero */
310 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
312 #endif
314 #elif defined(HAVE___CONTROL87_2)
316 int mode;
317 __control87_2(0, 0, &ctl->state, NULL);
318 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
319 #ifdef HAVE_SSE
320 if((CPUCapFlags&CPU_CAP_SSE))
322 __control87_2(0, 0, NULL, &ctl->sse_state);
323 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
325 #endif
327 #elif defined(HAVE__CONTROLFP)
329 ctl->state = _controlfp(0, 0);
330 (void)_controlfp(_RC_CHOP, _MCW_RC);
331 #endif
334 void RestoreFPUMode(const FPUCtl *ctl)
336 #ifdef HAVE_FENV_H
337 fesetenv(STATIC_CAST(fenv_t, ctl));
338 #if defined(__GNUC__) && defined(HAVE_SSE)
339 if((CPUCapFlags&CPU_CAP_SSE))
340 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
341 #endif
343 #elif defined(HAVE___CONTROL87_2)
345 int mode;
346 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
347 #ifdef HAVE_SSE
348 if((CPUCapFlags&CPU_CAP_SSE))
349 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
350 #endif
352 #elif defined(HAVE__CONTROLFP)
354 _controlfp(ctl->state, _MCW_RC);
355 #endif
359 static int StringSortCompare(const void *str1, const void *str2)
361 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
364 #ifdef _WIN32
366 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
368 WCHAR *ret = NULL;
369 while(*str)
371 if(*str == ch)
372 ret = str;
373 ++str;
375 return ret;
378 al_string GetProcPath(void)
380 al_string ret = AL_STRING_INIT_STATIC();
381 WCHAR *pathname, *sep;
382 DWORD pathlen;
383 DWORD len;
385 pathlen = 256;
386 pathname = malloc(pathlen * sizeof(pathname[0]));
387 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
389 free(pathname);
390 pathlen <<= 1;
391 pathname = malloc(pathlen * sizeof(pathname[0]));
393 if(len == 0)
395 free(pathname);
396 ERR("Failed to get process name: error %lu\n", GetLastError());
397 return ret;
400 pathname[len] = 0;
401 if((sep = strrchrW(pathname, '\\')))
403 WCHAR *sep2 = strrchrW(pathname, '/');
404 if(sep2) *sep2 = 0;
405 else *sep = 0;
407 else if((sep = strrchrW(pathname, '/')))
408 *sep = 0;
409 alstr_copy_wcstr(&ret, pathname);
410 free(pathname);
412 TRACE("Got: %s\n", alstr_get_cstr(ret));
413 return ret;
417 static WCHAR *FromUTF8(const char *str)
419 WCHAR *out = NULL;
420 int len;
422 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
424 out = calloc(sizeof(WCHAR), len);
425 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
427 return out;
431 void *LoadLib(const char *name)
433 HANDLE hdl = NULL;
434 WCHAR *wname;
436 wname = FromUTF8(name);
437 if(!wname)
438 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
439 else
441 hdl = LoadLibraryW(wname);
442 free(wname);
444 return hdl;
446 void CloseLib(void *handle)
447 { FreeLibrary((HANDLE)handle); }
448 void *GetSymbol(void *handle, const char *name)
450 void *ret;
452 ret = (void*)GetProcAddress((HANDLE)handle, name);
453 if(ret == NULL)
454 ERR("Failed to load %s\n", name);
455 return ret;
458 WCHAR *strdupW(const WCHAR *str)
460 const WCHAR *n;
461 WCHAR *ret;
462 size_t len;
464 n = str;
465 while(*n) n++;
466 len = n - str;
468 ret = calloc(sizeof(WCHAR), len+1);
469 if(ret != NULL)
470 memcpy(ret, str, sizeof(WCHAR)*len);
471 return ret;
474 FILE *al_fopen(const char *fname, const char *mode)
476 WCHAR *wname=NULL, *wmode=NULL;
477 FILE *file = NULL;
479 wname = FromUTF8(fname);
480 wmode = FromUTF8(mode);
481 if(!wname)
482 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
483 else if(!wmode)
484 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
485 else
486 file = _wfopen(wname, wmode);
488 free(wname);
489 free(wmode);
491 return file;
495 void al_print(const char *type, const char *func, const char *fmt, ...)
497 char str[1024];
498 WCHAR *wstr;
499 va_list ap;
501 va_start(ap, fmt);
502 vsnprintf(str, sizeof(str), fmt, ap);
503 va_end(ap);
505 str[sizeof(str)-1] = 0;
506 wstr = FromUTF8(str);
507 if(!wstr)
508 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
509 else
511 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
512 free(wstr);
513 wstr = NULL;
515 fflush(LogFile);
519 static inline int is_slash(int c)
520 { return (c == '\\' || c == '/'); }
522 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
524 al_string pathstr = AL_STRING_INIT_STATIC();
525 WIN32_FIND_DATAW fdata;
526 WCHAR *wpath;
527 HANDLE hdl;
529 alstr_copy_cstr(&pathstr, path);
530 alstr_append_cstr(&pathstr, "\\*");
531 alstr_append_cstr(&pathstr, ext);
533 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
535 wpath = FromUTF8(alstr_get_cstr(pathstr));
537 hdl = FindFirstFileW(wpath, &fdata);
538 if(hdl != INVALID_HANDLE_VALUE)
540 size_t base = VECTOR_SIZE(*results);
541 do {
542 al_string str = AL_STRING_INIT_STATIC();
543 alstr_copy_cstr(&str, path);
544 alstr_append_char(&str, '\\');
545 alstr_append_wcstr(&str, fdata.cFileName);
546 TRACE("Got result %s\n", alstr_get_cstr(str));
547 VECTOR_PUSH_BACK(*results, str);
548 } while(FindNextFileW(hdl, &fdata));
549 FindClose(hdl);
551 if(VECTOR_SIZE(*results) > base)
552 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
553 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
556 free(wpath);
557 alstr_reset(&pathstr);
560 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
562 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
563 static RefCount search_lock;
564 vector_al_string results = VECTOR_INIT_STATIC();
565 size_t i;
567 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
568 althrd_yield();
570 /* If the path is absolute, use it directly. */
571 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
573 al_string path = AL_STRING_INIT_STATIC();
574 alstr_copy_cstr(&path, subdir);
575 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
576 VECTOR_FOR_EACH(char, path, FIX_SLASH);
577 #undef FIX_SLASH
579 DirectorySearch(alstr_get_cstr(path), ext, &results);
581 alstr_reset(&path);
583 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
584 DirectorySearch(subdir, ext, &results);
585 else
587 al_string path = AL_STRING_INIT_STATIC();
588 WCHAR *cwdbuf;
590 /* Search the app-local directory. */
591 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
593 alstr_copy_wcstr(&path, cwdbuf);
594 if(is_slash(VECTOR_BACK(path)))
596 VECTOR_POP_BACK(path);
597 *VECTOR_END(path) = 0;
600 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
601 alstr_copy_cstr(&path, ".");
602 else
604 alstr_copy_wcstr(&path, cwdbuf);
605 if(is_slash(VECTOR_BACK(path)))
607 VECTOR_POP_BACK(path);
608 *VECTOR_END(path) = 0;
610 free(cwdbuf);
612 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
613 VECTOR_FOR_EACH(char, path, FIX_SLASH);
614 #undef FIX_SLASH
615 DirectorySearch(alstr_get_cstr(path), ext, &results);
617 /* Search the local and global data dirs. */
618 for(i = 0;i < COUNTOF(ids);i++)
620 WCHAR buffer[PATH_MAX];
621 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
623 alstr_copy_wcstr(&path, buffer);
624 if(!is_slash(VECTOR_BACK(path)))
625 alstr_append_char(&path, '\\');
626 alstr_append_cstr(&path, subdir);
627 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
628 VECTOR_FOR_EACH(char, path, FIX_SLASH);
629 #undef FIX_SLASH
631 DirectorySearch(alstr_get_cstr(path), ext, &results);
635 alstr_reset(&path);
638 ATOMIC_STORE_SEQ(&search_lock, 0);
640 return results;
644 struct FileMapping MapFileToMem(const char *fname)
646 struct FileMapping ret = { NULL, NULL, NULL, 0 };
647 MEMORY_BASIC_INFORMATION meminfo;
648 HANDLE file, fmap;
649 WCHAR *wname;
650 void *ptr;
652 wname = FromUTF8(fname);
654 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
655 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
656 if(file == INVALID_HANDLE_VALUE)
658 ERR("Failed to open %s: %lu\n", fname, GetLastError());
659 free(wname);
660 return ret;
662 free(wname);
663 wname = NULL;
665 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
666 if(!fmap)
668 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
669 CloseHandle(file);
670 return ret;
673 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
674 if(!ptr)
676 ERR("Failed to map %s: %lu\n", fname, GetLastError());
677 CloseHandle(fmap);
678 CloseHandle(file);
679 return ret;
682 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
684 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
685 UnmapViewOfFile(ptr);
686 CloseHandle(fmap);
687 CloseHandle(file);
688 return ret;
691 ret.file = file;
692 ret.fmap = fmap;
693 ret.ptr = ptr;
694 ret.len = meminfo.RegionSize;
695 return ret;
698 void UnmapFileMem(const struct FileMapping *mapping)
700 UnmapViewOfFile(mapping->ptr);
701 CloseHandle(mapping->fmap);
702 CloseHandle(mapping->file);
705 #else
707 al_string GetProcPath(void)
709 al_string ret = AL_STRING_INIT_STATIC();
710 const char *fname;
711 char *pathname, *sep;
712 size_t pathlen;
713 ssize_t len;
715 pathlen = 256;
716 pathname = malloc(pathlen);
718 fname = "/proc/self/exe";
719 len = readlink(fname, pathname, pathlen);
720 if(len == -1 && errno == ENOENT)
722 fname = "/proc/self/file";
723 len = readlink(fname, pathname, pathlen);
726 while(len > 0 && (size_t)len == pathlen)
728 free(pathname);
729 pathlen <<= 1;
730 pathname = malloc(pathlen);
731 len = readlink(fname, pathname, pathlen);
733 if(len <= 0)
735 free(pathname);
736 WARN("Failed to readlink %s: %s\n", fname, strerror(errno));
737 return ret;
740 pathname[len] = 0;
741 sep = strrchr(pathname, '/');
742 if(sep)
743 alstr_copy_range(&ret, pathname, sep);
744 else
745 alstr_copy_cstr(&ret, pathname);
746 free(pathname);
748 TRACE("Got: %s\n", alstr_get_cstr(ret));
749 return ret;
753 #ifdef HAVE_DLFCN_H
755 void *LoadLib(const char *name)
757 const char *err;
758 void *handle;
760 dlerror();
761 handle = dlopen(name, RTLD_NOW);
762 if((err=dlerror()) != NULL)
763 handle = NULL;
764 return handle;
766 void CloseLib(void *handle)
767 { dlclose(handle); }
768 void *GetSymbol(void *handle, const char *name)
770 const char *err;
771 void *sym;
773 dlerror();
774 sym = dlsym(handle, name);
775 if((err=dlerror()) != NULL)
777 WARN("Failed to load %s: %s\n", name, err);
778 sym = NULL;
780 return sym;
783 #endif /* HAVE_DLFCN_H */
785 void al_print(const char *type, const char *func, const char *fmt, ...)
787 va_list ap;
789 va_start(ap, fmt);
790 fprintf(LogFile, "AL lib: %s %s: ", type, func);
791 vfprintf(LogFile, fmt, ap);
792 va_end(ap);
794 fflush(LogFile);
798 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
800 size_t extlen = strlen(ext);
801 DIR *dir;
803 TRACE("Searching %s for *%s\n", path, ext);
804 dir = opendir(path);
805 if(dir != NULL)
807 size_t base = VECTOR_SIZE(*results);
808 struct dirent *dirent;
809 while((dirent=readdir(dir)) != NULL)
811 al_string str;
812 size_t len;
813 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
814 continue;
816 len = strlen(dirent->d_name);
817 if(!(len > extlen))
818 continue;
819 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
820 continue;
822 AL_STRING_INIT(str);
823 alstr_copy_cstr(&str, path);
824 if(VECTOR_BACK(str) != '/')
825 alstr_append_char(&str, '/');
826 alstr_append_cstr(&str, dirent->d_name);
827 TRACE("Got result %s\n", alstr_get_cstr(str));
828 VECTOR_PUSH_BACK(*results, str);
830 closedir(dir);
832 if(VECTOR_SIZE(*results) > base)
833 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
834 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
838 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
840 static RefCount search_lock;
841 vector_al_string results = VECTOR_INIT_STATIC();
843 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
844 althrd_yield();
846 if(subdir[0] == '/')
847 DirectorySearch(subdir, ext, &results);
848 else
850 al_string path = AL_STRING_INIT_STATIC();
851 const char *str, *next;
852 char cwdbuf[PATH_MAX];
854 /* Search the app-local directory. */
855 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
856 DirectorySearch(str, ext, &results);
857 else if(getcwd(cwdbuf, sizeof(cwdbuf)))
858 DirectorySearch(cwdbuf, ext, &results);
859 else
860 DirectorySearch(".", ext, &results);
862 // Search local data dir
863 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
865 alstr_copy_cstr(&path, str);
866 if(VECTOR_BACK(path) != '/')
867 alstr_append_char(&path, '/');
868 alstr_append_cstr(&path, subdir);
869 DirectorySearch(alstr_get_cstr(path), ext, &results);
871 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
873 alstr_copy_cstr(&path, str);
874 if(VECTOR_BACK(path) == '/')
876 VECTOR_POP_BACK(path);
877 *VECTOR_END(path) = 0;
879 alstr_append_cstr(&path, "/.local/share/");
880 alstr_append_cstr(&path, subdir);
881 DirectorySearch(alstr_get_cstr(path), ext, &results);
884 // Search global data dirs
885 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
886 str = "/usr/local/share/:/usr/share/";
888 next = str;
889 while((str=next) != NULL && str[0] != '\0')
891 next = strchr(str, ':');
892 if(!next)
893 alstr_copy_cstr(&path, str);
894 else
896 alstr_copy_range(&path, str, next);
897 ++next;
899 if(!alstr_empty(path))
901 if(VECTOR_BACK(path) != '/')
902 alstr_append_char(&path, '/');
903 alstr_append_cstr(&path, subdir);
905 DirectorySearch(alstr_get_cstr(path), ext, &results);
909 alstr_reset(&path);
912 ATOMIC_STORE_SEQ(&search_lock, 0);
914 return results;
918 struct FileMapping MapFileToMem(const char *fname)
920 struct FileMapping ret = { -1, NULL, 0 };
921 struct stat sbuf;
922 void *ptr;
923 int fd;
925 fd = open(fname, O_RDONLY, 0);
926 if(fd == -1)
928 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
929 return ret;
931 if(fstat(fd, &sbuf) == -1)
933 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
934 close(fd);
935 return ret;
938 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
939 if(ptr == MAP_FAILED)
941 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
942 close(fd);
943 return ret;
946 ret.fd = fd;
947 ret.ptr = ptr;
948 ret.len = sbuf.st_size;
949 return ret;
952 void UnmapFileMem(const struct FileMapping *mapping)
954 munmap(mapping->ptr, mapping->len);
955 close(mapping->fd);
958 #endif
961 void SetRTPriority(void)
963 ALboolean failed = AL_FALSE;
965 #ifdef _WIN32
966 if(RTPrioLevel > 0)
967 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
968 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
969 if(RTPrioLevel > 0)
971 struct sched_param param;
972 /* Use the minimum real-time priority possible for now (on Linux this
973 * should be 1 for SCHED_RR) */
974 param.sched_priority = sched_get_priority_min(SCHED_RR);
975 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
977 #else
978 /* Real-time priority not available */
979 failed = (RTPrioLevel>0);
980 #endif
981 if(failed)
982 ERR("Failed to set priority level for thread\n");
986 extern inline void alstr_reset(al_string *str);
987 extern inline size_t alstr_length(const_al_string str);
988 extern inline ALboolean alstr_empty(const_al_string str);
989 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
991 void alstr_clear(al_string *str)
993 if(!alstr_empty(*str))
995 /* Reserve one more character than the total size of the string. This
996 * is to ensure we have space to add a null terminator in the string
997 * data so it can be used as a C-style string.
999 VECTOR_RESIZE(*str, 0, 1);
1000 VECTOR_ELEM(*str, 0) = 0;
1004 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1005 const al_string_char_type *str2, size_t str2len)
1007 size_t complen = (str1len < str2len) ? str1len : str2len;
1008 int ret = memcmp(str1, str2, complen);
1009 if(ret == 0)
1011 if(str1len > str2len) return 1;
1012 if(str1len < str2len) return -1;
1014 return ret;
1016 int alstr_cmp(const_al_string str1, const_al_string str2)
1018 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1019 &VECTOR_FRONT(str2), alstr_length(str2));
1021 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1023 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1024 str2, strlen(str2));
1027 void alstr_copy(al_string *str, const_al_string from)
1029 size_t len = alstr_length(from);
1030 size_t i;
1032 VECTOR_RESIZE(*str, len, len+1);
1033 for(i = 0;i < len;i++)
1034 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1035 VECTOR_ELEM(*str, i) = 0;
1038 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1040 size_t len = strlen(from);
1041 size_t i;
1043 VECTOR_RESIZE(*str, len, len+1);
1044 for(i = 0;i < len;i++)
1045 VECTOR_ELEM(*str, i) = from[i];
1046 VECTOR_ELEM(*str, i) = 0;
1049 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1051 size_t len = to - from;
1052 size_t i;
1054 VECTOR_RESIZE(*str, len, len+1);
1055 for(i = 0;i < len;i++)
1056 VECTOR_ELEM(*str, i) = from[i];
1057 VECTOR_ELEM(*str, i) = 0;
1060 void alstr_append_char(al_string *str, const al_string_char_type c)
1062 size_t len = alstr_length(*str);
1063 VECTOR_RESIZE(*str, len, len+2);
1064 VECTOR_PUSH_BACK(*str, c);
1065 VECTOR_ELEM(*str, len+1) = 0;
1068 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1070 size_t len = strlen(from);
1071 if(len != 0)
1073 size_t base = alstr_length(*str);
1074 size_t i;
1076 VECTOR_RESIZE(*str, base+len, base+len+1);
1077 for(i = 0;i < len;i++)
1078 VECTOR_ELEM(*str, base+i) = from[i];
1079 VECTOR_ELEM(*str, base+i) = 0;
1083 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1085 size_t len = to - from;
1086 if(len != 0)
1088 size_t base = alstr_length(*str);
1089 size_t i;
1091 VECTOR_RESIZE(*str, base+len, base+len+1);
1092 for(i = 0;i < len;i++)
1093 VECTOR_ELEM(*str, base+i) = from[i];
1094 VECTOR_ELEM(*str, base+i) = 0;
1098 #ifdef _WIN32
1099 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1101 int len;
1102 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1104 VECTOR_RESIZE(*str, len-1, len);
1105 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1106 VECTOR_ELEM(*str, len-1) = 0;
1110 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1112 int len;
1113 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1115 size_t base = alstr_length(*str);
1116 VECTOR_RESIZE(*str, base+len-1, base+len);
1117 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1118 VECTOR_ELEM(*str, base+len-1) = 0;
1122 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1124 int len;
1125 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1127 size_t base = alstr_length(*str);
1128 VECTOR_RESIZE(*str, base+len, base+len+1);
1129 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1130 VECTOR_ELEM(*str, base+len) = 0;
1133 #endif