Don't force a fade-in when resuming a paused source
[openal-soft.git] / Alc / helpers.c
blobf1cd1f66295d18e111cbe102d0e2232743922136
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 ALint fastf2i(ALfloat f);
121 extern inline ALuint fastf2u(ALfloat f);
124 ALuint CPUCapFlags = 0;
127 void FillCPUCaps(ALuint capfilter)
129 ALuint caps = 0;
131 /* FIXME: We really should get this for all available CPUs in case different
132 * CPUs have different caps (is that possible on one machine?). */
133 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
134 defined(_M_IX86) || defined(_M_X64))
135 union {
136 unsigned int regs[4];
137 char str[sizeof(unsigned int[4])];
138 } cpuinf[3];
140 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
141 ERR("Failed to get CPUID\n");
142 else
144 unsigned int maxfunc = cpuinf[0].regs[0];
145 unsigned int maxextfunc = 0;
147 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
148 maxextfunc = cpuinf[0].regs[0];
149 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
151 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
152 if(maxextfunc >= 0x80000004 &&
153 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
154 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
155 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
156 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
158 if(maxfunc >= 1 &&
159 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
161 if((cpuinf[0].regs[3]&(1<<25)))
163 caps |= CPU_CAP_SSE;
164 if((cpuinf[0].regs[3]&(1<<26)))
166 caps |= CPU_CAP_SSE2;
167 if((cpuinf[0].regs[2]&(1<<0)))
169 caps |= CPU_CAP_SSE3;
170 if((cpuinf[0].regs[2]&(1<<19)))
171 caps |= CPU_CAP_SSE4_1;
177 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
178 defined(_M_IX86) || defined(_M_X64))
179 union {
180 int regs[4];
181 char str[sizeof(int[4])];
182 } cpuinf[3];
184 (__cpuid)(cpuinf[0].regs, 0);
185 if(cpuinf[0].regs[0] == 0)
186 ERR("Failed to get CPUID\n");
187 else
189 unsigned int maxfunc = cpuinf[0].regs[0];
190 unsigned int maxextfunc;
192 (__cpuid)(cpuinf[0].regs, 0x80000000);
193 maxextfunc = cpuinf[0].regs[0];
195 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
197 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
198 if(maxextfunc >= 0x80000004)
200 (__cpuid)(cpuinf[0].regs, 0x80000002);
201 (__cpuid)(cpuinf[1].regs, 0x80000003);
202 (__cpuid)(cpuinf[2].regs, 0x80000004);
203 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
206 if(maxfunc >= 1)
208 (__cpuid)(cpuinf[0].regs, 1);
209 if((cpuinf[0].regs[3]&(1<<25)))
211 caps |= CPU_CAP_SSE;
212 if((cpuinf[0].regs[3]&(1<<26)))
214 caps |= CPU_CAP_SSE2;
215 if((cpuinf[0].regs[2]&(1<<0)))
217 caps |= CPU_CAP_SSE3;
218 if((cpuinf[0].regs[2]&(1<<19)))
219 caps |= CPU_CAP_SSE4_1;
225 #else
226 /* Assume support for whatever's supported if we can't check for it */
227 #if defined(HAVE_SSE4_1)
228 #warning "Assuming SSE 4.1 run-time support!"
229 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
230 #elif defined(HAVE_SSE3)
231 #warning "Assuming SSE 3 run-time support!"
232 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
233 #elif defined(HAVE_SSE2)
234 #warning "Assuming SSE 2 run-time support!"
235 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
236 #elif defined(HAVE_SSE)
237 #warning "Assuming SSE run-time support!"
238 caps |= CPU_CAP_SSE;
239 #endif
240 #endif
241 #ifdef HAVE_NEON
242 FILE *file = fopen("/proc/cpuinfo", "rt");
243 if(!file)
244 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
245 else
247 char buf[256];
248 while(fgets(buf, sizeof(buf), file) != NULL)
250 size_t len;
251 char *str;
253 if(strncmp(buf, "Features\t:", 10) != 0)
254 continue;
256 len = strlen(buf);
257 while(len > 0 && isspace(buf[len-1]))
258 buf[--len] = 0;
260 TRACE("Got features string:%s\n", buf+10);
262 str = buf;
263 while((str=strstr(str, "neon")) != NULL)
265 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
267 caps |= CPU_CAP_NEON;
268 break;
270 str++;
272 break;
275 fclose(file);
276 file = NULL;
278 #endif
280 TRACE("Extensions:%s%s%s%s%s%s\n",
281 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
282 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
283 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
284 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
285 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
286 ((!capfilter) ? " -none-" : "")
288 CPUCapFlags = caps & capfilter;
292 void SetMixerFPUMode(FPUCtl *ctl)
294 #ifdef HAVE_FENV_H
295 fegetenv(STATIC_CAST(fenv_t, ctl));
296 #if defined(__GNUC__) && defined(HAVE_SSE)
297 /* FIXME: Some fegetenv implementations can get the SSE environment too?
298 * How to tell when it does? */
299 if((CPUCapFlags&CPU_CAP_SSE))
300 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
301 #endif
303 #ifdef FE_TOWARDZERO
304 fesetround(FE_TOWARDZERO);
305 #endif
306 #if defined(__GNUC__) && defined(HAVE_SSE)
307 if((CPUCapFlags&CPU_CAP_SSE))
309 int sseState = ctl->sse_state;
310 sseState |= 0x6000; /* set round-to-zero */
311 sseState |= 0x8000; /* set flush-to-zero */
312 if((CPUCapFlags&CPU_CAP_SSE2))
313 sseState |= 0x0040; /* set denormals-are-zero */
314 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
316 #endif
318 #elif defined(HAVE___CONTROL87_2)
320 int mode;
321 __control87_2(0, 0, &ctl->state, NULL);
322 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
323 #ifdef HAVE_SSE
324 if((CPUCapFlags&CPU_CAP_SSE))
326 __control87_2(0, 0, NULL, &ctl->sse_state);
327 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
329 #endif
331 #elif defined(HAVE__CONTROLFP)
333 ctl->state = _controlfp(0, 0);
334 (void)_controlfp(_RC_CHOP, _MCW_RC);
335 #endif
338 void RestoreFPUMode(const FPUCtl *ctl)
340 #ifdef HAVE_FENV_H
341 fesetenv(STATIC_CAST(fenv_t, ctl));
342 #if defined(__GNUC__) && defined(HAVE_SSE)
343 if((CPUCapFlags&CPU_CAP_SSE))
344 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
345 #endif
347 #elif defined(HAVE___CONTROL87_2)
349 int mode;
350 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
351 #ifdef HAVE_SSE
352 if((CPUCapFlags&CPU_CAP_SSE))
353 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
354 #endif
356 #elif defined(HAVE__CONTROLFP)
358 _controlfp(ctl->state, _MCW_RC);
359 #endif
363 static int StringSortCompare(const void *str1, const void *str2)
365 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
368 #ifdef _WIN32
370 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
372 WCHAR *ret = NULL;
373 while(*str)
375 if(*str == ch)
376 ret = str;
377 ++str;
379 return ret;
382 al_string GetProcPath(void)
384 al_string ret = AL_STRING_INIT_STATIC();
385 WCHAR *pathname, *sep;
386 DWORD pathlen;
387 DWORD len;
389 pathlen = 256;
390 pathname = malloc(pathlen * sizeof(pathname[0]));
391 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
393 free(pathname);
394 pathlen <<= 1;
395 pathname = malloc(pathlen * sizeof(pathname[0]));
397 if(len == 0)
399 free(pathname);
400 ERR("Failed to get process name: error %lu\n", GetLastError());
401 return ret;
404 pathname[len] = 0;
405 if((sep = strrchrW(pathname, '\\')))
407 WCHAR *sep2 = strrchrW(pathname, '/');
408 if(sep2) *sep2 = 0;
409 else *sep = 0;
411 else if((sep = strrchrW(pathname, '/')))
412 *sep = 0;
413 alstr_copy_wcstr(&ret, pathname);
414 free(pathname);
416 TRACE("Got: %s\n", alstr_get_cstr(ret));
417 return ret;
421 static WCHAR *FromUTF8(const char *str)
423 WCHAR *out = NULL;
424 int len;
426 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
428 out = calloc(sizeof(WCHAR), len);
429 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
431 return out;
435 void *LoadLib(const char *name)
437 HANDLE hdl = NULL;
438 WCHAR *wname;
440 wname = FromUTF8(name);
441 if(!wname)
442 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
443 else
445 hdl = LoadLibraryW(wname);
446 free(wname);
448 return hdl;
450 void CloseLib(void *handle)
451 { FreeLibrary((HANDLE)handle); }
452 void *GetSymbol(void *handle, const char *name)
454 void *ret;
456 ret = (void*)GetProcAddress((HANDLE)handle, name);
457 if(ret == NULL)
458 ERR("Failed to load %s\n", name);
459 return ret;
462 WCHAR *strdupW(const WCHAR *str)
464 const WCHAR *n;
465 WCHAR *ret;
466 size_t len;
468 n = str;
469 while(*n) n++;
470 len = n - str;
472 ret = calloc(sizeof(WCHAR), len+1);
473 if(ret != NULL)
474 memcpy(ret, str, sizeof(WCHAR)*len);
475 return ret;
478 FILE *al_fopen(const char *fname, const char *mode)
480 WCHAR *wname=NULL, *wmode=NULL;
481 FILE *file = NULL;
483 wname = FromUTF8(fname);
484 wmode = FromUTF8(mode);
485 if(!wname)
486 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
487 else if(!wmode)
488 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
489 else
490 file = _wfopen(wname, wmode);
492 free(wname);
493 free(wmode);
495 return file;
499 void al_print(const char *type, const char *func, const char *fmt, ...)
501 char str[1024];
502 WCHAR *wstr;
503 va_list ap;
505 va_start(ap, fmt);
506 vsnprintf(str, sizeof(str), fmt, ap);
507 va_end(ap);
509 str[sizeof(str)-1] = 0;
510 wstr = FromUTF8(str);
511 if(!wstr)
512 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
513 else
515 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
516 free(wstr);
517 wstr = NULL;
519 fflush(LogFile);
523 static inline int is_slash(int c)
524 { return (c == '\\' || c == '/'); }
526 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
528 al_string pathstr = AL_STRING_INIT_STATIC();
529 WIN32_FIND_DATAW fdata;
530 WCHAR *wpath;
531 HANDLE hdl;
533 alstr_copy_cstr(&pathstr, path);
534 alstr_append_cstr(&pathstr, "\\*");
535 alstr_append_cstr(&pathstr, ext);
537 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
539 wpath = FromUTF8(alstr_get_cstr(pathstr));
541 hdl = FindFirstFileW(wpath, &fdata);
542 if(hdl != INVALID_HANDLE_VALUE)
544 size_t base = VECTOR_SIZE(*results);
545 do {
546 al_string str = AL_STRING_INIT_STATIC();
547 alstr_copy_cstr(&str, path);
548 alstr_append_char(&str, '\\');
549 alstr_append_wcstr(&str, fdata.cFileName);
550 TRACE("Got result %s\n", alstr_get_cstr(str));
551 VECTOR_PUSH_BACK(*results, str);
552 } while(FindNextFileW(hdl, &fdata));
553 FindClose(hdl);
555 if(VECTOR_SIZE(*results) > base)
556 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
557 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
560 free(wpath);
561 alstr_reset(&pathstr);
564 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
566 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
567 static RefCount search_lock;
568 vector_al_string results = VECTOR_INIT_STATIC();
569 size_t i;
571 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
572 althrd_yield();
574 /* If the path is absolute, use it directly. */
575 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
577 al_string path = AL_STRING_INIT_STATIC();
578 alstr_copy_cstr(&path, subdir);
579 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
580 VECTOR_FOR_EACH(char, path, FIX_SLASH);
581 #undef FIX_SLASH
583 DirectorySearch(alstr_get_cstr(path), ext, &results);
585 alstr_reset(&path);
587 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
588 DirectorySearch(subdir, ext, &results);
589 else
591 al_string path = AL_STRING_INIT_STATIC();
592 WCHAR *cwdbuf;
594 /* Search the app-local directory. */
595 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
597 alstr_copy_wcstr(&path, cwdbuf);
598 if(is_slash(VECTOR_BACK(path)))
600 VECTOR_POP_BACK(path);
601 *VECTOR_END(path) = 0;
604 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
605 alstr_copy_cstr(&path, ".");
606 else
608 alstr_copy_wcstr(&path, cwdbuf);
609 if(is_slash(VECTOR_BACK(path)))
611 VECTOR_POP_BACK(path);
612 *VECTOR_END(path) = 0;
614 free(cwdbuf);
616 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
617 VECTOR_FOR_EACH(char, path, FIX_SLASH);
618 #undef FIX_SLASH
619 DirectorySearch(alstr_get_cstr(path), ext, &results);
621 /* Search the local and global data dirs. */
622 for(i = 0;i < COUNTOF(ids);i++)
624 WCHAR buffer[PATH_MAX];
625 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
627 alstr_copy_wcstr(&path, buffer);
628 if(!is_slash(VECTOR_BACK(path)))
629 alstr_append_char(&path, '\\');
630 alstr_append_cstr(&path, subdir);
631 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
632 VECTOR_FOR_EACH(char, path, FIX_SLASH);
633 #undef FIX_SLASH
635 DirectorySearch(alstr_get_cstr(path), ext, &results);
639 alstr_reset(&path);
642 ATOMIC_STORE_SEQ(&search_lock, 0);
644 return results;
648 struct FileMapping MapFileToMem(const char *fname)
650 struct FileMapping ret = { NULL, NULL, NULL, 0 };
651 MEMORY_BASIC_INFORMATION meminfo;
652 HANDLE file, fmap;
653 WCHAR *wname;
654 void *ptr;
656 wname = FromUTF8(fname);
658 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
659 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
660 if(file == INVALID_HANDLE_VALUE)
662 ERR("Failed to open %s: %lu\n", fname, GetLastError());
663 free(wname);
664 return ret;
666 free(wname);
667 wname = NULL;
669 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
670 if(!fmap)
672 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
673 CloseHandle(file);
674 return ret;
677 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
678 if(!ptr)
680 ERR("Failed to map %s: %lu\n", fname, GetLastError());
681 CloseHandle(fmap);
682 CloseHandle(file);
683 return ret;
686 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
688 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
689 UnmapViewOfFile(ptr);
690 CloseHandle(fmap);
691 CloseHandle(file);
692 return ret;
695 ret.file = file;
696 ret.fmap = fmap;
697 ret.ptr = ptr;
698 ret.len = meminfo.RegionSize;
699 return ret;
702 void UnmapFileMem(const struct FileMapping *mapping)
704 UnmapViewOfFile(mapping->ptr);
705 CloseHandle(mapping->fmap);
706 CloseHandle(mapping->file);
709 #else
711 al_string GetProcPath(void)
713 al_string ret = AL_STRING_INIT_STATIC();
714 char *pathname, *sep;
715 size_t pathlen;
717 #ifdef __FreeBSD__
718 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
719 mib[3] = getpid();
720 if (sysctl(mib, 4, NULL, &pathlen, NULL, 0) == -1) {
721 WARN("Failed to sysctl kern.proc.pathname.%d: %s\n", mib[3], strerror(errno));
722 return ret;
725 pathname = malloc(pathlen + 1);
726 sysctl(mib, 4, (void*)pathname, &pathlen, NULL, 0);
727 pathname[pathlen] = 0;
728 #else
729 const char *fname;
730 ssize_t len;
732 pathlen = 256;
733 pathname = malloc(pathlen);
735 fname = "/proc/self/exe";
736 len = readlink(fname, pathname, pathlen);
737 if(len == -1 && errno == ENOENT)
739 fname = "/proc/self/file";
740 len = readlink(fname, pathname, pathlen);
743 while(len > 0 && (size_t)len == pathlen)
745 free(pathname);
746 pathlen <<= 1;
747 pathname = malloc(pathlen);
748 len = readlink(fname, pathname, pathlen);
750 if(len <= 0)
752 free(pathname);
753 WARN("Failed to readlink %s: %s\n", fname, strerror(errno));
754 return ret;
757 pathname[len] = 0;
758 #endif
760 sep = strrchr(pathname, '/');
761 if(sep)
762 alstr_copy_range(&ret, pathname, sep);
763 else
764 alstr_copy_cstr(&ret, pathname);
765 free(pathname);
767 TRACE("Got: %s\n", alstr_get_cstr(ret));
768 return ret;
772 #ifdef HAVE_DLFCN_H
774 void *LoadLib(const char *name)
776 const char *err;
777 void *handle;
779 dlerror();
780 handle = dlopen(name, RTLD_NOW);
781 if((err=dlerror()) != NULL)
782 handle = NULL;
783 return handle;
785 void CloseLib(void *handle)
786 { dlclose(handle); }
787 void *GetSymbol(void *handle, const char *name)
789 const char *err;
790 void *sym;
792 dlerror();
793 sym = dlsym(handle, name);
794 if((err=dlerror()) != NULL)
796 WARN("Failed to load %s: %s\n", name, err);
797 sym = NULL;
799 return sym;
802 #endif /* HAVE_DLFCN_H */
804 void al_print(const char *type, const char *func, const char *fmt, ...)
806 va_list ap;
808 va_start(ap, fmt);
809 fprintf(LogFile, "AL lib: %s %s: ", type, func);
810 vfprintf(LogFile, fmt, ap);
811 va_end(ap);
813 fflush(LogFile);
817 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
819 size_t extlen = strlen(ext);
820 DIR *dir;
822 TRACE("Searching %s for *%s\n", path, ext);
823 dir = opendir(path);
824 if(dir != NULL)
826 size_t base = VECTOR_SIZE(*results);
827 struct dirent *dirent;
828 while((dirent=readdir(dir)) != NULL)
830 al_string str;
831 size_t len;
832 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
833 continue;
835 len = strlen(dirent->d_name);
836 if(!(len > extlen))
837 continue;
838 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
839 continue;
841 AL_STRING_INIT(str);
842 alstr_copy_cstr(&str, path);
843 if(VECTOR_BACK(str) != '/')
844 alstr_append_char(&str, '/');
845 alstr_append_cstr(&str, dirent->d_name);
846 TRACE("Got result %s\n", alstr_get_cstr(str));
847 VECTOR_PUSH_BACK(*results, str);
849 closedir(dir);
851 if(VECTOR_SIZE(*results) > base)
852 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
853 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
857 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
859 static RefCount search_lock;
860 vector_al_string results = VECTOR_INIT_STATIC();
862 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
863 althrd_yield();
865 if(subdir[0] == '/')
866 DirectorySearch(subdir, ext, &results);
867 else
869 al_string path = AL_STRING_INIT_STATIC();
870 const char *str, *next;
871 char cwdbuf[PATH_MAX];
873 /* Search the app-local directory. */
874 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
875 DirectorySearch(str, ext, &results);
876 else if(getcwd(cwdbuf, sizeof(cwdbuf)))
877 DirectorySearch(cwdbuf, ext, &results);
878 else
879 DirectorySearch(".", ext, &results);
881 // Search local data dir
882 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
884 alstr_copy_cstr(&path, str);
885 if(VECTOR_BACK(path) != '/')
886 alstr_append_char(&path, '/');
887 alstr_append_cstr(&path, subdir);
888 DirectorySearch(alstr_get_cstr(path), ext, &results);
890 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
892 alstr_copy_cstr(&path, str);
893 if(VECTOR_BACK(path) == '/')
895 VECTOR_POP_BACK(path);
896 *VECTOR_END(path) = 0;
898 alstr_append_cstr(&path, "/.local/share/");
899 alstr_append_cstr(&path, subdir);
900 DirectorySearch(alstr_get_cstr(path), ext, &results);
903 // Search global data dirs
904 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
905 str = "/usr/local/share/:/usr/share/";
907 next = str;
908 while((str=next) != NULL && str[0] != '\0')
910 next = strchr(str, ':');
911 if(!next)
912 alstr_copy_cstr(&path, str);
913 else
915 alstr_copy_range(&path, str, next);
916 ++next;
918 if(!alstr_empty(path))
920 if(VECTOR_BACK(path) != '/')
921 alstr_append_char(&path, '/');
922 alstr_append_cstr(&path, subdir);
924 DirectorySearch(alstr_get_cstr(path), ext, &results);
928 alstr_reset(&path);
931 ATOMIC_STORE_SEQ(&search_lock, 0);
933 return results;
937 struct FileMapping MapFileToMem(const char *fname)
939 struct FileMapping ret = { -1, NULL, 0 };
940 struct stat sbuf;
941 void *ptr;
942 int fd;
944 fd = open(fname, O_RDONLY, 0);
945 if(fd == -1)
947 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
948 return ret;
950 if(fstat(fd, &sbuf) == -1)
952 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
953 close(fd);
954 return ret;
957 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
958 if(ptr == MAP_FAILED)
960 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
961 close(fd);
962 return ret;
965 ret.fd = fd;
966 ret.ptr = ptr;
967 ret.len = sbuf.st_size;
968 return ret;
971 void UnmapFileMem(const struct FileMapping *mapping)
973 munmap(mapping->ptr, mapping->len);
974 close(mapping->fd);
977 #endif
980 void SetRTPriority(void)
982 ALboolean failed = AL_FALSE;
984 #ifdef _WIN32
985 if(RTPrioLevel > 0)
986 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
987 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
988 if(RTPrioLevel > 0)
990 struct sched_param param;
991 /* Use the minimum real-time priority possible for now (on Linux this
992 * should be 1 for SCHED_RR) */
993 param.sched_priority = sched_get_priority_min(SCHED_RR);
994 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
996 #else
997 /* Real-time priority not available */
998 failed = (RTPrioLevel>0);
999 #endif
1000 if(failed)
1001 ERR("Failed to set priority level for thread\n");
1005 extern inline void alstr_reset(al_string *str);
1006 extern inline size_t alstr_length(const_al_string str);
1007 extern inline ALboolean alstr_empty(const_al_string str);
1008 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1010 void alstr_clear(al_string *str)
1012 if(!alstr_empty(*str))
1014 /* Reserve one more character than the total size of the string. This
1015 * is to ensure we have space to add a null terminator in the string
1016 * data so it can be used as a C-style string.
1018 VECTOR_RESIZE(*str, 0, 1);
1019 VECTOR_ELEM(*str, 0) = 0;
1023 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1024 const al_string_char_type *str2, size_t str2len)
1026 size_t complen = (str1len < str2len) ? str1len : str2len;
1027 int ret = memcmp(str1, str2, complen);
1028 if(ret == 0)
1030 if(str1len > str2len) return 1;
1031 if(str1len < str2len) return -1;
1033 return ret;
1035 int alstr_cmp(const_al_string str1, const_al_string str2)
1037 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1038 &VECTOR_FRONT(str2), alstr_length(str2));
1040 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1042 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1043 str2, strlen(str2));
1046 void alstr_copy(al_string *str, const_al_string from)
1048 size_t len = alstr_length(from);
1049 size_t i;
1051 VECTOR_RESIZE(*str, len, len+1);
1052 for(i = 0;i < len;i++)
1053 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1054 VECTOR_ELEM(*str, i) = 0;
1057 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1059 size_t len = strlen(from);
1060 size_t i;
1062 VECTOR_RESIZE(*str, len, len+1);
1063 for(i = 0;i < len;i++)
1064 VECTOR_ELEM(*str, i) = from[i];
1065 VECTOR_ELEM(*str, i) = 0;
1068 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1070 size_t len = to - from;
1071 size_t i;
1073 VECTOR_RESIZE(*str, len, len+1);
1074 for(i = 0;i < len;i++)
1075 VECTOR_ELEM(*str, i) = from[i];
1076 VECTOR_ELEM(*str, i) = 0;
1079 void alstr_append_char(al_string *str, const al_string_char_type c)
1081 size_t len = alstr_length(*str);
1082 VECTOR_RESIZE(*str, len, len+2);
1083 VECTOR_PUSH_BACK(*str, c);
1084 VECTOR_ELEM(*str, len+1) = 0;
1087 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1089 size_t len = strlen(from);
1090 if(len != 0)
1092 size_t base = alstr_length(*str);
1093 size_t i;
1095 VECTOR_RESIZE(*str, base+len, base+len+1);
1096 for(i = 0;i < len;i++)
1097 VECTOR_ELEM(*str, base+i) = from[i];
1098 VECTOR_ELEM(*str, base+i) = 0;
1102 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1104 size_t len = to - from;
1105 if(len != 0)
1107 size_t base = alstr_length(*str);
1108 size_t i;
1110 VECTOR_RESIZE(*str, base+len, base+len+1);
1111 for(i = 0;i < len;i++)
1112 VECTOR_ELEM(*str, base+i) = from[i];
1113 VECTOR_ELEM(*str, base+i) = 0;
1117 #ifdef _WIN32
1118 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1120 int len;
1121 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1123 VECTOR_RESIZE(*str, len-1, len);
1124 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1125 VECTOR_ELEM(*str, len-1) = 0;
1129 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1131 int len;
1132 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1134 size_t base = alstr_length(*str);
1135 VECTOR_RESIZE(*str, base+len-1, base+len);
1136 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1137 VECTOR_ELEM(*str, base+len-1) = 0;
1141 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1143 int len;
1144 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1146 size_t base = alstr_length(*str);
1147 VECTOR_RESIZE(*str, base+len, base+len+1);
1148 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1149 VECTOR_ELEM(*str, base+len) = 0;
1152 #endif