Always link to ossaudio when found
[openal-soft.git] / Alc / helpers.c
blob8e6306aed497bd5c14d7a6f15f53e5aa2c307521
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/sysctl.h>
45 #endif
47 #ifndef AL_NO_UID_DEFS
48 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
49 #define INITGUID
50 #include <windows.h>
51 #ifdef HAVE_GUIDDEF_H
52 #include <guiddef.h>
53 #else
54 #include <initguid.h>
55 #endif
57 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
58 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
60 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
62 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
63 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
64 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
65 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
66 DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
68 #ifdef HAVE_MMDEVAPI
69 #include <wtypes.h>
70 #include <devpropdef.h>
71 #include <propkeydef.h>
72 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
73 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
74 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
75 #endif
76 #endif
77 #endif /* AL_NO_UID_DEFS */
79 #ifdef HAVE_DLFCN_H
80 #include <dlfcn.h>
81 #endif
82 #ifdef HAVE_INTRIN_H
83 #include <intrin.h>
84 #endif
85 #ifdef HAVE_CPUID_H
86 #include <cpuid.h>
87 #endif
88 #ifdef HAVE_SYS_SYSCONF_H
89 #include <sys/sysconf.h>
90 #endif
91 #ifdef HAVE_FLOAT_H
92 #include <float.h>
93 #endif
94 #ifdef HAVE_IEEEFP_H
95 #include <ieeefp.h>
96 #endif
98 #ifndef _WIN32
99 #include <sys/types.h>
100 #include <sys/stat.h>
101 #include <sys/mman.h>
102 #include <fcntl.h>
103 #include <unistd.h>
104 #elif defined(_WIN32_IE)
105 #include <shlobj.h>
106 #endif
108 #include "alMain.h"
109 #include "alu.h"
110 #include "atomic.h"
111 #include "uintmap.h"
112 #include "vector.h"
113 #include "alstring.h"
114 #include "compat.h"
115 #include "threads.h"
118 extern inline ALuint NextPowerOf2(ALuint value);
119 extern inline size_t RoundUp(size_t value, size_t r);
120 extern inline ALuint64 ScaleRound(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
121 extern inline ALuint64 ScaleFloor(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
122 extern inline ALuint64 ScaleCeil(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
123 extern inline ALint fastf2i(ALfloat f);
126 ALuint CPUCapFlags = 0;
129 void FillCPUCaps(ALuint capfilter)
131 ALuint caps = 0;
133 /* FIXME: We really should get this for all available CPUs in case different
134 * CPUs have different caps (is that possible on one machine?). */
135 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
136 defined(_M_IX86) || defined(_M_X64))
137 union {
138 unsigned int regs[4];
139 char str[sizeof(unsigned int[4])];
140 } cpuinf[3];
142 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
143 ERR("Failed to get CPUID\n");
144 else
146 unsigned int maxfunc = cpuinf[0].regs[0];
147 unsigned int maxextfunc = 0;
149 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
150 maxextfunc = cpuinf[0].regs[0];
151 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
153 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
154 if(maxextfunc >= 0x80000004 &&
155 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
156 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
157 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
158 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
160 if(maxfunc >= 1 &&
161 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
163 if((cpuinf[0].regs[3]&(1<<25)))
165 caps |= CPU_CAP_SSE;
166 if((cpuinf[0].regs[3]&(1<<26)))
168 caps |= CPU_CAP_SSE2;
169 if((cpuinf[0].regs[2]&(1<<0)))
171 caps |= CPU_CAP_SSE3;
172 if((cpuinf[0].regs[2]&(1<<19)))
173 caps |= CPU_CAP_SSE4_1;
179 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
180 defined(_M_IX86) || defined(_M_X64))
181 union {
182 int regs[4];
183 char str[sizeof(int[4])];
184 } cpuinf[3];
186 (__cpuid)(cpuinf[0].regs, 0);
187 if(cpuinf[0].regs[0] == 0)
188 ERR("Failed to get CPUID\n");
189 else
191 unsigned int maxfunc = cpuinf[0].regs[0];
192 unsigned int maxextfunc;
194 (__cpuid)(cpuinf[0].regs, 0x80000000);
195 maxextfunc = cpuinf[0].regs[0];
197 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
199 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
200 if(maxextfunc >= 0x80000004)
202 (__cpuid)(cpuinf[0].regs, 0x80000002);
203 (__cpuid)(cpuinf[1].regs, 0x80000003);
204 (__cpuid)(cpuinf[2].regs, 0x80000004);
205 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
208 if(maxfunc >= 1)
210 (__cpuid)(cpuinf[0].regs, 1);
211 if((cpuinf[0].regs[3]&(1<<25)))
213 caps |= CPU_CAP_SSE;
214 if((cpuinf[0].regs[3]&(1<<26)))
216 caps |= CPU_CAP_SSE2;
217 if((cpuinf[0].regs[2]&(1<<0)))
219 caps |= CPU_CAP_SSE3;
220 if((cpuinf[0].regs[2]&(1<<19)))
221 caps |= CPU_CAP_SSE4_1;
227 #else
228 /* Assume support for whatever's supported if we can't check for it */
229 #if defined(HAVE_SSE4_1)
230 #warning "Assuming SSE 4.1 run-time support!"
231 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
232 #elif defined(HAVE_SSE3)
233 #warning "Assuming SSE 3 run-time support!"
234 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
235 #elif defined(HAVE_SSE2)
236 #warning "Assuming SSE 2 run-time support!"
237 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
238 #elif defined(HAVE_SSE)
239 #warning "Assuming SSE run-time support!"
240 caps |= CPU_CAP_SSE;
241 #endif
242 #endif
243 #ifdef HAVE_NEON
244 FILE *file = fopen("/proc/cpuinfo", "rt");
245 if(!file)
246 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
247 else
249 char buf[256];
250 while(fgets(buf, sizeof(buf), file) != NULL)
252 size_t len;
253 char *str;
255 if(strncmp(buf, "Features\t:", 10) != 0)
256 continue;
258 len = strlen(buf);
259 while(len > 0 && isspace(buf[len-1]))
260 buf[--len] = 0;
262 TRACE("Got features string:%s\n", buf+10);
264 str = buf;
265 while((str=strstr(str, "neon")) != NULL)
267 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
269 caps |= CPU_CAP_NEON;
270 break;
272 str++;
274 break;
277 fclose(file);
278 file = NULL;
280 #endif
282 TRACE("Extensions:%s%s%s%s%s%s\n",
283 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
284 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
285 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
286 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
287 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
288 ((!capfilter) ? " -none-" : "")
290 CPUCapFlags = caps & capfilter;
294 void SetMixerFPUMode(FPUCtl *ctl)
296 #ifdef HAVE_FENV_H
297 fegetenv(STATIC_CAST(fenv_t, ctl));
298 #if defined(__GNUC__) && defined(HAVE_SSE)
299 /* FIXME: Some fegetenv implementations can get the SSE environment too?
300 * How to tell when it does? */
301 if((CPUCapFlags&CPU_CAP_SSE))
302 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
303 #endif
305 #ifdef FE_TOWARDZERO
306 fesetround(FE_TOWARDZERO);
307 #endif
308 #if defined(__GNUC__) && defined(HAVE_SSE)
309 if((CPUCapFlags&CPU_CAP_SSE))
311 int sseState = ctl->sse_state;
312 sseState |= 0x6000; /* set round-to-zero */
313 sseState |= 0x8000; /* set flush-to-zero */
314 if((CPUCapFlags&CPU_CAP_SSE2))
315 sseState |= 0x0040; /* set denormals-are-zero */
316 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
318 #endif
320 #elif defined(HAVE___CONTROL87_2)
322 int mode;
323 __control87_2(0, 0, &ctl->state, NULL);
324 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
325 #ifdef HAVE_SSE
326 if((CPUCapFlags&CPU_CAP_SSE))
328 __control87_2(0, 0, NULL, &ctl->sse_state);
329 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
331 #endif
333 #elif defined(HAVE__CONTROLFP)
335 ctl->state = _controlfp(0, 0);
336 (void)_controlfp(_RC_CHOP, _MCW_RC);
337 #endif
340 void RestoreFPUMode(const FPUCtl *ctl)
342 #ifdef HAVE_FENV_H
343 fesetenv(STATIC_CAST(fenv_t, ctl));
344 #if defined(__GNUC__) && defined(HAVE_SSE)
345 if((CPUCapFlags&CPU_CAP_SSE))
346 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
347 #endif
349 #elif defined(HAVE___CONTROL87_2)
351 int mode;
352 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
353 #ifdef HAVE_SSE
354 if((CPUCapFlags&CPU_CAP_SSE))
355 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
356 #endif
358 #elif defined(HAVE__CONTROLFP)
360 _controlfp(ctl->state, _MCW_RC);
361 #endif
365 static int StringSortCompare(const void *str1, const void *str2)
367 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
370 #ifdef _WIN32
372 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
374 WCHAR *ret = NULL;
375 while(*str)
377 if(*str == ch)
378 ret = str;
379 ++str;
381 return ret;
384 al_string GetProcPath(void)
386 al_string ret = AL_STRING_INIT_STATIC();
387 WCHAR *pathname, *sep;
388 DWORD pathlen;
389 DWORD len;
391 pathlen = 256;
392 pathname = malloc(pathlen * sizeof(pathname[0]));
393 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
395 free(pathname);
396 pathlen <<= 1;
397 pathname = malloc(pathlen * sizeof(pathname[0]));
399 if(len == 0)
401 free(pathname);
402 ERR("Failed to get process name: error %lu\n", GetLastError());
403 return ret;
406 pathname[len] = 0;
407 if((sep = strrchrW(pathname, '\\')))
409 WCHAR *sep2 = strrchrW(pathname, '/');
410 if(sep2) *sep2 = 0;
411 else *sep = 0;
413 else if((sep = strrchrW(pathname, '/')))
414 *sep = 0;
415 alstr_copy_wcstr(&ret, pathname);
416 free(pathname);
418 TRACE("Got: %s\n", alstr_get_cstr(ret));
419 return ret;
423 static WCHAR *FromUTF8(const char *str)
425 WCHAR *out = NULL;
426 int len;
428 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
430 out = calloc(sizeof(WCHAR), len);
431 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
433 return out;
437 void *LoadLib(const char *name)
439 HANDLE hdl = NULL;
440 WCHAR *wname;
442 wname = FromUTF8(name);
443 if(!wname)
444 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
445 else
447 hdl = LoadLibraryW(wname);
448 free(wname);
450 return hdl;
452 void CloseLib(void *handle)
453 { FreeLibrary((HANDLE)handle); }
454 void *GetSymbol(void *handle, const char *name)
456 void *ret;
458 ret = (void*)GetProcAddress((HANDLE)handle, name);
459 if(ret == NULL)
460 ERR("Failed to load %s\n", name);
461 return ret;
464 WCHAR *strdupW(const WCHAR *str)
466 const WCHAR *n;
467 WCHAR *ret;
468 size_t len;
470 n = str;
471 while(*n) n++;
472 len = n - str;
474 ret = calloc(sizeof(WCHAR), len+1);
475 if(ret != NULL)
476 memcpy(ret, str, sizeof(WCHAR)*len);
477 return ret;
480 FILE *al_fopen(const char *fname, const char *mode)
482 WCHAR *wname=NULL, *wmode=NULL;
483 FILE *file = NULL;
485 wname = FromUTF8(fname);
486 wmode = FromUTF8(mode);
487 if(!wname)
488 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
489 else if(!wmode)
490 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
491 else
492 file = _wfopen(wname, wmode);
494 free(wname);
495 free(wmode);
497 return file;
501 void al_print(const char *type, const char *func, const char *fmt, ...)
503 char str[1024];
504 WCHAR *wstr;
505 va_list ap;
507 va_start(ap, fmt);
508 vsnprintf(str, sizeof(str), fmt, ap);
509 va_end(ap);
511 str[sizeof(str)-1] = 0;
512 wstr = FromUTF8(str);
513 if(!wstr)
514 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
515 else
517 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
518 free(wstr);
519 wstr = NULL;
521 fflush(LogFile);
525 static inline int is_slash(int c)
526 { return (c == '\\' || c == '/'); }
528 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
530 al_string pathstr = AL_STRING_INIT_STATIC();
531 WIN32_FIND_DATAW fdata;
532 WCHAR *wpath;
533 HANDLE hdl;
535 alstr_copy_cstr(&pathstr, path);
536 alstr_append_cstr(&pathstr, "\\*");
537 alstr_append_cstr(&pathstr, ext);
539 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
541 wpath = FromUTF8(alstr_get_cstr(pathstr));
543 hdl = FindFirstFileW(wpath, &fdata);
544 if(hdl != INVALID_HANDLE_VALUE)
546 size_t base = VECTOR_SIZE(*results);
547 do {
548 al_string str = AL_STRING_INIT_STATIC();
549 alstr_copy_cstr(&str, path);
550 alstr_append_char(&str, '\\');
551 alstr_append_wcstr(&str, fdata.cFileName);
552 TRACE("Got result %s\n", alstr_get_cstr(str));
553 VECTOR_PUSH_BACK(*results, str);
554 } while(FindNextFileW(hdl, &fdata));
555 FindClose(hdl);
557 if(VECTOR_SIZE(*results) > base)
558 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
559 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
562 free(wpath);
563 alstr_reset(&pathstr);
566 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
568 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
569 static RefCount search_lock;
570 vector_al_string results = VECTOR_INIT_STATIC();
571 size_t i;
573 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
574 althrd_yield();
576 /* If the path is absolute, use it directly. */
577 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
579 al_string path = AL_STRING_INIT_STATIC();
580 alstr_copy_cstr(&path, subdir);
581 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
582 VECTOR_FOR_EACH(char, path, FIX_SLASH);
583 #undef FIX_SLASH
585 DirectorySearch(alstr_get_cstr(path), ext, &results);
587 alstr_reset(&path);
589 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
590 DirectorySearch(subdir, ext, &results);
591 else
593 al_string path = AL_STRING_INIT_STATIC();
594 WCHAR *cwdbuf;
596 /* Search the app-local directory. */
597 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
599 alstr_copy_wcstr(&path, cwdbuf);
600 if(is_slash(VECTOR_BACK(path)))
602 VECTOR_POP_BACK(path);
603 *VECTOR_END(path) = 0;
606 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
607 alstr_copy_cstr(&path, ".");
608 else
610 alstr_copy_wcstr(&path, cwdbuf);
611 if(is_slash(VECTOR_BACK(path)))
613 VECTOR_POP_BACK(path);
614 *VECTOR_END(path) = 0;
616 free(cwdbuf);
618 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
619 VECTOR_FOR_EACH(char, path, FIX_SLASH);
620 #undef FIX_SLASH
621 DirectorySearch(alstr_get_cstr(path), ext, &results);
623 /* Search the local and global data dirs. */
624 for(i = 0;i < COUNTOF(ids);i++)
626 WCHAR buffer[PATH_MAX];
627 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
629 alstr_copy_wcstr(&path, buffer);
630 if(!is_slash(VECTOR_BACK(path)))
631 alstr_append_char(&path, '\\');
632 alstr_append_cstr(&path, subdir);
633 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
634 VECTOR_FOR_EACH(char, path, FIX_SLASH);
635 #undef FIX_SLASH
637 DirectorySearch(alstr_get_cstr(path), ext, &results);
641 alstr_reset(&path);
644 ATOMIC_STORE_SEQ(&search_lock, 0);
646 return results;
650 struct FileMapping MapFileToMem(const char *fname)
652 struct FileMapping ret = { NULL, NULL, NULL, 0 };
653 MEMORY_BASIC_INFORMATION meminfo;
654 HANDLE file, fmap;
655 WCHAR *wname;
656 void *ptr;
658 wname = FromUTF8(fname);
660 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
661 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
662 if(file == INVALID_HANDLE_VALUE)
664 ERR("Failed to open %s: %lu\n", fname, GetLastError());
665 free(wname);
666 return ret;
668 free(wname);
669 wname = NULL;
671 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
672 if(!fmap)
674 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
675 CloseHandle(file);
676 return ret;
679 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
680 if(!ptr)
682 ERR("Failed to map %s: %lu\n", fname, GetLastError());
683 CloseHandle(fmap);
684 CloseHandle(file);
685 return ret;
688 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
690 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
691 UnmapViewOfFile(ptr);
692 CloseHandle(fmap);
693 CloseHandle(file);
694 return ret;
697 ret.file = file;
698 ret.fmap = fmap;
699 ret.ptr = ptr;
700 ret.len = meminfo.RegionSize;
701 return ret;
704 void UnmapFileMem(const struct FileMapping *mapping)
706 UnmapViewOfFile(mapping->ptr);
707 CloseHandle(mapping->fmap);
708 CloseHandle(mapping->file);
711 #else
713 al_string GetProcPath(void)
715 al_string ret = AL_STRING_INIT_STATIC();
716 char *pathname, *sep;
717 size_t pathlen;
719 #ifdef __FreeBSD__
720 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
721 mib[3] = getpid();
722 if (sysctl(mib, 4, NULL, &pathlen, NULL, 0) == -1) {
723 WARN("Failed to sysctl kern.proc.pathname.%d: %s\n", mib[3], strerror(errno));
724 return ret;
727 pathname = malloc(pathlen + 1);
728 sysctl(mib, 4, (void*)pathname, &pathlen, NULL, 0);
729 pathname[pathlen] = 0;
730 #else
731 const char *fname;
732 ssize_t len;
734 pathlen = 256;
735 pathname = malloc(pathlen);
737 fname = "/proc/self/exe";
738 len = readlink(fname, pathname, pathlen);
739 if(len == -1 && errno == ENOENT)
741 fname = "/proc/self/file";
742 len = readlink(fname, pathname, pathlen);
745 while(len > 0 && (size_t)len == pathlen)
747 free(pathname);
748 pathlen <<= 1;
749 pathname = malloc(pathlen);
750 len = readlink(fname, pathname, pathlen);
752 if(len <= 0)
754 free(pathname);
755 WARN("Failed to readlink %s: %s\n", fname, strerror(errno));
756 return ret;
759 pathname[len] = 0;
760 #endif
762 sep = strrchr(pathname, '/');
763 if(sep)
764 alstr_copy_range(&ret, pathname, sep);
765 else
766 alstr_copy_cstr(&ret, pathname);
767 free(pathname);
769 TRACE("Got: %s\n", alstr_get_cstr(ret));
770 return ret;
774 #ifdef HAVE_DLFCN_H
776 void *LoadLib(const char *name)
778 const char *err;
779 void *handle;
781 dlerror();
782 handle = dlopen(name, RTLD_NOW);
783 if((err=dlerror()) != NULL)
784 handle = NULL;
785 return handle;
787 void CloseLib(void *handle)
788 { dlclose(handle); }
789 void *GetSymbol(void *handle, const char *name)
791 const char *err;
792 void *sym;
794 dlerror();
795 sym = dlsym(handle, name);
796 if((err=dlerror()) != NULL)
798 WARN("Failed to load %s: %s\n", name, err);
799 sym = NULL;
801 return sym;
804 #endif /* HAVE_DLFCN_H */
806 void al_print(const char *type, const char *func, const char *fmt, ...)
808 va_list ap;
810 va_start(ap, fmt);
811 fprintf(LogFile, "AL lib: %s %s: ", type, func);
812 vfprintf(LogFile, fmt, ap);
813 va_end(ap);
815 fflush(LogFile);
819 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
821 size_t extlen = strlen(ext);
822 DIR *dir;
824 TRACE("Searching %s for *%s\n", path, ext);
825 dir = opendir(path);
826 if(dir != NULL)
828 size_t base = VECTOR_SIZE(*results);
829 struct dirent *dirent;
830 while((dirent=readdir(dir)) != NULL)
832 al_string str;
833 size_t len;
834 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
835 continue;
837 len = strlen(dirent->d_name);
838 if(!(len > extlen))
839 continue;
840 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
841 continue;
843 AL_STRING_INIT(str);
844 alstr_copy_cstr(&str, path);
845 if(VECTOR_BACK(str) != '/')
846 alstr_append_char(&str, '/');
847 alstr_append_cstr(&str, dirent->d_name);
848 TRACE("Got result %s\n", alstr_get_cstr(str));
849 VECTOR_PUSH_BACK(*results, str);
851 closedir(dir);
853 if(VECTOR_SIZE(*results) > base)
854 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
855 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
859 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
861 static RefCount search_lock;
862 vector_al_string results = VECTOR_INIT_STATIC();
864 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
865 althrd_yield();
867 if(subdir[0] == '/')
868 DirectorySearch(subdir, ext, &results);
869 else
871 al_string path = AL_STRING_INIT_STATIC();
872 const char *str, *next;
873 char cwdbuf[PATH_MAX];
875 /* Search the app-local directory. */
876 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
877 DirectorySearch(str, ext, &results);
878 else if(getcwd(cwdbuf, sizeof(cwdbuf)))
879 DirectorySearch(cwdbuf, ext, &results);
880 else
881 DirectorySearch(".", ext, &results);
883 // Search local data dir
884 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
886 alstr_copy_cstr(&path, str);
887 if(VECTOR_BACK(path) != '/')
888 alstr_append_char(&path, '/');
889 alstr_append_cstr(&path, subdir);
890 DirectorySearch(alstr_get_cstr(path), ext, &results);
892 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
894 alstr_copy_cstr(&path, str);
895 if(VECTOR_BACK(path) == '/')
897 VECTOR_POP_BACK(path);
898 *VECTOR_END(path) = 0;
900 alstr_append_cstr(&path, "/.local/share/");
901 alstr_append_cstr(&path, subdir);
902 DirectorySearch(alstr_get_cstr(path), ext, &results);
905 // Search global data dirs
906 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
907 str = "/usr/local/share/:/usr/share/";
909 next = str;
910 while((str=next) != NULL && str[0] != '\0')
912 next = strchr(str, ':');
913 if(!next)
914 alstr_copy_cstr(&path, str);
915 else
917 alstr_copy_range(&path, str, next);
918 ++next;
920 if(!alstr_empty(path))
922 if(VECTOR_BACK(path) != '/')
923 alstr_append_char(&path, '/');
924 alstr_append_cstr(&path, subdir);
926 DirectorySearch(alstr_get_cstr(path), ext, &results);
930 alstr_reset(&path);
933 ATOMIC_STORE_SEQ(&search_lock, 0);
935 return results;
939 struct FileMapping MapFileToMem(const char *fname)
941 struct FileMapping ret = { -1, NULL, 0 };
942 struct stat sbuf;
943 void *ptr;
944 int fd;
946 fd = open(fname, O_RDONLY, 0);
947 if(fd == -1)
949 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
950 return ret;
952 if(fstat(fd, &sbuf) == -1)
954 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
955 close(fd);
956 return ret;
959 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
960 if(ptr == MAP_FAILED)
962 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
963 close(fd);
964 return ret;
967 ret.fd = fd;
968 ret.ptr = ptr;
969 ret.len = sbuf.st_size;
970 return ret;
973 void UnmapFileMem(const struct FileMapping *mapping)
975 munmap(mapping->ptr, mapping->len);
976 close(mapping->fd);
979 #endif
982 void SetRTPriority(void)
984 ALboolean failed = AL_FALSE;
986 #ifdef _WIN32
987 if(RTPrioLevel > 0)
988 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
989 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
990 if(RTPrioLevel > 0)
992 struct sched_param param;
993 /* Use the minimum real-time priority possible for now (on Linux this
994 * should be 1 for SCHED_RR) */
995 param.sched_priority = sched_get_priority_min(SCHED_RR);
996 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
998 #else
999 /* Real-time priority not available */
1000 failed = (RTPrioLevel>0);
1001 #endif
1002 if(failed)
1003 ERR("Failed to set priority level for thread\n");
1007 extern inline void alstr_reset(al_string *str);
1008 extern inline size_t alstr_length(const_al_string str);
1009 extern inline ALboolean alstr_empty(const_al_string str);
1010 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1012 void alstr_clear(al_string *str)
1014 if(!alstr_empty(*str))
1016 /* Reserve one more character than the total size of the string. This
1017 * is to ensure we have space to add a null terminator in the string
1018 * data so it can be used as a C-style string.
1020 VECTOR_RESIZE(*str, 0, 1);
1021 VECTOR_ELEM(*str, 0) = 0;
1025 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1026 const al_string_char_type *str2, size_t str2len)
1028 size_t complen = (str1len < str2len) ? str1len : str2len;
1029 int ret = memcmp(str1, str2, complen);
1030 if(ret == 0)
1032 if(str1len > str2len) return 1;
1033 if(str1len < str2len) return -1;
1035 return ret;
1037 int alstr_cmp(const_al_string str1, const_al_string str2)
1039 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1040 &VECTOR_FRONT(str2), alstr_length(str2));
1042 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1044 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1045 str2, strlen(str2));
1048 void alstr_copy(al_string *str, const_al_string from)
1050 size_t len = alstr_length(from);
1051 size_t i;
1053 VECTOR_RESIZE(*str, len, len+1);
1054 for(i = 0;i < len;i++)
1055 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1056 VECTOR_ELEM(*str, i) = 0;
1059 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1061 size_t len = strlen(from);
1062 size_t i;
1064 VECTOR_RESIZE(*str, len, len+1);
1065 for(i = 0;i < len;i++)
1066 VECTOR_ELEM(*str, i) = from[i];
1067 VECTOR_ELEM(*str, i) = 0;
1070 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1072 size_t len = to - from;
1073 size_t i;
1075 VECTOR_RESIZE(*str, len, len+1);
1076 for(i = 0;i < len;i++)
1077 VECTOR_ELEM(*str, i) = from[i];
1078 VECTOR_ELEM(*str, i) = 0;
1081 void alstr_append_char(al_string *str, const al_string_char_type c)
1083 size_t len = alstr_length(*str);
1084 VECTOR_RESIZE(*str, len, len+2);
1085 VECTOR_PUSH_BACK(*str, c);
1086 VECTOR_ELEM(*str, len+1) = 0;
1089 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1091 size_t len = strlen(from);
1092 if(len != 0)
1094 size_t base = alstr_length(*str);
1095 size_t i;
1097 VECTOR_RESIZE(*str, base+len, base+len+1);
1098 for(i = 0;i < len;i++)
1099 VECTOR_ELEM(*str, base+i) = from[i];
1100 VECTOR_ELEM(*str, base+i) = 0;
1104 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1106 size_t len = to - from;
1107 if(len != 0)
1109 size_t base = alstr_length(*str);
1110 size_t i;
1112 VECTOR_RESIZE(*str, base+len, base+len+1);
1113 for(i = 0;i < len;i++)
1114 VECTOR_ELEM(*str, base+i) = from[i];
1115 VECTOR_ELEM(*str, base+i) = 0;
1119 #ifdef _WIN32
1120 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1122 int len;
1123 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1125 VECTOR_RESIZE(*str, len-1, len);
1126 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1127 VECTOR_ELEM(*str, len-1) = 0;
1131 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1133 int len;
1134 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1136 size_t base = alstr_length(*str);
1137 VECTOR_RESIZE(*str, base+len-1, base+len);
1138 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1139 VECTOR_ELEM(*str, base+len-1) = 0;
1143 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1145 int len;
1146 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1148 size_t base = alstr_length(*str);
1149 VECTOR_RESIZE(*str, base+len, base+len+1);
1150 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1151 VECTOR_ELEM(*str, base+len) = 0;
1154 #endif