Fix the reverb panning behavior to better fit the spec
[openal-soft.git] / Alc / helpers.c
blobe55454924b3c3914d6c8141ece7250cfb72f7470
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 #ifdef __FreeBSD__
44 #include <sys/types.h>
45 #include <sys/sysctl.h>
46 #endif
48 #ifndef AL_NO_UID_DEFS
49 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
50 #define INITGUID
51 #include <windows.h>
52 #ifdef HAVE_GUIDDEF_H
53 #include <guiddef.h>
54 #else
55 #include <initguid.h>
56 #endif
58 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
59 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
61 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
63 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
64 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
65 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
66 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
67 DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
69 #ifdef HAVE_WASAPI
70 #include <wtypes.h>
71 #include <devpropdef.h>
72 #include <propkeydef.h>
73 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
74 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
75 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
76 #endif
77 #endif
78 #endif /* AL_NO_UID_DEFS */
80 #ifdef HAVE_DLFCN_H
81 #include <dlfcn.h>
82 #endif
83 #ifdef HAVE_INTRIN_H
84 #include <intrin.h>
85 #endif
86 #ifdef HAVE_CPUID_H
87 #include <cpuid.h>
88 #endif
89 #ifdef HAVE_SYS_SYSCONF_H
90 #include <sys/sysconf.h>
91 #endif
92 #ifdef HAVE_FLOAT_H
93 #include <float.h>
94 #endif
95 #ifdef HAVE_IEEEFP_H
96 #include <ieeefp.h>
97 #endif
99 #ifndef _WIN32
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/mman.h>
103 #include <fcntl.h>
104 #include <unistd.h>
105 #elif defined(_WIN32_IE)
106 #include <shlobj.h>
107 #endif
109 #include "alMain.h"
110 #include "alu.h"
111 #include "cpu_caps.h"
112 #include "fpu_modes.h"
113 #include "atomic.h"
114 #include "uintmap.h"
115 #include "vector.h"
116 #include "alstring.h"
117 #include "compat.h"
118 #include "threads.h"
121 extern inline ALuint NextPowerOf2(ALuint value);
122 extern inline size_t RoundUp(size_t value, size_t r);
123 extern inline ALint fastf2i(ALfloat f);
124 #ifndef __GNUC__
125 #if defined(HAVE_BITSCANFORWARD64_INTRINSIC)
126 extern inline int msvc64_ctz64(ALuint64 v);
127 #elif defined(HAVE_BITSCANFORWARD_INTRINSIC)
128 extern inline int msvc_ctz64(ALuint64 v);
129 #else
130 extern inline int fallback_popcnt64(ALuint64 v);
131 extern inline int fallback_ctz64(ALuint64 value);
132 #endif
133 #endif
136 int CPUCapFlags = 0;
138 void FillCPUCaps(int capfilter)
140 int caps = 0;
142 /* FIXME: We really should get this for all available CPUs in case different
143 * CPUs have different caps (is that possible on one machine?). */
144 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
145 defined(_M_IX86) || defined(_M_X64))
146 union {
147 unsigned int regs[4];
148 char str[sizeof(unsigned int[4])];
149 } cpuinf[3];
151 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
152 ERR("Failed to get CPUID\n");
153 else
155 unsigned int maxfunc = cpuinf[0].regs[0];
156 unsigned int maxextfunc = 0;
158 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
159 maxextfunc = cpuinf[0].regs[0];
160 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
162 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
163 if(maxextfunc >= 0x80000004 &&
164 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
165 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
166 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
167 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
169 if(maxfunc >= 1 &&
170 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
172 if((cpuinf[0].regs[3]&(1<<25)))
174 caps |= CPU_CAP_SSE;
175 if((cpuinf[0].regs[3]&(1<<26)))
177 caps |= CPU_CAP_SSE2;
178 if((cpuinf[0].regs[2]&(1<<0)))
180 caps |= CPU_CAP_SSE3;
181 if((cpuinf[0].regs[2]&(1<<19)))
182 caps |= CPU_CAP_SSE4_1;
188 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
189 defined(_M_IX86) || defined(_M_X64))
190 union {
191 int regs[4];
192 char str[sizeof(int[4])];
193 } cpuinf[3];
195 (__cpuid)(cpuinf[0].regs, 0);
196 if(cpuinf[0].regs[0] == 0)
197 ERR("Failed to get CPUID\n");
198 else
200 unsigned int maxfunc = cpuinf[0].regs[0];
201 unsigned int maxextfunc;
203 (__cpuid)(cpuinf[0].regs, 0x80000000);
204 maxextfunc = cpuinf[0].regs[0];
206 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
208 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
209 if(maxextfunc >= 0x80000004)
211 (__cpuid)(cpuinf[0].regs, 0x80000002);
212 (__cpuid)(cpuinf[1].regs, 0x80000003);
213 (__cpuid)(cpuinf[2].regs, 0x80000004);
214 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
217 if(maxfunc >= 1)
219 (__cpuid)(cpuinf[0].regs, 1);
220 if((cpuinf[0].regs[3]&(1<<25)))
222 caps |= CPU_CAP_SSE;
223 if((cpuinf[0].regs[3]&(1<<26)))
225 caps |= CPU_CAP_SSE2;
226 if((cpuinf[0].regs[2]&(1<<0)))
228 caps |= CPU_CAP_SSE3;
229 if((cpuinf[0].regs[2]&(1<<19)))
230 caps |= CPU_CAP_SSE4_1;
236 #else
237 /* Assume support for whatever's supported if we can't check for it */
238 #if defined(HAVE_SSE4_1)
239 #warning "Assuming SSE 4.1 run-time support!"
240 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
241 #elif defined(HAVE_SSE3)
242 #warning "Assuming SSE 3 run-time support!"
243 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
244 #elif defined(HAVE_SSE2)
245 #warning "Assuming SSE 2 run-time support!"
246 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
247 #elif defined(HAVE_SSE)
248 #warning "Assuming SSE run-time support!"
249 caps |= CPU_CAP_SSE;
250 #endif
251 #endif
252 #ifdef HAVE_NEON
253 FILE *file = fopen("/proc/cpuinfo", "rt");
254 if(!file)
255 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
256 else
258 char buf[256];
259 while(fgets(buf, sizeof(buf), file) != NULL)
261 size_t len;
262 char *str;
264 if(strncmp(buf, "Features\t:", 10) != 0)
265 continue;
267 len = strlen(buf);
268 while(len > 0 && isspace(buf[len-1]))
269 buf[--len] = 0;
271 TRACE("Got features string:%s\n", buf+10);
273 str = buf;
274 while((str=strstr(str, "neon")) != NULL)
276 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
278 caps |= CPU_CAP_NEON;
279 break;
281 str++;
283 break;
286 fclose(file);
287 file = NULL;
289 #endif
291 TRACE("Extensions:%s%s%s%s%s%s\n",
292 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
293 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
294 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
295 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
296 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
297 ((!capfilter) ? " -none-" : "")
299 CPUCapFlags = caps & capfilter;
303 void SetMixerFPUMode(FPUCtl *ctl)
305 #ifdef HAVE_FENV_H
306 fegetenv(&ctl->flt_env);
307 #ifdef _WIN32
308 /* HACK: A nasty bug in MinGW-W64 causes fegetenv and fesetenv to not save
309 * and restore the FPU rounding mode, so we have to do it manually. Don't
310 * know if this also applies to MSVC.
312 ctl->round_mode = fegetround();
313 #endif
314 #if defined(__GNUC__) && defined(HAVE_SSE)
315 /* FIXME: Some fegetenv implementations can get the SSE environment too?
316 * How to tell when it does? */
317 if((CPUCapFlags&CPU_CAP_SSE))
318 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
319 #endif
321 #ifdef FE_TOWARDZERO
322 fesetround(FE_TOWARDZERO);
323 #endif
324 #if defined(__GNUC__) && defined(HAVE_SSE)
325 if((CPUCapFlags&CPU_CAP_SSE))
327 int sseState = ctl->sse_state;
328 sseState |= 0x6000; /* set round-to-zero */
329 sseState |= 0x8000; /* set flush-to-zero */
330 if((CPUCapFlags&CPU_CAP_SSE2))
331 sseState |= 0x0040; /* set denormals-are-zero */
332 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
334 #endif
336 #elif defined(HAVE___CONTROL87_2)
338 int mode;
339 __control87_2(0, 0, &ctl->state, NULL);
340 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
341 #ifdef HAVE_SSE
342 if((CPUCapFlags&CPU_CAP_SSE))
344 __control87_2(0, 0, NULL, &ctl->sse_state);
345 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
347 #endif
349 #elif defined(HAVE__CONTROLFP)
351 ctl->state = _controlfp(0, 0);
352 (void)_controlfp(_RC_CHOP, _MCW_RC);
353 #endif
356 void RestoreFPUMode(const FPUCtl *ctl)
358 #ifdef HAVE_FENV_H
359 fesetenv(&ctl->flt_env);
360 #ifdef _WIN32
361 fesetround(ctl->round_mode);
362 #endif
363 #if defined(__GNUC__) && defined(HAVE_SSE)
364 if((CPUCapFlags&CPU_CAP_SSE))
365 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
366 #endif
368 #elif defined(HAVE___CONTROL87_2)
370 int mode;
371 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
372 #ifdef HAVE_SSE
373 if((CPUCapFlags&CPU_CAP_SSE))
374 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
375 #endif
377 #elif defined(HAVE__CONTROLFP)
379 _controlfp(ctl->state, _MCW_RC);
380 #endif
384 static int StringSortCompare(const void *str1, const void *str2)
386 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
389 #ifdef _WIN32
391 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
393 WCHAR *ret = NULL;
394 while(*str)
396 if(*str == ch)
397 ret = str;
398 ++str;
400 return ret;
403 void GetProcBinary(al_string *path, al_string *fname)
405 WCHAR *pathname, *sep;
406 DWORD pathlen;
407 DWORD len;
409 pathlen = 256;
410 pathname = malloc(pathlen * sizeof(pathname[0]));
411 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
413 free(pathname);
414 pathlen <<= 1;
415 pathname = malloc(pathlen * sizeof(pathname[0]));
417 if(len == 0)
419 free(pathname);
420 ERR("Failed to get process name: error %lu\n", GetLastError());
421 return;
424 pathname[len] = 0;
425 if((sep=strrchrW(pathname, '\\')) != NULL)
427 WCHAR *sep2 = strrchrW(sep+1, '/');
428 if(sep2) sep = sep2;
430 else
431 sep = strrchrW(pathname, '/');
433 if(sep)
435 if(path) alstr_copy_wrange(path, pathname, sep);
436 if(fname) alstr_copy_wcstr(fname, sep+1);
438 else
440 if(path) alstr_clear(path);
441 if(fname) alstr_copy_wcstr(fname, pathname);
443 free(pathname);
445 if(path && fname)
446 TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
447 else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
448 else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
452 static WCHAR *FromUTF8(const char *str)
454 WCHAR *out = NULL;
455 int len;
457 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
459 out = calloc(sizeof(WCHAR), len);
460 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
462 return out;
466 void *LoadLib(const char *name)
468 HANDLE hdl = NULL;
469 WCHAR *wname;
471 wname = FromUTF8(name);
472 if(!wname)
473 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
474 else
476 hdl = LoadLibraryW(wname);
477 free(wname);
479 return hdl;
481 void CloseLib(void *handle)
482 { FreeLibrary((HANDLE)handle); }
483 void *GetSymbol(void *handle, const char *name)
485 void *ret;
487 ret = (void*)GetProcAddress((HANDLE)handle, name);
488 if(ret == NULL)
489 ERR("Failed to load %s\n", name);
490 return ret;
493 WCHAR *strdupW(const WCHAR *str)
495 const WCHAR *n;
496 WCHAR *ret;
497 size_t len;
499 n = str;
500 while(*n) n++;
501 len = n - str;
503 ret = calloc(sizeof(WCHAR), len+1);
504 if(ret != NULL)
505 memcpy(ret, str, sizeof(WCHAR)*len);
506 return ret;
509 FILE *al_fopen(const char *fname, const char *mode)
511 WCHAR *wname=NULL, *wmode=NULL;
512 FILE *file = NULL;
514 wname = FromUTF8(fname);
515 wmode = FromUTF8(mode);
516 if(!wname)
517 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
518 else if(!wmode)
519 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
520 else
521 file = _wfopen(wname, wmode);
523 free(wname);
524 free(wmode);
526 return file;
530 void al_print(const char *type, const char *func, const char *fmt, ...)
532 char str[1024];
533 WCHAR *wstr;
534 va_list ap;
536 va_start(ap, fmt);
537 vsnprintf(str, sizeof(str), fmt, ap);
538 va_end(ap);
540 str[sizeof(str)-1] = 0;
541 wstr = FromUTF8(str);
542 if(!wstr)
543 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
544 else
546 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
547 free(wstr);
548 wstr = NULL;
550 fflush(LogFile);
554 static inline int is_slash(int c)
555 { return (c == '\\' || c == '/'); }
557 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
559 al_string pathstr = AL_STRING_INIT_STATIC();
560 WIN32_FIND_DATAW fdata;
561 WCHAR *wpath;
562 HANDLE hdl;
564 alstr_copy_cstr(&pathstr, path);
565 alstr_append_cstr(&pathstr, "\\*");
566 alstr_append_cstr(&pathstr, ext);
568 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
570 wpath = FromUTF8(alstr_get_cstr(pathstr));
572 hdl = FindFirstFileW(wpath, &fdata);
573 if(hdl != INVALID_HANDLE_VALUE)
575 size_t base = VECTOR_SIZE(*results);
576 do {
577 al_string str = AL_STRING_INIT_STATIC();
578 alstr_copy_cstr(&str, path);
579 alstr_append_char(&str, '\\');
580 alstr_append_wcstr(&str, fdata.cFileName);
581 TRACE("Got result %s\n", alstr_get_cstr(str));
582 VECTOR_PUSH_BACK(*results, str);
583 } while(FindNextFileW(hdl, &fdata));
584 FindClose(hdl);
586 if(VECTOR_SIZE(*results) > base)
587 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
588 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
591 free(wpath);
592 alstr_reset(&pathstr);
595 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
597 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
598 static RefCount search_lock;
599 vector_al_string results = VECTOR_INIT_STATIC();
600 size_t i;
602 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
603 althrd_yield();
605 /* If the path is absolute, use it directly. */
606 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
608 al_string path = AL_STRING_INIT_STATIC();
609 alstr_copy_cstr(&path, subdir);
610 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
611 VECTOR_FOR_EACH(char, path, FIX_SLASH);
612 #undef FIX_SLASH
614 DirectorySearch(alstr_get_cstr(path), ext, &results);
616 alstr_reset(&path);
618 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
619 DirectorySearch(subdir, ext, &results);
620 else
622 al_string path = AL_STRING_INIT_STATIC();
623 WCHAR *cwdbuf;
625 /* Search the app-local directory. */
626 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
628 alstr_copy_wcstr(&path, cwdbuf);
629 if(is_slash(VECTOR_BACK(path)))
631 VECTOR_POP_BACK(path);
632 *VECTOR_END(path) = 0;
635 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
636 alstr_copy_cstr(&path, ".");
637 else
639 alstr_copy_wcstr(&path, cwdbuf);
640 if(is_slash(VECTOR_BACK(path)))
642 VECTOR_POP_BACK(path);
643 *VECTOR_END(path) = 0;
645 free(cwdbuf);
647 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
648 VECTOR_FOR_EACH(char, path, FIX_SLASH);
649 #undef FIX_SLASH
650 DirectorySearch(alstr_get_cstr(path), ext, &results);
652 /* Search the local and global data dirs. */
653 for(i = 0;i < COUNTOF(ids);i++)
655 WCHAR buffer[MAX_PATH];
656 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
658 alstr_copy_wcstr(&path, buffer);
659 if(!is_slash(VECTOR_BACK(path)))
660 alstr_append_char(&path, '\\');
661 alstr_append_cstr(&path, subdir);
662 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
663 VECTOR_FOR_EACH(char, path, FIX_SLASH);
664 #undef FIX_SLASH
666 DirectorySearch(alstr_get_cstr(path), ext, &results);
670 alstr_reset(&path);
673 ATOMIC_STORE_SEQ(&search_lock, 0);
675 return results;
679 struct FileMapping MapFileToMem(const char *fname)
681 struct FileMapping ret = { NULL, NULL, NULL, 0 };
682 MEMORY_BASIC_INFORMATION meminfo;
683 HANDLE file, fmap;
684 WCHAR *wname;
685 void *ptr;
687 wname = FromUTF8(fname);
689 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
690 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
691 if(file == INVALID_HANDLE_VALUE)
693 ERR("Failed to open %s: %lu\n", fname, GetLastError());
694 free(wname);
695 return ret;
697 free(wname);
698 wname = NULL;
700 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
701 if(!fmap)
703 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
704 CloseHandle(file);
705 return ret;
708 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
709 if(!ptr)
711 ERR("Failed to map %s: %lu\n", fname, GetLastError());
712 CloseHandle(fmap);
713 CloseHandle(file);
714 return ret;
717 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
719 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
720 UnmapViewOfFile(ptr);
721 CloseHandle(fmap);
722 CloseHandle(file);
723 return ret;
726 ret.file = file;
727 ret.fmap = fmap;
728 ret.ptr = ptr;
729 ret.len = meminfo.RegionSize;
730 return ret;
733 void UnmapFileMem(const struct FileMapping *mapping)
735 UnmapViewOfFile(mapping->ptr);
736 CloseHandle(mapping->fmap);
737 CloseHandle(mapping->file);
740 #else
742 void GetProcBinary(al_string *path, al_string *fname)
744 char *pathname = NULL;
745 size_t pathlen;
747 #ifdef __FreeBSD__
748 int mib[4] = { CTL_KERN, KERN_PROC_ARGS, getpid() };
749 if(sysctl(mib, 3, NULL, &pathlen, NULL, 0) == -1)
750 WARN("Failed to sysctl kern.procargs.%d: %s\n", mib[2], strerror(errno));
751 else
753 pathname = malloc(pathlen + 1);
754 sysctl(mib, 3, (void*)pathname, &pathlen, NULL, 0);
755 pathname[pathlen] = 0;
757 #endif
758 if(!pathname)
760 const char *selfname;
761 ssize_t len;
763 pathlen = 256;
764 pathname = malloc(pathlen);
766 selfname = "/proc/self/exe";
767 len = readlink(selfname, pathname, pathlen);
768 if(len == -1 && errno == ENOENT)
770 selfname = "/proc/self/file";
771 len = readlink(selfname, pathname, pathlen);
773 if(len == -1 && errno == ENOENT)
775 selfname = "/proc/curproc/exe";
776 len = readlink(selfname, pathname, pathlen);
778 if(len == -1 && errno == ENOENT)
780 selfname = "/proc/curproc/file";
781 len = readlink(selfname, pathname, pathlen);
784 while(len > 0 && (size_t)len == pathlen)
786 free(pathname);
787 pathlen <<= 1;
788 pathname = malloc(pathlen);
789 len = readlink(selfname, pathname, pathlen);
791 if(len <= 0)
793 free(pathname);
794 WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
795 return;
798 pathname[len] = 0;
801 char *sep = strrchr(pathname, '/');
802 if(sep)
804 if(path) alstr_copy_range(path, pathname, sep);
805 if(fname) alstr_copy_cstr(fname, sep+1);
807 else
809 if(path) alstr_clear(path);
810 if(fname) alstr_copy_cstr(fname, pathname);
812 free(pathname);
814 if(path && fname)
815 TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
816 else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
817 else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
821 #ifdef HAVE_DLFCN_H
823 void *LoadLib(const char *name)
825 const char *err;
826 void *handle;
828 dlerror();
829 handle = dlopen(name, RTLD_NOW);
830 if((err=dlerror()) != NULL)
831 handle = NULL;
832 return handle;
834 void CloseLib(void *handle)
835 { dlclose(handle); }
836 void *GetSymbol(void *handle, const char *name)
838 const char *err;
839 void *sym;
841 dlerror();
842 sym = dlsym(handle, name);
843 if((err=dlerror()) != NULL)
845 WARN("Failed to load %s: %s\n", name, err);
846 sym = NULL;
848 return sym;
851 #endif /* HAVE_DLFCN_H */
853 void al_print(const char *type, const char *func, const char *fmt, ...)
855 va_list ap;
857 va_start(ap, fmt);
858 fprintf(LogFile, "AL lib: %s %s: ", type, func);
859 vfprintf(LogFile, fmt, ap);
860 va_end(ap);
862 fflush(LogFile);
866 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
868 size_t extlen = strlen(ext);
869 DIR *dir;
871 TRACE("Searching %s for *%s\n", path, ext);
872 dir = opendir(path);
873 if(dir != NULL)
875 size_t base = VECTOR_SIZE(*results);
876 struct dirent *dirent;
877 while((dirent=readdir(dir)) != NULL)
879 al_string str;
880 size_t len;
881 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
882 continue;
884 len = strlen(dirent->d_name);
885 if(!(len > extlen))
886 continue;
887 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
888 continue;
890 AL_STRING_INIT(str);
891 alstr_copy_cstr(&str, path);
892 if(VECTOR_BACK(str) != '/')
893 alstr_append_char(&str, '/');
894 alstr_append_cstr(&str, dirent->d_name);
895 TRACE("Got result %s\n", alstr_get_cstr(str));
896 VECTOR_PUSH_BACK(*results, str);
898 closedir(dir);
900 if(VECTOR_SIZE(*results) > base)
901 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
902 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
906 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
908 static RefCount search_lock;
909 vector_al_string results = VECTOR_INIT_STATIC();
911 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
912 althrd_yield();
914 if(subdir[0] == '/')
915 DirectorySearch(subdir, ext, &results);
916 else
918 al_string path = AL_STRING_INIT_STATIC();
919 const char *str, *next;
921 /* Search the app-local directory. */
922 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
923 DirectorySearch(str, ext, &results);
924 else
926 size_t cwdlen = 256;
927 char *cwdbuf = malloc(cwdlen);
928 while(!getcwd(cwdbuf, cwdlen))
930 free(cwdbuf);
931 cwdbuf = NULL;
932 if(errno != ERANGE)
933 break;
934 cwdlen <<= 1;
935 cwdbuf = malloc(cwdlen);
937 if(!cwdbuf)
938 DirectorySearch(".", ext, &results);
939 else
941 DirectorySearch(cwdbuf, ext, &results);
942 free(cwdbuf);
943 cwdbuf = NULL;
947 // Search local data dir
948 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
950 alstr_copy_cstr(&path, str);
951 if(VECTOR_BACK(path) != '/')
952 alstr_append_char(&path, '/');
953 alstr_append_cstr(&path, subdir);
954 DirectorySearch(alstr_get_cstr(path), ext, &results);
956 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
958 alstr_copy_cstr(&path, str);
959 if(VECTOR_BACK(path) == '/')
961 VECTOR_POP_BACK(path);
962 *VECTOR_END(path) = 0;
964 alstr_append_cstr(&path, "/.local/share/");
965 alstr_append_cstr(&path, subdir);
966 DirectorySearch(alstr_get_cstr(path), ext, &results);
969 // Search global data dirs
970 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
971 str = "/usr/local/share/:/usr/share/";
973 next = str;
974 while((str=next) != NULL && str[0] != '\0')
976 next = strchr(str, ':');
977 if(!next)
978 alstr_copy_cstr(&path, str);
979 else
981 alstr_copy_range(&path, str, next);
982 ++next;
984 if(!alstr_empty(path))
986 if(VECTOR_BACK(path) != '/')
987 alstr_append_char(&path, '/');
988 alstr_append_cstr(&path, subdir);
990 DirectorySearch(alstr_get_cstr(path), ext, &results);
994 alstr_reset(&path);
997 ATOMIC_STORE_SEQ(&search_lock, 0);
999 return results;
1003 struct FileMapping MapFileToMem(const char *fname)
1005 struct FileMapping ret = { -1, NULL, 0 };
1006 struct stat sbuf;
1007 void *ptr;
1008 int fd;
1010 fd = open(fname, O_RDONLY, 0);
1011 if(fd == -1)
1013 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
1014 return ret;
1016 if(fstat(fd, &sbuf) == -1)
1018 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
1019 close(fd);
1020 return ret;
1023 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1024 if(ptr == MAP_FAILED)
1026 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
1027 close(fd);
1028 return ret;
1031 ret.fd = fd;
1032 ret.ptr = ptr;
1033 ret.len = sbuf.st_size;
1034 return ret;
1037 void UnmapFileMem(const struct FileMapping *mapping)
1039 munmap(mapping->ptr, mapping->len);
1040 close(mapping->fd);
1043 #endif
1046 void SetRTPriority(void)
1048 ALboolean failed = AL_FALSE;
1050 #ifdef _WIN32
1051 if(RTPrioLevel > 0)
1052 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
1053 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
1054 if(RTPrioLevel > 0)
1056 struct sched_param param;
1057 /* Use the minimum real-time priority possible for now (on Linux this
1058 * should be 1 for SCHED_RR) */
1059 param.sched_priority = sched_get_priority_min(SCHED_RR);
1060 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
1062 #else
1063 /* Real-time priority not available */
1064 failed = (RTPrioLevel>0);
1065 #endif
1066 if(failed)
1067 ERR("Failed to set priority level for thread\n");
1071 extern inline void alstr_reset(al_string *str);
1072 extern inline size_t alstr_length(const_al_string str);
1073 extern inline ALboolean alstr_empty(const_al_string str);
1074 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1076 void alstr_clear(al_string *str)
1078 if(!alstr_empty(*str))
1080 /* Reserve one more character than the total size of the string. This
1081 * is to ensure we have space to add a null terminator in the string
1082 * data so it can be used as a C-style string.
1084 VECTOR_RESIZE(*str, 0, 1);
1085 VECTOR_ELEM(*str, 0) = 0;
1089 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1090 const al_string_char_type *str2, size_t str2len)
1092 size_t complen = (str1len < str2len) ? str1len : str2len;
1093 int ret = memcmp(str1, str2, complen);
1094 if(ret == 0)
1096 if(str1len > str2len) return 1;
1097 if(str1len < str2len) return -1;
1099 return ret;
1101 int alstr_cmp(const_al_string str1, const_al_string str2)
1103 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1104 &VECTOR_FRONT(str2), alstr_length(str2));
1106 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1108 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1109 str2, strlen(str2));
1112 void alstr_copy(al_string *str, const_al_string from)
1114 size_t len = alstr_length(from);
1115 size_t i;
1117 VECTOR_RESIZE(*str, len, len+1);
1118 for(i = 0;i < len;i++)
1119 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1120 VECTOR_ELEM(*str, i) = 0;
1123 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1125 size_t len = strlen(from);
1126 size_t i;
1128 VECTOR_RESIZE(*str, len, len+1);
1129 for(i = 0;i < len;i++)
1130 VECTOR_ELEM(*str, i) = from[i];
1131 VECTOR_ELEM(*str, i) = 0;
1134 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1136 size_t len = to - from;
1137 size_t i;
1139 VECTOR_RESIZE(*str, len, len+1);
1140 for(i = 0;i < len;i++)
1141 VECTOR_ELEM(*str, i) = from[i];
1142 VECTOR_ELEM(*str, i) = 0;
1145 void alstr_append_char(al_string *str, const al_string_char_type c)
1147 size_t len = alstr_length(*str);
1148 VECTOR_RESIZE(*str, len, len+2);
1149 VECTOR_PUSH_BACK(*str, c);
1150 VECTOR_ELEM(*str, len+1) = 0;
1153 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1155 size_t len = strlen(from);
1156 if(len != 0)
1158 size_t base = alstr_length(*str);
1159 size_t i;
1161 VECTOR_RESIZE(*str, base+len, base+len+1);
1162 for(i = 0;i < len;i++)
1163 VECTOR_ELEM(*str, base+i) = from[i];
1164 VECTOR_ELEM(*str, base+i) = 0;
1168 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1170 size_t len = to - from;
1171 if(len != 0)
1173 size_t base = alstr_length(*str);
1174 size_t i;
1176 VECTOR_RESIZE(*str, base+len, base+len+1);
1177 for(i = 0;i < len;i++)
1178 VECTOR_ELEM(*str, base+i) = from[i];
1179 VECTOR_ELEM(*str, base+i) = 0;
1183 #ifdef _WIN32
1184 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1186 int len;
1187 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1189 VECTOR_RESIZE(*str, len-1, len);
1190 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1191 VECTOR_ELEM(*str, len-1) = 0;
1195 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1197 int len;
1198 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1200 size_t base = alstr_length(*str);
1201 VECTOR_RESIZE(*str, base+len-1, base+len);
1202 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1203 VECTOR_ELEM(*str, base+len-1) = 0;
1207 void alstr_copy_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1209 int len;
1210 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1212 VECTOR_RESIZE(*str, len, len+1);
1213 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_FRONT(*str), len+1, NULL, NULL);
1214 VECTOR_ELEM(*str, len) = 0;
1218 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1220 int len;
1221 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1223 size_t base = alstr_length(*str);
1224 VECTOR_RESIZE(*str, base+len, base+len+1);
1225 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1226 VECTOR_ELEM(*str, base+len) = 0;
1229 #endif