Use transposed direct form 2 for the UHJ all-pass filters
[openal-soft.git] / Alc / helpers.c
blobf7adfba0b7e0f71a0c405579289a104dbd3b7157
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
42 #ifdef HAVE_PROC_PIDPATH
43 #include <libproc.h>
44 #endif
46 #ifdef __FreeBSD__
47 #include <sys/types.h>
48 #include <sys/sysctl.h>
49 #endif
51 #ifndef AL_NO_UID_DEFS
52 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
53 #define INITGUID
54 #include <windows.h>
55 #ifdef HAVE_GUIDDEF_H
56 #include <guiddef.h>
57 #else
58 #include <initguid.h>
59 #endif
61 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
62 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
64 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
66 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
67 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
68 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
69 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
70 DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
72 #ifdef HAVE_WASAPI
73 #include <wtypes.h>
74 #include <devpropdef.h>
75 #include <propkeydef.h>
76 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
77 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
78 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
79 #endif
80 #endif
81 #endif /* AL_NO_UID_DEFS */
83 #ifdef HAVE_DLFCN_H
84 #include <dlfcn.h>
85 #endif
86 #ifdef HAVE_INTRIN_H
87 #include <intrin.h>
88 #endif
89 #ifdef HAVE_CPUID_H
90 #include <cpuid.h>
91 #endif
92 #ifdef HAVE_SYS_SYSCONF_H
93 #include <sys/sysconf.h>
94 #endif
95 #ifdef HAVE_FLOAT_H
96 #include <float.h>
97 #endif
98 #ifdef HAVE_IEEEFP_H
99 #include <ieeefp.h>
100 #endif
102 #ifndef _WIN32
103 #include <sys/types.h>
104 #include <sys/stat.h>
105 #include <sys/mman.h>
106 #include <fcntl.h>
107 #include <unistd.h>
108 #elif defined(_WIN32_IE)
109 #include <shlobj.h>
110 #endif
112 #include "alMain.h"
113 #include "alu.h"
114 #include "cpu_caps.h"
115 #include "fpu_modes.h"
116 #include "atomic.h"
117 #include "uintmap.h"
118 #include "vector.h"
119 #include "alstring.h"
120 #include "compat.h"
121 #include "threads.h"
124 extern inline ALuint NextPowerOf2(ALuint value);
125 extern inline size_t RoundUp(size_t value, size_t r);
126 extern inline ALint fastf2i(ALfloat f);
127 #ifndef __GNUC__
128 #if defined(HAVE_BITSCANFORWARD64_INTRINSIC)
129 extern inline int msvc64_ctz64(ALuint64 v);
130 #elif defined(HAVE_BITSCANFORWARD_INTRINSIC)
131 extern inline int msvc_ctz64(ALuint64 v);
132 #else
133 extern inline int fallback_popcnt64(ALuint64 v);
134 extern inline int fallback_ctz64(ALuint64 value);
135 #endif
136 #endif
139 int CPUCapFlags = 0;
141 void FillCPUCaps(int capfilter)
143 int caps = 0;
145 /* FIXME: We really should get this for all available CPUs in case different
146 * CPUs have different caps (is that possible on one machine?). */
147 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
148 defined(_M_IX86) || defined(_M_X64))
149 union {
150 unsigned int regs[4];
151 char str[sizeof(unsigned int[4])];
152 } cpuinf[3];
154 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
155 ERR("Failed to get CPUID\n");
156 else
158 unsigned int maxfunc = cpuinf[0].regs[0];
159 unsigned int maxextfunc = 0;
161 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
162 maxextfunc = cpuinf[0].regs[0];
163 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
165 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
166 if(maxextfunc >= 0x80000004 &&
167 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
168 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
169 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
170 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
172 if(maxfunc >= 1 &&
173 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
175 if((cpuinf[0].regs[3]&(1<<25)))
177 caps |= CPU_CAP_SSE;
178 if((cpuinf[0].regs[3]&(1<<26)))
180 caps |= CPU_CAP_SSE2;
181 if((cpuinf[0].regs[2]&(1<<0)))
183 caps |= CPU_CAP_SSE3;
184 if((cpuinf[0].regs[2]&(1<<19)))
185 caps |= CPU_CAP_SSE4_1;
191 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
192 defined(_M_IX86) || defined(_M_X64))
193 union {
194 int regs[4];
195 char str[sizeof(int[4])];
196 } cpuinf[3];
198 (__cpuid)(cpuinf[0].regs, 0);
199 if(cpuinf[0].regs[0] == 0)
200 ERR("Failed to get CPUID\n");
201 else
203 unsigned int maxfunc = cpuinf[0].regs[0];
204 unsigned int maxextfunc;
206 (__cpuid)(cpuinf[0].regs, 0x80000000);
207 maxextfunc = cpuinf[0].regs[0];
209 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
211 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
212 if(maxextfunc >= 0x80000004)
214 (__cpuid)(cpuinf[0].regs, 0x80000002);
215 (__cpuid)(cpuinf[1].regs, 0x80000003);
216 (__cpuid)(cpuinf[2].regs, 0x80000004);
217 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
220 if(maxfunc >= 1)
222 (__cpuid)(cpuinf[0].regs, 1);
223 if((cpuinf[0].regs[3]&(1<<25)))
225 caps |= CPU_CAP_SSE;
226 if((cpuinf[0].regs[3]&(1<<26)))
228 caps |= CPU_CAP_SSE2;
229 if((cpuinf[0].regs[2]&(1<<0)))
231 caps |= CPU_CAP_SSE3;
232 if((cpuinf[0].regs[2]&(1<<19)))
233 caps |= CPU_CAP_SSE4_1;
239 #else
240 /* Assume support for whatever's supported if we can't check for it */
241 #if defined(HAVE_SSE4_1)
242 #warning "Assuming SSE 4.1 run-time support!"
243 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
244 #elif defined(HAVE_SSE3)
245 #warning "Assuming SSE 3 run-time support!"
246 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
247 #elif defined(HAVE_SSE2)
248 #warning "Assuming SSE 2 run-time support!"
249 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
250 #elif defined(HAVE_SSE)
251 #warning "Assuming SSE run-time support!"
252 caps |= CPU_CAP_SSE;
253 #endif
254 #endif
255 #ifdef HAVE_NEON
256 FILE *file = fopen("/proc/cpuinfo", "rt");
257 if(!file)
258 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
259 else
261 char buf[256];
262 while(fgets(buf, sizeof(buf), file) != NULL)
264 size_t len;
265 char *str;
267 if(strncmp(buf, "Features\t:", 10) != 0)
268 continue;
270 len = strlen(buf);
271 while(len > 0 && isspace(buf[len-1]))
272 buf[--len] = 0;
274 TRACE("Got features string:%s\n", buf+10);
276 str = buf;
277 while((str=strstr(str, "neon")) != NULL)
279 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
281 caps |= CPU_CAP_NEON;
282 break;
284 str++;
286 break;
289 fclose(file);
290 file = NULL;
292 #endif
294 TRACE("Extensions:%s%s%s%s%s%s\n",
295 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
296 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
297 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
298 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
299 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
300 ((!capfilter) ? " -none-" : "")
302 CPUCapFlags = caps & capfilter;
306 void SetMixerFPUMode(FPUCtl *ctl)
308 #ifdef HAVE_FENV_H
309 fegetenv(&ctl->flt_env);
310 #ifdef _WIN32
311 /* HACK: A nasty bug in MinGW-W64 causes fegetenv and fesetenv to not save
312 * and restore the FPU rounding mode, so we have to do it manually. Don't
313 * know if this also applies to MSVC.
315 ctl->round_mode = fegetround();
316 #endif
317 #if defined(__GNUC__) && defined(HAVE_SSE)
318 /* FIXME: Some fegetenv implementations can get the SSE environment too?
319 * How to tell when it does? */
320 if((CPUCapFlags&CPU_CAP_SSE))
321 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
322 #endif
324 #ifdef FE_TOWARDZERO
325 fesetround(FE_TOWARDZERO);
326 #endif
327 #if defined(__GNUC__) && defined(HAVE_SSE)
328 if((CPUCapFlags&CPU_CAP_SSE))
330 int sseState = ctl->sse_state;
331 sseState |= 0x6000; /* set round-to-zero */
332 sseState |= 0x8000; /* set flush-to-zero */
333 if((CPUCapFlags&CPU_CAP_SSE2))
334 sseState |= 0x0040; /* set denormals-are-zero */
335 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
337 #endif
339 #elif defined(HAVE___CONTROL87_2)
341 int mode;
342 __control87_2(0, 0, &ctl->state, NULL);
343 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
344 #ifdef HAVE_SSE
345 if((CPUCapFlags&CPU_CAP_SSE))
347 __control87_2(0, 0, NULL, &ctl->sse_state);
348 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
350 #endif
352 #elif defined(HAVE__CONTROLFP)
354 ctl->state = _controlfp(0, 0);
355 (void)_controlfp(_RC_CHOP, _MCW_RC);
356 #endif
359 void RestoreFPUMode(const FPUCtl *ctl)
361 #ifdef HAVE_FENV_H
362 fesetenv(&ctl->flt_env);
363 #ifdef _WIN32
364 fesetround(ctl->round_mode);
365 #endif
366 #if defined(__GNUC__) && defined(HAVE_SSE)
367 if((CPUCapFlags&CPU_CAP_SSE))
368 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
369 #endif
371 #elif defined(HAVE___CONTROL87_2)
373 int mode;
374 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
375 #ifdef HAVE_SSE
376 if((CPUCapFlags&CPU_CAP_SSE))
377 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
378 #endif
380 #elif defined(HAVE__CONTROLFP)
382 _controlfp(ctl->state, _MCW_RC);
383 #endif
387 static int StringSortCompare(const void *str1, const void *str2)
389 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
392 #ifdef _WIN32
394 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
396 WCHAR *ret = NULL;
397 while(*str)
399 if(*str == ch)
400 ret = str;
401 ++str;
403 return ret;
406 void GetProcBinary(al_string *path, al_string *fname)
408 WCHAR *pathname, *sep;
409 DWORD pathlen;
410 DWORD len;
412 pathlen = 256;
413 pathname = malloc(pathlen * sizeof(pathname[0]));
414 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
416 free(pathname);
417 pathlen <<= 1;
418 pathname = malloc(pathlen * sizeof(pathname[0]));
420 if(len == 0)
422 free(pathname);
423 ERR("Failed to get process name: error %lu\n", GetLastError());
424 return;
427 pathname[len] = 0;
428 if((sep=strrchrW(pathname, '\\')) != NULL)
430 WCHAR *sep2 = strrchrW(sep+1, '/');
431 if(sep2) sep = sep2;
433 else
434 sep = strrchrW(pathname, '/');
436 if(sep)
438 if(path) alstr_copy_wrange(path, pathname, sep);
439 if(fname) alstr_copy_wcstr(fname, sep+1);
441 else
443 if(path) alstr_clear(path);
444 if(fname) alstr_copy_wcstr(fname, pathname);
446 free(pathname);
448 if(path && fname)
449 TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
450 else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
451 else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
455 static WCHAR *FromUTF8(const char *str)
457 WCHAR *out = NULL;
458 int len;
460 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
462 out = calloc(sizeof(WCHAR), len);
463 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
465 return out;
469 void *LoadLib(const char *name)
471 HANDLE hdl = NULL;
472 WCHAR *wname;
474 wname = FromUTF8(name);
475 if(!wname)
476 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
477 else
479 hdl = LoadLibraryW(wname);
480 free(wname);
482 return hdl;
484 void CloseLib(void *handle)
485 { FreeLibrary((HANDLE)handle); }
486 void *GetSymbol(void *handle, const char *name)
488 void *ret;
490 ret = (void*)GetProcAddress((HANDLE)handle, name);
491 if(ret == NULL)
492 ERR("Failed to load %s\n", name);
493 return ret;
496 WCHAR *strdupW(const WCHAR *str)
498 const WCHAR *n;
499 WCHAR *ret;
500 size_t len;
502 n = str;
503 while(*n) n++;
504 len = n - str;
506 ret = calloc(sizeof(WCHAR), len+1);
507 if(ret != NULL)
508 memcpy(ret, str, sizeof(WCHAR)*len);
509 return ret;
512 FILE *al_fopen(const char *fname, const char *mode)
514 WCHAR *wname=NULL, *wmode=NULL;
515 FILE *file = NULL;
517 wname = FromUTF8(fname);
518 wmode = FromUTF8(mode);
519 if(!wname)
520 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
521 else if(!wmode)
522 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
523 else
524 file = _wfopen(wname, wmode);
526 free(wname);
527 free(wmode);
529 return file;
533 void al_print(const char *type, const char *func, const char *fmt, ...)
535 char str[1024];
536 WCHAR *wstr;
537 va_list ap;
539 va_start(ap, fmt);
540 vsnprintf(str, sizeof(str), fmt, ap);
541 va_end(ap);
543 str[sizeof(str)-1] = 0;
544 wstr = FromUTF8(str);
545 if(!wstr)
546 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
547 else
549 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
550 free(wstr);
551 wstr = NULL;
553 fflush(LogFile);
557 static inline int is_slash(int c)
558 { return (c == '\\' || c == '/'); }
560 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
562 al_string pathstr = AL_STRING_INIT_STATIC();
563 WIN32_FIND_DATAW fdata;
564 WCHAR *wpath;
565 HANDLE hdl;
567 alstr_copy_cstr(&pathstr, path);
568 alstr_append_cstr(&pathstr, "\\*");
569 alstr_append_cstr(&pathstr, ext);
571 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
573 wpath = FromUTF8(alstr_get_cstr(pathstr));
575 hdl = FindFirstFileW(wpath, &fdata);
576 if(hdl != INVALID_HANDLE_VALUE)
578 size_t base = VECTOR_SIZE(*results);
579 do {
580 al_string str = AL_STRING_INIT_STATIC();
581 alstr_copy_cstr(&str, path);
582 alstr_append_char(&str, '\\');
583 alstr_append_wcstr(&str, fdata.cFileName);
584 TRACE("Got result %s\n", alstr_get_cstr(str));
585 VECTOR_PUSH_BACK(*results, str);
586 } while(FindNextFileW(hdl, &fdata));
587 FindClose(hdl);
589 if(VECTOR_SIZE(*results) > base)
590 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
591 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
594 free(wpath);
595 alstr_reset(&pathstr);
598 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
600 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
601 static RefCount search_lock;
602 vector_al_string results = VECTOR_INIT_STATIC();
603 size_t i;
605 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
606 althrd_yield();
608 /* If the path is absolute, use it directly. */
609 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
611 al_string path = AL_STRING_INIT_STATIC();
612 alstr_copy_cstr(&path, subdir);
613 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
614 VECTOR_FOR_EACH(char, path, FIX_SLASH);
615 #undef FIX_SLASH
617 DirectorySearch(alstr_get_cstr(path), ext, &results);
619 alstr_reset(&path);
621 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
622 DirectorySearch(subdir, ext, &results);
623 else
625 al_string path = AL_STRING_INIT_STATIC();
626 WCHAR *cwdbuf;
628 /* Search the app-local directory. */
629 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
631 alstr_copy_wcstr(&path, cwdbuf);
632 if(is_slash(VECTOR_BACK(path)))
634 VECTOR_POP_BACK(path);
635 *VECTOR_END(path) = 0;
638 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
639 alstr_copy_cstr(&path, ".");
640 else
642 alstr_copy_wcstr(&path, cwdbuf);
643 if(is_slash(VECTOR_BACK(path)))
645 VECTOR_POP_BACK(path);
646 *VECTOR_END(path) = 0;
648 free(cwdbuf);
650 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
651 VECTOR_FOR_EACH(char, path, FIX_SLASH);
652 #undef FIX_SLASH
653 DirectorySearch(alstr_get_cstr(path), ext, &results);
655 /* Search the local and global data dirs. */
656 for(i = 0;i < COUNTOF(ids);i++)
658 WCHAR buffer[MAX_PATH];
659 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
661 alstr_copy_wcstr(&path, buffer);
662 if(!is_slash(VECTOR_BACK(path)))
663 alstr_append_char(&path, '\\');
664 alstr_append_cstr(&path, subdir);
665 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
666 VECTOR_FOR_EACH(char, path, FIX_SLASH);
667 #undef FIX_SLASH
669 DirectorySearch(alstr_get_cstr(path), ext, &results);
673 alstr_reset(&path);
676 ATOMIC_STORE_SEQ(&search_lock, 0);
678 return results;
682 struct FileMapping MapFileToMem(const char *fname)
684 struct FileMapping ret = { NULL, NULL, NULL, 0 };
685 MEMORY_BASIC_INFORMATION meminfo;
686 HANDLE file, fmap;
687 WCHAR *wname;
688 void *ptr;
690 wname = FromUTF8(fname);
692 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
693 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
694 if(file == INVALID_HANDLE_VALUE)
696 ERR("Failed to open %s: %lu\n", fname, GetLastError());
697 free(wname);
698 return ret;
700 free(wname);
701 wname = NULL;
703 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
704 if(!fmap)
706 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
707 CloseHandle(file);
708 return ret;
711 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
712 if(!ptr)
714 ERR("Failed to map %s: %lu\n", fname, GetLastError());
715 CloseHandle(fmap);
716 CloseHandle(file);
717 return ret;
720 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
722 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
723 UnmapViewOfFile(ptr);
724 CloseHandle(fmap);
725 CloseHandle(file);
726 return ret;
729 ret.file = file;
730 ret.fmap = fmap;
731 ret.ptr = ptr;
732 ret.len = meminfo.RegionSize;
733 return ret;
736 void UnmapFileMem(const struct FileMapping *mapping)
738 UnmapViewOfFile(mapping->ptr);
739 CloseHandle(mapping->fmap);
740 CloseHandle(mapping->file);
743 #else
745 void GetProcBinary(al_string *path, al_string *fname)
747 char *pathname = NULL;
748 size_t pathlen;
750 #ifdef __FreeBSD__
751 int mib[4] = { CTL_KERN, KERN_PROC_ARGS, getpid() };
752 if(sysctl(mib, 3, NULL, &pathlen, NULL, 0) == -1)
753 WARN("Failed to sysctl kern.procargs.%d: %s\n", mib[2], strerror(errno));
754 else
756 pathname = malloc(pathlen + 1);
757 sysctl(mib, 3, (void*)pathname, &pathlen, NULL, 0);
758 pathname[pathlen] = 0;
760 #endif
761 #ifdef HAVE_PROC_PIDPATH
762 if(!pathname)
764 const pid_t pid = getpid();
765 char procpath[PROC_PIDPATHINFO_MAXSIZE];
766 int ret;
768 ret = proc_pidpath(pid, procpath, sizeof(procpath));
769 if(ret < 1)
771 WARN("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
772 free(pathname);
773 pathname = NULL;
775 else
777 pathlen = strlen(procpath);
778 pathname = strdup(procpath);
781 #endif
782 if(!pathname)
784 const char *selfname;
785 ssize_t len;
787 pathlen = 256;
788 pathname = malloc(pathlen);
790 selfname = "/proc/self/exe";
791 len = readlink(selfname, pathname, pathlen);
792 if(len == -1 && errno == ENOENT)
794 selfname = "/proc/self/file";
795 len = readlink(selfname, pathname, pathlen);
797 if(len == -1 && errno == ENOENT)
799 selfname = "/proc/curproc/exe";
800 len = readlink(selfname, pathname, pathlen);
802 if(len == -1 && errno == ENOENT)
804 selfname = "/proc/curproc/file";
805 len = readlink(selfname, pathname, pathlen);
808 while(len > 0 && (size_t)len == pathlen)
810 free(pathname);
811 pathlen <<= 1;
812 pathname = malloc(pathlen);
813 len = readlink(selfname, pathname, pathlen);
815 if(len <= 0)
817 free(pathname);
818 WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
819 return;
822 pathname[len] = 0;
825 char *sep = strrchr(pathname, '/');
826 if(sep)
828 if(path) alstr_copy_range(path, pathname, sep);
829 if(fname) alstr_copy_cstr(fname, sep+1);
831 else
833 if(path) alstr_clear(path);
834 if(fname) alstr_copy_cstr(fname, pathname);
836 free(pathname);
838 if(path && fname)
839 TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
840 else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
841 else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
845 #ifdef HAVE_DLFCN_H
847 void *LoadLib(const char *name)
849 const char *err;
850 void *handle;
852 dlerror();
853 handle = dlopen(name, RTLD_NOW);
854 if((err=dlerror()) != NULL)
855 handle = NULL;
856 return handle;
858 void CloseLib(void *handle)
859 { dlclose(handle); }
860 void *GetSymbol(void *handle, const char *name)
862 const char *err;
863 void *sym;
865 dlerror();
866 sym = dlsym(handle, name);
867 if((err=dlerror()) != NULL)
869 WARN("Failed to load %s: %s\n", name, err);
870 sym = NULL;
872 return sym;
875 #endif /* HAVE_DLFCN_H */
877 void al_print(const char *type, const char *func, const char *fmt, ...)
879 va_list ap;
881 va_start(ap, fmt);
882 fprintf(LogFile, "AL lib: %s %s: ", type, func);
883 vfprintf(LogFile, fmt, ap);
884 va_end(ap);
886 fflush(LogFile);
890 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
892 size_t extlen = strlen(ext);
893 DIR *dir;
895 TRACE("Searching %s for *%s\n", path, ext);
896 dir = opendir(path);
897 if(dir != NULL)
899 size_t base = VECTOR_SIZE(*results);
900 struct dirent *dirent;
901 while((dirent=readdir(dir)) != NULL)
903 al_string str;
904 size_t len;
905 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
906 continue;
908 len = strlen(dirent->d_name);
909 if(!(len > extlen))
910 continue;
911 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
912 continue;
914 AL_STRING_INIT(str);
915 alstr_copy_cstr(&str, path);
916 if(VECTOR_BACK(str) != '/')
917 alstr_append_char(&str, '/');
918 alstr_append_cstr(&str, dirent->d_name);
919 TRACE("Got result %s\n", alstr_get_cstr(str));
920 VECTOR_PUSH_BACK(*results, str);
922 closedir(dir);
924 if(VECTOR_SIZE(*results) > base)
925 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
926 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
930 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
932 static RefCount search_lock;
933 vector_al_string results = VECTOR_INIT_STATIC();
935 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
936 althrd_yield();
938 if(subdir[0] == '/')
939 DirectorySearch(subdir, ext, &results);
940 else
942 al_string path = AL_STRING_INIT_STATIC();
943 const char *str, *next;
945 /* Search the app-local directory. */
946 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
947 DirectorySearch(str, ext, &results);
948 else
950 size_t cwdlen = 256;
951 char *cwdbuf = malloc(cwdlen);
952 while(!getcwd(cwdbuf, cwdlen))
954 free(cwdbuf);
955 cwdbuf = NULL;
956 if(errno != ERANGE)
957 break;
958 cwdlen <<= 1;
959 cwdbuf = malloc(cwdlen);
961 if(!cwdbuf)
962 DirectorySearch(".", ext, &results);
963 else
965 DirectorySearch(cwdbuf, ext, &results);
966 free(cwdbuf);
967 cwdbuf = NULL;
971 // Search local data dir
972 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
974 alstr_copy_cstr(&path, str);
975 if(VECTOR_BACK(path) != '/')
976 alstr_append_char(&path, '/');
977 alstr_append_cstr(&path, subdir);
978 DirectorySearch(alstr_get_cstr(path), ext, &results);
980 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
982 alstr_copy_cstr(&path, str);
983 if(VECTOR_BACK(path) == '/')
985 VECTOR_POP_BACK(path);
986 *VECTOR_END(path) = 0;
988 alstr_append_cstr(&path, "/.local/share/");
989 alstr_append_cstr(&path, subdir);
990 DirectorySearch(alstr_get_cstr(path), ext, &results);
993 // Search global data dirs
994 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
995 str = "/usr/local/share/:/usr/share/";
997 next = str;
998 while((str=next) != NULL && str[0] != '\0')
1000 next = strchr(str, ':');
1001 if(!next)
1002 alstr_copy_cstr(&path, str);
1003 else
1005 alstr_copy_range(&path, str, next);
1006 ++next;
1008 if(!alstr_empty(path))
1010 if(VECTOR_BACK(path) != '/')
1011 alstr_append_char(&path, '/');
1012 alstr_append_cstr(&path, subdir);
1014 DirectorySearch(alstr_get_cstr(path), ext, &results);
1018 alstr_reset(&path);
1021 ATOMIC_STORE_SEQ(&search_lock, 0);
1023 return results;
1027 struct FileMapping MapFileToMem(const char *fname)
1029 struct FileMapping ret = { -1, NULL, 0 };
1030 struct stat sbuf;
1031 void *ptr;
1032 int fd;
1034 fd = open(fname, O_RDONLY, 0);
1035 if(fd == -1)
1037 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
1038 return ret;
1040 if(fstat(fd, &sbuf) == -1)
1042 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
1043 close(fd);
1044 return ret;
1047 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1048 if(ptr == MAP_FAILED)
1050 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
1051 close(fd);
1052 return ret;
1055 ret.fd = fd;
1056 ret.ptr = ptr;
1057 ret.len = sbuf.st_size;
1058 return ret;
1061 void UnmapFileMem(const struct FileMapping *mapping)
1063 munmap(mapping->ptr, mapping->len);
1064 close(mapping->fd);
1067 #endif
1070 void SetRTPriority(void)
1072 ALboolean failed = AL_FALSE;
1074 #ifdef _WIN32
1075 if(RTPrioLevel > 0)
1076 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
1077 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
1078 if(RTPrioLevel > 0)
1080 struct sched_param param;
1081 /* Use the minimum real-time priority possible for now (on Linux this
1082 * should be 1 for SCHED_RR) */
1083 param.sched_priority = sched_get_priority_min(SCHED_RR);
1084 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
1086 #else
1087 /* Real-time priority not available */
1088 failed = (RTPrioLevel>0);
1089 #endif
1090 if(failed)
1091 ERR("Failed to set priority level for thread\n");
1095 extern inline void alstr_reset(al_string *str);
1096 extern inline size_t alstr_length(const_al_string str);
1097 extern inline ALboolean alstr_empty(const_al_string str);
1098 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1100 void alstr_clear(al_string *str)
1102 if(!alstr_empty(*str))
1104 /* Reserve one more character than the total size of the string. This
1105 * is to ensure we have space to add a null terminator in the string
1106 * data so it can be used as a C-style string.
1108 VECTOR_RESIZE(*str, 0, 1);
1109 VECTOR_ELEM(*str, 0) = 0;
1113 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1114 const al_string_char_type *str2, size_t str2len)
1116 size_t complen = (str1len < str2len) ? str1len : str2len;
1117 int ret = memcmp(str1, str2, complen);
1118 if(ret == 0)
1120 if(str1len > str2len) return 1;
1121 if(str1len < str2len) return -1;
1123 return ret;
1125 int alstr_cmp(const_al_string str1, const_al_string str2)
1127 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1128 &VECTOR_FRONT(str2), alstr_length(str2));
1130 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1132 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1133 str2, strlen(str2));
1136 void alstr_copy(al_string *str, const_al_string from)
1138 size_t len = alstr_length(from);
1139 size_t i;
1141 VECTOR_RESIZE(*str, len, len+1);
1142 for(i = 0;i < len;i++)
1143 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1144 VECTOR_ELEM(*str, i) = 0;
1147 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1149 size_t len = strlen(from);
1150 size_t i;
1152 VECTOR_RESIZE(*str, len, len+1);
1153 for(i = 0;i < len;i++)
1154 VECTOR_ELEM(*str, i) = from[i];
1155 VECTOR_ELEM(*str, i) = 0;
1158 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1160 size_t len = to - from;
1161 size_t i;
1163 VECTOR_RESIZE(*str, len, len+1);
1164 for(i = 0;i < len;i++)
1165 VECTOR_ELEM(*str, i) = from[i];
1166 VECTOR_ELEM(*str, i) = 0;
1169 void alstr_append_char(al_string *str, const al_string_char_type c)
1171 size_t len = alstr_length(*str);
1172 VECTOR_RESIZE(*str, len, len+2);
1173 VECTOR_PUSH_BACK(*str, c);
1174 VECTOR_ELEM(*str, len+1) = 0;
1177 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1179 size_t len = strlen(from);
1180 if(len != 0)
1182 size_t base = alstr_length(*str);
1183 size_t i;
1185 VECTOR_RESIZE(*str, base+len, base+len+1);
1186 for(i = 0;i < len;i++)
1187 VECTOR_ELEM(*str, base+i) = from[i];
1188 VECTOR_ELEM(*str, base+i) = 0;
1192 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1194 size_t len = to - from;
1195 if(len != 0)
1197 size_t base = alstr_length(*str);
1198 size_t i;
1200 VECTOR_RESIZE(*str, base+len, base+len+1);
1201 for(i = 0;i < len;i++)
1202 VECTOR_ELEM(*str, base+i) = from[i];
1203 VECTOR_ELEM(*str, base+i) = 0;
1207 #ifdef _WIN32
1208 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1210 int len;
1211 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1213 VECTOR_RESIZE(*str, len-1, len);
1214 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1215 VECTOR_ELEM(*str, len-1) = 0;
1219 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1221 int len;
1222 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1224 size_t base = alstr_length(*str);
1225 VECTOR_RESIZE(*str, base+len-1, base+len);
1226 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1227 VECTOR_ELEM(*str, base+len-1) = 0;
1231 void alstr_copy_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1233 int len;
1234 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1236 VECTOR_RESIZE(*str, len, len+1);
1237 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_FRONT(*str), len+1, NULL, NULL);
1238 VECTOR_ELEM(*str, len) = 0;
1242 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1244 int len;
1245 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1247 size_t base = alstr_length(*str);
1248 VECTOR_RESIZE(*str, base+len, base+len+1);
1249 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1250 VECTOR_ELEM(*str, base+len) = 0;
1253 #endif