Round the converter's stepping value
[openal-soft.git] / Alc / helpers.c
blob53623d854642b5188e34710f5c4c026e3e558c35
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);
124 extern inline ALuint fastf2u(ALfloat f);
127 ALuint CPUCapFlags = 0;
130 void FillCPUCaps(ALuint capfilter)
132 ALuint caps = 0;
134 /* FIXME: We really should get this for all available CPUs in case different
135 * CPUs have different caps (is that possible on one machine?). */
136 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
137 defined(_M_IX86) || defined(_M_X64))
138 union {
139 unsigned int regs[4];
140 char str[sizeof(unsigned int[4])];
141 } cpuinf[3];
143 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
144 ERR("Failed to get CPUID\n");
145 else
147 unsigned int maxfunc = cpuinf[0].regs[0];
148 unsigned int maxextfunc = 0;
150 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
151 maxextfunc = cpuinf[0].regs[0];
152 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
154 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
155 if(maxextfunc >= 0x80000004 &&
156 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
157 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
158 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
159 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
161 if(maxfunc >= 1 &&
162 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
164 if((cpuinf[0].regs[3]&(1<<25)))
166 caps |= CPU_CAP_SSE;
167 if((cpuinf[0].regs[3]&(1<<26)))
169 caps |= CPU_CAP_SSE2;
170 if((cpuinf[0].regs[2]&(1<<0)))
172 caps |= CPU_CAP_SSE3;
173 if((cpuinf[0].regs[2]&(1<<19)))
174 caps |= CPU_CAP_SSE4_1;
180 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
181 defined(_M_IX86) || defined(_M_X64))
182 union {
183 int regs[4];
184 char str[sizeof(int[4])];
185 } cpuinf[3];
187 (__cpuid)(cpuinf[0].regs, 0);
188 if(cpuinf[0].regs[0] == 0)
189 ERR("Failed to get CPUID\n");
190 else
192 unsigned int maxfunc = cpuinf[0].regs[0];
193 unsigned int maxextfunc;
195 (__cpuid)(cpuinf[0].regs, 0x80000000);
196 maxextfunc = cpuinf[0].regs[0];
198 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
200 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
201 if(maxextfunc >= 0x80000004)
203 (__cpuid)(cpuinf[0].regs, 0x80000002);
204 (__cpuid)(cpuinf[1].regs, 0x80000003);
205 (__cpuid)(cpuinf[2].regs, 0x80000004);
206 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
209 if(maxfunc >= 1)
211 (__cpuid)(cpuinf[0].regs, 1);
212 if((cpuinf[0].regs[3]&(1<<25)))
214 caps |= CPU_CAP_SSE;
215 if((cpuinf[0].regs[3]&(1<<26)))
217 caps |= CPU_CAP_SSE2;
218 if((cpuinf[0].regs[2]&(1<<0)))
220 caps |= CPU_CAP_SSE3;
221 if((cpuinf[0].regs[2]&(1<<19)))
222 caps |= CPU_CAP_SSE4_1;
228 #else
229 /* Assume support for whatever's supported if we can't check for it */
230 #if defined(HAVE_SSE4_1)
231 #warning "Assuming SSE 4.1 run-time support!"
232 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
233 #elif defined(HAVE_SSE3)
234 #warning "Assuming SSE 3 run-time support!"
235 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
236 #elif defined(HAVE_SSE2)
237 #warning "Assuming SSE 2 run-time support!"
238 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
239 #elif defined(HAVE_SSE)
240 #warning "Assuming SSE run-time support!"
241 caps |= CPU_CAP_SSE;
242 #endif
243 #endif
244 #ifdef HAVE_NEON
245 FILE *file = fopen("/proc/cpuinfo", "rt");
246 if(!file)
247 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
248 else
250 char buf[256];
251 while(fgets(buf, sizeof(buf), file) != NULL)
253 size_t len;
254 char *str;
256 if(strncmp(buf, "Features\t:", 10) != 0)
257 continue;
259 len = strlen(buf);
260 while(len > 0 && isspace(buf[len-1]))
261 buf[--len] = 0;
263 TRACE("Got features string:%s\n", buf+10);
265 str = buf;
266 while((str=strstr(str, "neon")) != NULL)
268 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
270 caps |= CPU_CAP_NEON;
271 break;
273 str++;
275 break;
278 fclose(file);
279 file = NULL;
281 #endif
283 TRACE("Extensions:%s%s%s%s%s%s\n",
284 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
285 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
286 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
287 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
288 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
289 ((!capfilter) ? " -none-" : "")
291 CPUCapFlags = caps & capfilter;
295 void SetMixerFPUMode(FPUCtl *ctl)
297 #ifdef HAVE_FENV_H
298 fegetenv(STATIC_CAST(fenv_t, ctl));
299 #if defined(__GNUC__) && defined(HAVE_SSE)
300 /* FIXME: Some fegetenv implementations can get the SSE environment too?
301 * How to tell when it does? */
302 if((CPUCapFlags&CPU_CAP_SSE))
303 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
304 #endif
306 #ifdef FE_TOWARDZERO
307 fesetround(FE_TOWARDZERO);
308 #endif
309 #if defined(__GNUC__) && defined(HAVE_SSE)
310 if((CPUCapFlags&CPU_CAP_SSE))
312 int sseState = ctl->sse_state;
313 sseState |= 0x6000; /* set round-to-zero */
314 sseState |= 0x8000; /* set flush-to-zero */
315 if((CPUCapFlags&CPU_CAP_SSE2))
316 sseState |= 0x0040; /* set denormals-are-zero */
317 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
319 #endif
321 #elif defined(HAVE___CONTROL87_2)
323 int mode;
324 __control87_2(0, 0, &ctl->state, NULL);
325 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
326 #ifdef HAVE_SSE
327 if((CPUCapFlags&CPU_CAP_SSE))
329 __control87_2(0, 0, NULL, &ctl->sse_state);
330 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
332 #endif
334 #elif defined(HAVE__CONTROLFP)
336 ctl->state = _controlfp(0, 0);
337 (void)_controlfp(_RC_CHOP, _MCW_RC);
338 #endif
341 void RestoreFPUMode(const FPUCtl *ctl)
343 #ifdef HAVE_FENV_H
344 fesetenv(STATIC_CAST(fenv_t, ctl));
345 #if defined(__GNUC__) && defined(HAVE_SSE)
346 if((CPUCapFlags&CPU_CAP_SSE))
347 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
348 #endif
350 #elif defined(HAVE___CONTROL87_2)
352 int mode;
353 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
354 #ifdef HAVE_SSE
355 if((CPUCapFlags&CPU_CAP_SSE))
356 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
357 #endif
359 #elif defined(HAVE__CONTROLFP)
361 _controlfp(ctl->state, _MCW_RC);
362 #endif
366 static int StringSortCompare(const void *str1, const void *str2)
368 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
371 #ifdef _WIN32
373 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
375 WCHAR *ret = NULL;
376 while(*str)
378 if(*str == ch)
379 ret = str;
380 ++str;
382 return ret;
385 al_string GetProcPath(void)
387 al_string ret = AL_STRING_INIT_STATIC();
388 WCHAR *pathname, *sep;
389 DWORD pathlen;
390 DWORD len;
392 pathlen = 256;
393 pathname = malloc(pathlen * sizeof(pathname[0]));
394 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
396 free(pathname);
397 pathlen <<= 1;
398 pathname = malloc(pathlen * sizeof(pathname[0]));
400 if(len == 0)
402 free(pathname);
403 ERR("Failed to get process name: error %lu\n", GetLastError());
404 return ret;
407 pathname[len] = 0;
408 if((sep = strrchrW(pathname, '\\')))
410 WCHAR *sep2 = strrchrW(pathname, '/');
411 if(sep2) *sep2 = 0;
412 else *sep = 0;
414 else if((sep = strrchrW(pathname, '/')))
415 *sep = 0;
416 alstr_copy_wcstr(&ret, pathname);
417 free(pathname);
419 TRACE("Got: %s\n", alstr_get_cstr(ret));
420 return ret;
424 static WCHAR *FromUTF8(const char *str)
426 WCHAR *out = NULL;
427 int len;
429 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
431 out = calloc(sizeof(WCHAR), len);
432 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
434 return out;
438 void *LoadLib(const char *name)
440 HANDLE hdl = NULL;
441 WCHAR *wname;
443 wname = FromUTF8(name);
444 if(!wname)
445 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
446 else
448 hdl = LoadLibraryW(wname);
449 free(wname);
451 return hdl;
453 void CloseLib(void *handle)
454 { FreeLibrary((HANDLE)handle); }
455 void *GetSymbol(void *handle, const char *name)
457 void *ret;
459 ret = (void*)GetProcAddress((HANDLE)handle, name);
460 if(ret == NULL)
461 ERR("Failed to load %s\n", name);
462 return ret;
465 WCHAR *strdupW(const WCHAR *str)
467 const WCHAR *n;
468 WCHAR *ret;
469 size_t len;
471 n = str;
472 while(*n) n++;
473 len = n - str;
475 ret = calloc(sizeof(WCHAR), len+1);
476 if(ret != NULL)
477 memcpy(ret, str, sizeof(WCHAR)*len);
478 return ret;
481 FILE *al_fopen(const char *fname, const char *mode)
483 WCHAR *wname=NULL, *wmode=NULL;
484 FILE *file = NULL;
486 wname = FromUTF8(fname);
487 wmode = FromUTF8(mode);
488 if(!wname)
489 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
490 else if(!wmode)
491 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
492 else
493 file = _wfopen(wname, wmode);
495 free(wname);
496 free(wmode);
498 return file;
502 void al_print(const char *type, const char *func, const char *fmt, ...)
504 char str[1024];
505 WCHAR *wstr;
506 va_list ap;
508 va_start(ap, fmt);
509 vsnprintf(str, sizeof(str), fmt, ap);
510 va_end(ap);
512 str[sizeof(str)-1] = 0;
513 wstr = FromUTF8(str);
514 if(!wstr)
515 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
516 else
518 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
519 free(wstr);
520 wstr = NULL;
522 fflush(LogFile);
526 static inline int is_slash(int c)
527 { return (c == '\\' || c == '/'); }
529 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
531 al_string pathstr = AL_STRING_INIT_STATIC();
532 WIN32_FIND_DATAW fdata;
533 WCHAR *wpath;
534 HANDLE hdl;
536 alstr_copy_cstr(&pathstr, path);
537 alstr_append_cstr(&pathstr, "\\*");
538 alstr_append_cstr(&pathstr, ext);
540 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
542 wpath = FromUTF8(alstr_get_cstr(pathstr));
544 hdl = FindFirstFileW(wpath, &fdata);
545 if(hdl != INVALID_HANDLE_VALUE)
547 size_t base = VECTOR_SIZE(*results);
548 do {
549 al_string str = AL_STRING_INIT_STATIC();
550 alstr_copy_cstr(&str, path);
551 alstr_append_char(&str, '\\');
552 alstr_append_wcstr(&str, fdata.cFileName);
553 TRACE("Got result %s\n", alstr_get_cstr(str));
554 VECTOR_PUSH_BACK(*results, str);
555 } while(FindNextFileW(hdl, &fdata));
556 FindClose(hdl);
558 if(VECTOR_SIZE(*results) > base)
559 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
560 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
563 free(wpath);
564 alstr_reset(&pathstr);
567 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
569 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
570 static RefCount search_lock;
571 vector_al_string results = VECTOR_INIT_STATIC();
572 size_t i;
574 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
575 althrd_yield();
577 /* If the path is absolute, use it directly. */
578 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
580 al_string path = AL_STRING_INIT_STATIC();
581 alstr_copy_cstr(&path, subdir);
582 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
583 VECTOR_FOR_EACH(char, path, FIX_SLASH);
584 #undef FIX_SLASH
586 DirectorySearch(alstr_get_cstr(path), ext, &results);
588 alstr_reset(&path);
590 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
591 DirectorySearch(subdir, ext, &results);
592 else
594 al_string path = AL_STRING_INIT_STATIC();
595 WCHAR *cwdbuf;
597 /* Search the app-local directory. */
598 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
600 alstr_copy_wcstr(&path, cwdbuf);
601 if(is_slash(VECTOR_BACK(path)))
603 VECTOR_POP_BACK(path);
604 *VECTOR_END(path) = 0;
607 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
608 alstr_copy_cstr(&path, ".");
609 else
611 alstr_copy_wcstr(&path, cwdbuf);
612 if(is_slash(VECTOR_BACK(path)))
614 VECTOR_POP_BACK(path);
615 *VECTOR_END(path) = 0;
617 free(cwdbuf);
619 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
620 VECTOR_FOR_EACH(char, path, FIX_SLASH);
621 #undef FIX_SLASH
622 DirectorySearch(alstr_get_cstr(path), ext, &results);
624 /* Search the local and global data dirs. */
625 for(i = 0;i < COUNTOF(ids);i++)
627 WCHAR buffer[PATH_MAX];
628 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
630 alstr_copy_wcstr(&path, buffer);
631 if(!is_slash(VECTOR_BACK(path)))
632 alstr_append_char(&path, '\\');
633 alstr_append_cstr(&path, subdir);
634 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
635 VECTOR_FOR_EACH(char, path, FIX_SLASH);
636 #undef FIX_SLASH
638 DirectorySearch(alstr_get_cstr(path), ext, &results);
642 alstr_reset(&path);
645 ATOMIC_STORE_SEQ(&search_lock, 0);
647 return results;
651 struct FileMapping MapFileToMem(const char *fname)
653 struct FileMapping ret = { NULL, NULL, NULL, 0 };
654 MEMORY_BASIC_INFORMATION meminfo;
655 HANDLE file, fmap;
656 WCHAR *wname;
657 void *ptr;
659 wname = FromUTF8(fname);
661 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
662 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
663 if(file == INVALID_HANDLE_VALUE)
665 ERR("Failed to open %s: %lu\n", fname, GetLastError());
666 free(wname);
667 return ret;
669 free(wname);
670 wname = NULL;
672 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
673 if(!fmap)
675 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
676 CloseHandle(file);
677 return ret;
680 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
681 if(!ptr)
683 ERR("Failed to map %s: %lu\n", fname, GetLastError());
684 CloseHandle(fmap);
685 CloseHandle(file);
686 return ret;
689 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
691 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
692 UnmapViewOfFile(ptr);
693 CloseHandle(fmap);
694 CloseHandle(file);
695 return ret;
698 ret.file = file;
699 ret.fmap = fmap;
700 ret.ptr = ptr;
701 ret.len = meminfo.RegionSize;
702 return ret;
705 void UnmapFileMem(const struct FileMapping *mapping)
707 UnmapViewOfFile(mapping->ptr);
708 CloseHandle(mapping->fmap);
709 CloseHandle(mapping->file);
712 #else
714 al_string GetProcPath(void)
716 al_string ret = AL_STRING_INIT_STATIC();
717 char *pathname, *sep;
718 size_t pathlen;
720 #ifdef __FreeBSD__
721 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
722 mib[3] = getpid();
723 if (sysctl(mib, 4, NULL, &pathlen, NULL, 0) == -1) {
724 WARN("Failed to sysctl kern.proc.pathname.%d: %s\n", mib[3], strerror(errno));
725 return ret;
728 pathname = malloc(pathlen + 1);
729 sysctl(mib, 4, (void*)pathname, &pathlen, NULL, 0);
730 pathname[pathlen] = 0;
731 #else
732 const char *fname;
733 ssize_t len;
735 pathlen = 256;
736 pathname = malloc(pathlen);
738 fname = "/proc/self/exe";
739 len = readlink(fname, pathname, pathlen);
740 if(len == -1 && errno == ENOENT)
742 fname = "/proc/self/file";
743 len = readlink(fname, pathname, pathlen);
746 while(len > 0 && (size_t)len == pathlen)
748 free(pathname);
749 pathlen <<= 1;
750 pathname = malloc(pathlen);
751 len = readlink(fname, pathname, pathlen);
753 if(len <= 0)
755 free(pathname);
756 WARN("Failed to readlink %s: %s\n", fname, strerror(errno));
757 return ret;
760 pathname[len] = 0;
761 #endif
763 sep = strrchr(pathname, '/');
764 if(sep)
765 alstr_copy_range(&ret, pathname, sep);
766 else
767 alstr_copy_cstr(&ret, pathname);
768 free(pathname);
770 TRACE("Got: %s\n", alstr_get_cstr(ret));
771 return ret;
775 #ifdef HAVE_DLFCN_H
777 void *LoadLib(const char *name)
779 const char *err;
780 void *handle;
782 dlerror();
783 handle = dlopen(name, RTLD_NOW);
784 if((err=dlerror()) != NULL)
785 handle = NULL;
786 return handle;
788 void CloseLib(void *handle)
789 { dlclose(handle); }
790 void *GetSymbol(void *handle, const char *name)
792 const char *err;
793 void *sym;
795 dlerror();
796 sym = dlsym(handle, name);
797 if((err=dlerror()) != NULL)
799 WARN("Failed to load %s: %s\n", name, err);
800 sym = NULL;
802 return sym;
805 #endif /* HAVE_DLFCN_H */
807 void al_print(const char *type, const char *func, const char *fmt, ...)
809 va_list ap;
811 va_start(ap, fmt);
812 fprintf(LogFile, "AL lib: %s %s: ", type, func);
813 vfprintf(LogFile, fmt, ap);
814 va_end(ap);
816 fflush(LogFile);
820 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
822 size_t extlen = strlen(ext);
823 DIR *dir;
825 TRACE("Searching %s for *%s\n", path, ext);
826 dir = opendir(path);
827 if(dir != NULL)
829 size_t base = VECTOR_SIZE(*results);
830 struct dirent *dirent;
831 while((dirent=readdir(dir)) != NULL)
833 al_string str;
834 size_t len;
835 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
836 continue;
838 len = strlen(dirent->d_name);
839 if(!(len > extlen))
840 continue;
841 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
842 continue;
844 AL_STRING_INIT(str);
845 alstr_copy_cstr(&str, path);
846 if(VECTOR_BACK(str) != '/')
847 alstr_append_char(&str, '/');
848 alstr_append_cstr(&str, dirent->d_name);
849 TRACE("Got result %s\n", alstr_get_cstr(str));
850 VECTOR_PUSH_BACK(*results, str);
852 closedir(dir);
854 if(VECTOR_SIZE(*results) > base)
855 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
856 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
860 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
862 static RefCount search_lock;
863 vector_al_string results = VECTOR_INIT_STATIC();
865 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
866 althrd_yield();
868 if(subdir[0] == '/')
869 DirectorySearch(subdir, ext, &results);
870 else
872 al_string path = AL_STRING_INIT_STATIC();
873 const char *str, *next;
874 char cwdbuf[PATH_MAX];
876 /* Search the app-local directory. */
877 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
878 DirectorySearch(str, ext, &results);
879 else if(getcwd(cwdbuf, sizeof(cwdbuf)))
880 DirectorySearch(cwdbuf, ext, &results);
881 else
882 DirectorySearch(".", ext, &results);
884 // Search local data dir
885 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
887 alstr_copy_cstr(&path, str);
888 if(VECTOR_BACK(path) != '/')
889 alstr_append_char(&path, '/');
890 alstr_append_cstr(&path, subdir);
891 DirectorySearch(alstr_get_cstr(path), ext, &results);
893 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
895 alstr_copy_cstr(&path, str);
896 if(VECTOR_BACK(path) == '/')
898 VECTOR_POP_BACK(path);
899 *VECTOR_END(path) = 0;
901 alstr_append_cstr(&path, "/.local/share/");
902 alstr_append_cstr(&path, subdir);
903 DirectorySearch(alstr_get_cstr(path), ext, &results);
906 // Search global data dirs
907 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
908 str = "/usr/local/share/:/usr/share/";
910 next = str;
911 while((str=next) != NULL && str[0] != '\0')
913 next = strchr(str, ':');
914 if(!next)
915 alstr_copy_cstr(&path, str);
916 else
918 alstr_copy_range(&path, str, next);
919 ++next;
921 if(!alstr_empty(path))
923 if(VECTOR_BACK(path) != '/')
924 alstr_append_char(&path, '/');
925 alstr_append_cstr(&path, subdir);
927 DirectorySearch(alstr_get_cstr(path), ext, &results);
931 alstr_reset(&path);
934 ATOMIC_STORE_SEQ(&search_lock, 0);
936 return results;
940 struct FileMapping MapFileToMem(const char *fname)
942 struct FileMapping ret = { -1, NULL, 0 };
943 struct stat sbuf;
944 void *ptr;
945 int fd;
947 fd = open(fname, O_RDONLY, 0);
948 if(fd == -1)
950 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
951 return ret;
953 if(fstat(fd, &sbuf) == -1)
955 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
956 close(fd);
957 return ret;
960 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
961 if(ptr == MAP_FAILED)
963 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
964 close(fd);
965 return ret;
968 ret.fd = fd;
969 ret.ptr = ptr;
970 ret.len = sbuf.st_size;
971 return ret;
974 void UnmapFileMem(const struct FileMapping *mapping)
976 munmap(mapping->ptr, mapping->len);
977 close(mapping->fd);
980 #endif
983 void SetRTPriority(void)
985 ALboolean failed = AL_FALSE;
987 #ifdef _WIN32
988 if(RTPrioLevel > 0)
989 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
990 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
991 if(RTPrioLevel > 0)
993 struct sched_param param;
994 /* Use the minimum real-time priority possible for now (on Linux this
995 * should be 1 for SCHED_RR) */
996 param.sched_priority = sched_get_priority_min(SCHED_RR);
997 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
999 #else
1000 /* Real-time priority not available */
1001 failed = (RTPrioLevel>0);
1002 #endif
1003 if(failed)
1004 ERR("Failed to set priority level for thread\n");
1008 extern inline void alstr_reset(al_string *str);
1009 extern inline size_t alstr_length(const_al_string str);
1010 extern inline ALboolean alstr_empty(const_al_string str);
1011 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1013 void alstr_clear(al_string *str)
1015 if(!alstr_empty(*str))
1017 /* Reserve one more character than the total size of the string. This
1018 * is to ensure we have space to add a null terminator in the string
1019 * data so it can be used as a C-style string.
1021 VECTOR_RESIZE(*str, 0, 1);
1022 VECTOR_ELEM(*str, 0) = 0;
1026 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1027 const al_string_char_type *str2, size_t str2len)
1029 size_t complen = (str1len < str2len) ? str1len : str2len;
1030 int ret = memcmp(str1, str2, complen);
1031 if(ret == 0)
1033 if(str1len > str2len) return 1;
1034 if(str1len < str2len) return -1;
1036 return ret;
1038 int alstr_cmp(const_al_string str1, const_al_string str2)
1040 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1041 &VECTOR_FRONT(str2), alstr_length(str2));
1043 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1045 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1046 str2, strlen(str2));
1049 void alstr_copy(al_string *str, const_al_string from)
1051 size_t len = alstr_length(from);
1052 size_t i;
1054 VECTOR_RESIZE(*str, len, len+1);
1055 for(i = 0;i < len;i++)
1056 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1057 VECTOR_ELEM(*str, i) = 0;
1060 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1062 size_t len = strlen(from);
1063 size_t i;
1065 VECTOR_RESIZE(*str, len, len+1);
1066 for(i = 0;i < len;i++)
1067 VECTOR_ELEM(*str, i) = from[i];
1068 VECTOR_ELEM(*str, i) = 0;
1071 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1073 size_t len = to - from;
1074 size_t i;
1076 VECTOR_RESIZE(*str, len, len+1);
1077 for(i = 0;i < len;i++)
1078 VECTOR_ELEM(*str, i) = from[i];
1079 VECTOR_ELEM(*str, i) = 0;
1082 void alstr_append_char(al_string *str, const al_string_char_type c)
1084 size_t len = alstr_length(*str);
1085 VECTOR_RESIZE(*str, len, len+2);
1086 VECTOR_PUSH_BACK(*str, c);
1087 VECTOR_ELEM(*str, len+1) = 0;
1090 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1092 size_t len = strlen(from);
1093 if(len != 0)
1095 size_t base = alstr_length(*str);
1096 size_t i;
1098 VECTOR_RESIZE(*str, base+len, base+len+1);
1099 for(i = 0;i < len;i++)
1100 VECTOR_ELEM(*str, base+i) = from[i];
1101 VECTOR_ELEM(*str, base+i) = 0;
1105 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1107 size_t len = to - from;
1108 if(len != 0)
1110 size_t base = alstr_length(*str);
1111 size_t i;
1113 VECTOR_RESIZE(*str, base+len, base+len+1);
1114 for(i = 0;i < len;i++)
1115 VECTOR_ELEM(*str, base+i) = from[i];
1116 VECTOR_ELEM(*str, base+i) = 0;
1120 #ifdef _WIN32
1121 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1123 int len;
1124 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1126 VECTOR_RESIZE(*str, len-1, len);
1127 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1128 VECTOR_ELEM(*str, len-1) = 0;
1132 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1134 int len;
1135 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1137 size_t base = alstr_length(*str);
1138 VECTOR_RESIZE(*str, base+len-1, base+len);
1139 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1140 VECTOR_ELEM(*str, base+len-1) = 0;
1144 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1146 int len;
1147 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1149 size_t base = alstr_length(*str);
1150 VECTOR_RESIZE(*str, base+len, base+len+1);
1151 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1152 VECTOR_ELEM(*str, base+len) = 0;
1155 #endif