Separate the delay line feeding from reading
[openal-soft.git] / Alc / helpers.c
blobd2cb6253603660a13f7dcd16f639731c44d398be
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 extern inline int float2int(float f);
128 extern inline float fast_roundf(float f);
129 #ifndef __GNUC__
130 #if defined(HAVE_BITSCANFORWARD64_INTRINSIC)
131 extern inline int msvc64_ctz64(ALuint64 v);
132 #elif defined(HAVE_BITSCANFORWARD_INTRINSIC)
133 extern inline int msvc_ctz64(ALuint64 v);
134 #else
135 extern inline int fallback_popcnt64(ALuint64 v);
136 extern inline int fallback_ctz64(ALuint64 value);
137 #endif
138 #endif
141 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
142 defined(_M_IX86) || defined(_M_X64))
143 typedef unsigned int reg_type;
144 static inline void get_cpuid(int f, reg_type *regs)
145 { __get_cpuid(f, &regs[0], &regs[1], &regs[2], &regs[3]); }
146 #define CAN_GET_CPUID
147 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
148 defined(_M_IX86) || defined(_M_X64))
149 typedef int reg_type;
150 static inline void get_cpuid(int f, reg_type *regs)
151 { (__cpuid)(regs, f); }
152 #define CAN_GET_CPUID
153 #endif
155 int CPUCapFlags = 0;
157 void FillCPUCaps(int capfilter)
159 int caps = 0;
161 /* FIXME: We really should get this for all available CPUs in case different
162 * CPUs have different caps (is that possible on one machine?). */
163 #ifdef CAN_GET_CPUID
164 union {
165 reg_type regs[4];
166 char str[sizeof(reg_type[4])];
167 } cpuinf[3] = {{ { 0, 0, 0, 0 } }};
169 get_cpuid(0, cpuinf[0].regs);
170 if(cpuinf[0].regs[0] == 0)
171 ERR("Failed to get CPUID\n");
172 else
174 unsigned int maxfunc = cpuinf[0].regs[0];
175 unsigned int maxextfunc;
177 get_cpuid(0x80000000, cpuinf[0].regs);
178 maxextfunc = cpuinf[0].regs[0];
180 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
182 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
183 if(maxextfunc >= 0x80000004)
185 get_cpuid(0x80000002, cpuinf[0].regs);
186 get_cpuid(0x80000003, cpuinf[1].regs);
187 get_cpuid(0x80000004, cpuinf[2].regs);
188 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
191 if(maxfunc >= 1)
193 get_cpuid(1, cpuinf[0].regs);
194 if((cpuinf[0].regs[3]&(1<<25)))
195 caps |= CPU_CAP_SSE;
196 if((caps&CPU_CAP_SSE) && (cpuinf[0].regs[3]&(1<<26)))
197 caps |= CPU_CAP_SSE2;
198 if((caps&CPU_CAP_SSE2) && (cpuinf[0].regs[2]&(1<<0)))
199 caps |= CPU_CAP_SSE3;
200 if((caps&CPU_CAP_SSE3) && (cpuinf[0].regs[2]&(1<<19)))
201 caps |= CPU_CAP_SSE4_1;
204 #else
205 /* Assume support for whatever's supported if we can't check for it */
206 #if defined(HAVE_SSE4_1)
207 #warning "Assuming SSE 4.1 run-time support!"
208 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
209 #elif defined(HAVE_SSE3)
210 #warning "Assuming SSE 3 run-time support!"
211 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
212 #elif defined(HAVE_SSE2)
213 #warning "Assuming SSE 2 run-time support!"
214 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
215 #elif defined(HAVE_SSE)
216 #warning "Assuming SSE run-time support!"
217 caps |= CPU_CAP_SSE;
218 #endif
219 #endif
220 #ifdef HAVE_NEON
221 FILE *file = fopen("/proc/cpuinfo", "rt");
222 if(!file)
223 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
224 else
226 al_string features = AL_STRING_INIT_STATIC();
227 char buf[256];
229 while(fgets(buf, sizeof(buf), file) != NULL)
231 if(strncmp(buf, "Features\t:", 10) != 0)
232 continue;
234 alstr_copy_cstr(&features, buf+10);
235 while(VECTOR_BACK(features) != '\n')
237 if(fgets(buf, sizeof(buf), file) == NULL)
238 break;
239 alstr_append_cstr(&features, buf);
241 break;
243 fclose(file);
244 file = NULL;
246 if(!alstr_empty(features))
248 const char *str = alstr_get_cstr(features);
249 while(isspace(str[0])) ++str;
251 TRACE("Got features string:%s\n", str);
252 while((str=strstr(str, "neon")) != NULL)
254 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
256 caps |= CPU_CAP_NEON;
257 break;
259 ++str;
263 alstr_reset(&features);
265 #endif
267 TRACE("Extensions:%s%s%s%s%s%s\n",
268 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
269 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
270 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
271 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
272 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
273 ((!capfilter) ? " -none-" : "")
275 CPUCapFlags = caps & capfilter;
279 void SetMixerFPUMode(FPUCtl *ctl)
281 #if defined(__GNUC__) && defined(HAVE_SSE)
282 if((CPUCapFlags&CPU_CAP_SSE))
284 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
285 unsigned int sseState = ctl->sse_state;
286 sseState |= 0x8000; /* set flush-to-zero */
287 if((CPUCapFlags&CPU_CAP_SSE2))
288 sseState |= 0x0040; /* set denormals-are-zero */
289 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
292 #elif defined(HAVE___CONTROL87_2)
294 __control87_2(0, 0, &ctl->state, &ctl->sse_state);
295 _control87(_DN_FLUSH, _MCW_DN);
297 #elif defined(HAVE__CONTROLFP)
299 ctl->state = _controlfp(0, 0);
300 _controlfp(_DN_FLUSH, _MCW_DN);
301 #endif
304 void RestoreFPUMode(const FPUCtl *ctl)
306 #if defined(__GNUC__) && defined(HAVE_SSE)
307 if((CPUCapFlags&CPU_CAP_SSE))
308 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
310 #elif defined(HAVE___CONTROL87_2)
312 int mode;
313 __control87_2(ctl->state, _MCW_DN, &mode, NULL);
314 __control87_2(ctl->sse_state, _MCW_DN, NULL, &mode);
316 #elif defined(HAVE__CONTROLFP)
318 _controlfp(ctl->state, _MCW_DN);
319 #endif
323 static int StringSortCompare(const void *str1, const void *str2)
325 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
328 #ifdef _WIN32
330 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
332 WCHAR *ret = NULL;
333 while(*str)
335 if(*str == ch)
336 ret = str;
337 ++str;
339 return ret;
342 void GetProcBinary(al_string *path, al_string *fname)
344 WCHAR *pathname, *sep;
345 DWORD pathlen;
346 DWORD len;
348 pathlen = 256;
349 pathname = malloc(pathlen * sizeof(pathname[0]));
350 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
352 free(pathname);
353 pathlen <<= 1;
354 pathname = malloc(pathlen * sizeof(pathname[0]));
356 if(len == 0)
358 free(pathname);
359 ERR("Failed to get process name: error %lu\n", GetLastError());
360 return;
363 pathname[len] = 0;
364 if((sep=strrchrW(pathname, '\\')) != NULL)
366 WCHAR *sep2 = strrchrW(sep+1, '/');
367 if(sep2) sep = sep2;
369 else
370 sep = strrchrW(pathname, '/');
372 if(sep)
374 if(path) alstr_copy_wrange(path, pathname, sep);
375 if(fname) alstr_copy_wcstr(fname, sep+1);
377 else
379 if(path) alstr_clear(path);
380 if(fname) alstr_copy_wcstr(fname, pathname);
382 free(pathname);
384 if(path && fname)
385 TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
386 else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
387 else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
391 static WCHAR *FromUTF8(const char *str)
393 WCHAR *out = NULL;
394 int len;
396 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
398 out = calloc(sizeof(WCHAR), len);
399 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
401 return out;
405 void *LoadLib(const char *name)
407 HANDLE hdl = NULL;
408 WCHAR *wname;
410 wname = FromUTF8(name);
411 if(!wname)
412 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
413 else
415 hdl = LoadLibraryW(wname);
416 free(wname);
418 return hdl;
420 void CloseLib(void *handle)
421 { FreeLibrary((HANDLE)handle); }
422 void *GetSymbol(void *handle, const char *name)
424 void *ret;
426 ret = (void*)GetProcAddress((HANDLE)handle, name);
427 if(ret == NULL)
428 ERR("Failed to load %s\n", name);
429 return ret;
432 WCHAR *strdupW(const WCHAR *str)
434 const WCHAR *n;
435 WCHAR *ret;
436 size_t len;
438 n = str;
439 while(*n) n++;
440 len = n - str;
442 ret = calloc(sizeof(WCHAR), len+1);
443 if(ret != NULL)
444 memcpy(ret, str, sizeof(WCHAR)*len);
445 return ret;
448 FILE *al_fopen(const char *fname, const char *mode)
450 WCHAR *wname=NULL, *wmode=NULL;
451 FILE *file = NULL;
453 wname = FromUTF8(fname);
454 wmode = FromUTF8(mode);
455 if(!wname)
456 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
457 else if(!wmode)
458 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
459 else
460 file = _wfopen(wname, wmode);
462 free(wname);
463 free(wmode);
465 return file;
469 void al_print(const char *type, const char *func, const char *fmt, ...)
471 char str[1024];
472 WCHAR *wstr;
473 va_list ap;
475 va_start(ap, fmt);
476 vsnprintf(str, sizeof(str), fmt, ap);
477 va_end(ap);
479 str[sizeof(str)-1] = 0;
480 wstr = FromUTF8(str);
481 if(!wstr)
482 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
483 else
485 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
486 free(wstr);
487 wstr = NULL;
489 fflush(LogFile);
493 static inline int is_slash(int c)
494 { return (c == '\\' || c == '/'); }
496 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
498 al_string pathstr = AL_STRING_INIT_STATIC();
499 WIN32_FIND_DATAW fdata;
500 WCHAR *wpath;
501 HANDLE hdl;
503 alstr_copy_cstr(&pathstr, path);
504 alstr_append_cstr(&pathstr, "\\*");
505 alstr_append_cstr(&pathstr, ext);
507 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
509 wpath = FromUTF8(alstr_get_cstr(pathstr));
511 hdl = FindFirstFileW(wpath, &fdata);
512 if(hdl != INVALID_HANDLE_VALUE)
514 size_t base = VECTOR_SIZE(*results);
515 do {
516 al_string str = AL_STRING_INIT_STATIC();
517 alstr_copy_cstr(&str, path);
518 alstr_append_char(&str, '\\');
519 alstr_append_wcstr(&str, fdata.cFileName);
520 TRACE("Got result %s\n", alstr_get_cstr(str));
521 VECTOR_PUSH_BACK(*results, str);
522 } while(FindNextFileW(hdl, &fdata));
523 FindClose(hdl);
525 if(VECTOR_SIZE(*results) > base)
526 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
527 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
530 free(wpath);
531 alstr_reset(&pathstr);
534 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
536 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
537 static RefCount search_lock;
538 vector_al_string results = VECTOR_INIT_STATIC();
539 size_t i;
541 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
542 althrd_yield();
544 /* If the path is absolute, use it directly. */
545 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
547 al_string path = AL_STRING_INIT_STATIC();
548 alstr_copy_cstr(&path, subdir);
549 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
550 VECTOR_FOR_EACH(char, path, FIX_SLASH);
551 #undef FIX_SLASH
553 DirectorySearch(alstr_get_cstr(path), ext, &results);
555 alstr_reset(&path);
557 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
558 DirectorySearch(subdir, ext, &results);
559 else
561 al_string path = AL_STRING_INIT_STATIC();
562 WCHAR *cwdbuf;
564 /* Search the app-local directory. */
565 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
567 alstr_copy_wcstr(&path, cwdbuf);
568 if(is_slash(VECTOR_BACK(path)))
570 VECTOR_POP_BACK(path);
571 *VECTOR_END(path) = 0;
574 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
575 alstr_copy_cstr(&path, ".");
576 else
578 alstr_copy_wcstr(&path, cwdbuf);
579 if(is_slash(VECTOR_BACK(path)))
581 VECTOR_POP_BACK(path);
582 *VECTOR_END(path) = 0;
584 free(cwdbuf);
586 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
587 VECTOR_FOR_EACH(char, path, FIX_SLASH);
588 #undef FIX_SLASH
589 DirectorySearch(alstr_get_cstr(path), ext, &results);
591 /* Search the local and global data dirs. */
592 for(i = 0;i < COUNTOF(ids);i++)
594 WCHAR buffer[MAX_PATH];
595 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
597 alstr_copy_wcstr(&path, buffer);
598 if(!is_slash(VECTOR_BACK(path)))
599 alstr_append_char(&path, '\\');
600 alstr_append_cstr(&path, subdir);
601 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
602 VECTOR_FOR_EACH(char, path, FIX_SLASH);
603 #undef FIX_SLASH
605 DirectorySearch(alstr_get_cstr(path), ext, &results);
609 alstr_reset(&path);
612 ATOMIC_STORE_SEQ(&search_lock, 0);
614 return results;
618 struct FileMapping MapFileToMem(const char *fname)
620 struct FileMapping ret = { NULL, NULL, NULL, 0 };
621 MEMORY_BASIC_INFORMATION meminfo;
622 HANDLE file, fmap;
623 WCHAR *wname;
624 void *ptr;
626 wname = FromUTF8(fname);
628 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
629 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
630 if(file == INVALID_HANDLE_VALUE)
632 ERR("Failed to open %s: %lu\n", fname, GetLastError());
633 free(wname);
634 return ret;
636 free(wname);
637 wname = NULL;
639 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
640 if(!fmap)
642 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
643 CloseHandle(file);
644 return ret;
647 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
648 if(!ptr)
650 ERR("Failed to map %s: %lu\n", fname, GetLastError());
651 CloseHandle(fmap);
652 CloseHandle(file);
653 return ret;
656 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
658 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
659 UnmapViewOfFile(ptr);
660 CloseHandle(fmap);
661 CloseHandle(file);
662 return ret;
665 ret.file = file;
666 ret.fmap = fmap;
667 ret.ptr = ptr;
668 ret.len = meminfo.RegionSize;
669 return ret;
672 void UnmapFileMem(const struct FileMapping *mapping)
674 UnmapViewOfFile(mapping->ptr);
675 CloseHandle(mapping->fmap);
676 CloseHandle(mapping->file);
679 #else
681 void GetProcBinary(al_string *path, al_string *fname)
683 char *pathname = NULL;
684 size_t pathlen;
686 #ifdef __FreeBSD__
687 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
688 if(sysctl(mib, 4, NULL, &pathlen, NULL, 0) == -1)
689 WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno));
690 else
692 pathname = malloc(pathlen + 1);
693 sysctl(mib, 4, (void*)pathname, &pathlen, NULL, 0);
694 pathname[pathlen] = 0;
696 #endif
697 #ifdef HAVE_PROC_PIDPATH
698 if(!pathname)
700 const pid_t pid = getpid();
701 char procpath[PROC_PIDPATHINFO_MAXSIZE];
702 int ret;
704 ret = proc_pidpath(pid, procpath, sizeof(procpath));
705 if(ret < 1)
707 WARN("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
708 free(pathname);
709 pathname = NULL;
711 else
713 pathlen = strlen(procpath);
714 pathname = strdup(procpath);
717 #endif
718 if(!pathname)
720 const char *selfname;
721 ssize_t len;
723 pathlen = 256;
724 pathname = malloc(pathlen);
726 selfname = "/proc/self/exe";
727 len = readlink(selfname, pathname, pathlen);
728 if(len == -1 && errno == ENOENT)
730 selfname = "/proc/self/file";
731 len = readlink(selfname, pathname, pathlen);
733 if(len == -1 && errno == ENOENT)
735 selfname = "/proc/curproc/exe";
736 len = readlink(selfname, pathname, pathlen);
738 if(len == -1 && errno == ENOENT)
740 selfname = "/proc/curproc/file";
741 len = readlink(selfname, pathname, pathlen);
744 while(len > 0 && (size_t)len == pathlen)
746 free(pathname);
747 pathlen <<= 1;
748 pathname = malloc(pathlen);
749 len = readlink(selfname, pathname, pathlen);
751 if(len <= 0)
753 free(pathname);
754 WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
755 return;
758 pathname[len] = 0;
761 char *sep = strrchr(pathname, '/');
762 if(sep)
764 if(path) alstr_copy_range(path, pathname, sep);
765 if(fname) alstr_copy_cstr(fname, sep+1);
767 else
769 if(path) alstr_clear(path);
770 if(fname) alstr_copy_cstr(fname, pathname);
772 free(pathname);
774 if(path && fname)
775 TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
776 else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
777 else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
781 #ifdef HAVE_DLFCN_H
783 void *LoadLib(const char *name)
785 const char *err;
786 void *handle;
788 dlerror();
789 handle = dlopen(name, RTLD_NOW);
790 if((err=dlerror()) != NULL)
791 handle = NULL;
792 return handle;
794 void CloseLib(void *handle)
795 { dlclose(handle); }
796 void *GetSymbol(void *handle, const char *name)
798 const char *err;
799 void *sym;
801 dlerror();
802 sym = dlsym(handle, name);
803 if((err=dlerror()) != NULL)
805 WARN("Failed to load %s: %s\n", name, err);
806 sym = NULL;
808 return sym;
811 #endif /* HAVE_DLFCN_H */
813 void al_print(const char *type, const char *func, const char *fmt, ...)
815 va_list ap;
817 va_start(ap, fmt);
818 fprintf(LogFile, "AL lib: %s %s: ", type, func);
819 vfprintf(LogFile, fmt, ap);
820 va_end(ap);
822 fflush(LogFile);
826 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
828 size_t extlen = strlen(ext);
829 DIR *dir;
831 TRACE("Searching %s for *%s\n", path, ext);
832 dir = opendir(path);
833 if(dir != NULL)
835 size_t base = VECTOR_SIZE(*results);
836 struct dirent *dirent;
837 while((dirent=readdir(dir)) != NULL)
839 al_string str;
840 size_t len;
841 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
842 continue;
844 len = strlen(dirent->d_name);
845 if(!(len > extlen))
846 continue;
847 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
848 continue;
850 AL_STRING_INIT(str);
851 alstr_copy_cstr(&str, path);
852 if(VECTOR_BACK(str) != '/')
853 alstr_append_char(&str, '/');
854 alstr_append_cstr(&str, dirent->d_name);
855 TRACE("Got result %s\n", alstr_get_cstr(str));
856 VECTOR_PUSH_BACK(*results, str);
858 closedir(dir);
860 if(VECTOR_SIZE(*results) > base)
861 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
862 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
866 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
868 static RefCount search_lock;
869 vector_al_string results = VECTOR_INIT_STATIC();
871 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
872 althrd_yield();
874 if(subdir[0] == '/')
875 DirectorySearch(subdir, ext, &results);
876 else
878 al_string path = AL_STRING_INIT_STATIC();
879 const char *str, *next;
881 /* Search the app-local directory. */
882 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
883 DirectorySearch(str, ext, &results);
884 else
886 size_t cwdlen = 256;
887 char *cwdbuf = malloc(cwdlen);
888 while(!getcwd(cwdbuf, cwdlen))
890 free(cwdbuf);
891 cwdbuf = NULL;
892 if(errno != ERANGE)
893 break;
894 cwdlen <<= 1;
895 cwdbuf = malloc(cwdlen);
897 if(!cwdbuf)
898 DirectorySearch(".", ext, &results);
899 else
901 DirectorySearch(cwdbuf, ext, &results);
902 free(cwdbuf);
903 cwdbuf = NULL;
907 // Search local data dir
908 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
910 alstr_copy_cstr(&path, str);
911 if(VECTOR_BACK(path) != '/')
912 alstr_append_char(&path, '/');
913 alstr_append_cstr(&path, subdir);
914 DirectorySearch(alstr_get_cstr(path), ext, &results);
916 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
918 alstr_copy_cstr(&path, str);
919 if(VECTOR_BACK(path) == '/')
921 VECTOR_POP_BACK(path);
922 *VECTOR_END(path) = 0;
924 alstr_append_cstr(&path, "/.local/share/");
925 alstr_append_cstr(&path, subdir);
926 DirectorySearch(alstr_get_cstr(path), ext, &results);
929 // Search global data dirs
930 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
931 str = "/usr/local/share/:/usr/share/";
933 next = str;
934 while((str=next) != NULL && str[0] != '\0')
936 next = strchr(str, ':');
937 if(!next)
938 alstr_copy_cstr(&path, str);
939 else
941 alstr_copy_range(&path, str, next);
942 ++next;
944 if(!alstr_empty(path))
946 if(VECTOR_BACK(path) != '/')
947 alstr_append_char(&path, '/');
948 alstr_append_cstr(&path, subdir);
950 DirectorySearch(alstr_get_cstr(path), ext, &results);
954 alstr_reset(&path);
957 ATOMIC_STORE_SEQ(&search_lock, 0);
959 return results;
963 struct FileMapping MapFileToMem(const char *fname)
965 struct FileMapping ret = { -1, NULL, 0 };
966 struct stat sbuf;
967 void *ptr;
968 int fd;
970 fd = open(fname, O_RDONLY, 0);
971 if(fd == -1)
973 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
974 return ret;
976 if(fstat(fd, &sbuf) == -1)
978 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
979 close(fd);
980 return ret;
983 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
984 if(ptr == MAP_FAILED)
986 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
987 close(fd);
988 return ret;
991 ret.fd = fd;
992 ret.ptr = ptr;
993 ret.len = sbuf.st_size;
994 return ret;
997 void UnmapFileMem(const struct FileMapping *mapping)
999 munmap(mapping->ptr, mapping->len);
1000 close(mapping->fd);
1003 #endif
1006 void SetRTPriority(void)
1008 ALboolean failed = AL_FALSE;
1010 #ifdef _WIN32
1011 if(RTPrioLevel > 0)
1012 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
1013 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
1014 if(RTPrioLevel > 0)
1016 struct sched_param param;
1017 /* Use the minimum real-time priority possible for now (on Linux this
1018 * should be 1 for SCHED_RR) */
1019 param.sched_priority = sched_get_priority_min(SCHED_RR);
1020 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
1022 #else
1023 /* Real-time priority not available */
1024 failed = (RTPrioLevel>0);
1025 #endif
1026 if(failed)
1027 ERR("Failed to set priority level for thread\n");
1031 extern inline void alstr_reset(al_string *str);
1032 extern inline size_t alstr_length(const_al_string str);
1033 extern inline ALboolean alstr_empty(const_al_string str);
1034 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1036 void alstr_clear(al_string *str)
1038 if(!alstr_empty(*str))
1040 /* Reserve one more character than the total size of the string. This
1041 * is to ensure we have space to add a null terminator in the string
1042 * data so it can be used as a C-style string.
1044 VECTOR_RESIZE(*str, 0, 1);
1045 VECTOR_ELEM(*str, 0) = 0;
1049 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1050 const al_string_char_type *str2, size_t str2len)
1052 size_t complen = (str1len < str2len) ? str1len : str2len;
1053 int ret = memcmp(str1, str2, complen);
1054 if(ret == 0)
1056 if(str1len > str2len) return 1;
1057 if(str1len < str2len) return -1;
1059 return ret;
1061 int alstr_cmp(const_al_string str1, const_al_string str2)
1063 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1064 &VECTOR_FRONT(str2), alstr_length(str2));
1066 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1068 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1069 str2, strlen(str2));
1072 void alstr_copy(al_string *str, const_al_string from)
1074 size_t len = alstr_length(from);
1075 size_t i;
1077 VECTOR_RESIZE(*str, len, len+1);
1078 for(i = 0;i < len;i++)
1079 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1080 VECTOR_ELEM(*str, i) = 0;
1083 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1085 size_t len = strlen(from);
1086 size_t i;
1088 VECTOR_RESIZE(*str, len, len+1);
1089 for(i = 0;i < len;i++)
1090 VECTOR_ELEM(*str, i) = from[i];
1091 VECTOR_ELEM(*str, i) = 0;
1094 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1096 size_t len = to - from;
1097 size_t i;
1099 VECTOR_RESIZE(*str, len, len+1);
1100 for(i = 0;i < len;i++)
1101 VECTOR_ELEM(*str, i) = from[i];
1102 VECTOR_ELEM(*str, i) = 0;
1105 void alstr_append_char(al_string *str, const al_string_char_type c)
1107 size_t len = alstr_length(*str);
1108 VECTOR_RESIZE(*str, len+1, len+2);
1109 VECTOR_BACK(*str) = c;
1110 VECTOR_ELEM(*str, len+1) = 0;
1113 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1115 size_t len = strlen(from);
1116 if(len != 0)
1118 size_t base = alstr_length(*str);
1119 size_t i;
1121 VECTOR_RESIZE(*str, base+len, base+len+1);
1122 for(i = 0;i < len;i++)
1123 VECTOR_ELEM(*str, base+i) = from[i];
1124 VECTOR_ELEM(*str, base+i) = 0;
1128 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1130 size_t len = to - from;
1131 if(len != 0)
1133 size_t base = alstr_length(*str);
1134 size_t i;
1136 VECTOR_RESIZE(*str, base+len, base+len+1);
1137 for(i = 0;i < len;i++)
1138 VECTOR_ELEM(*str, base+i) = from[i];
1139 VECTOR_ELEM(*str, base+i) = 0;
1143 #ifdef _WIN32
1144 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1146 int len;
1147 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1149 VECTOR_RESIZE(*str, len-1, len);
1150 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1151 VECTOR_ELEM(*str, len-1) = 0;
1155 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1157 int len;
1158 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1160 size_t base = alstr_length(*str);
1161 VECTOR_RESIZE(*str, base+len-1, base+len);
1162 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1163 VECTOR_ELEM(*str, base+len-1) = 0;
1167 void alstr_copy_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1169 int len;
1170 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1172 VECTOR_RESIZE(*str, len, len+1);
1173 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_FRONT(*str), len+1, NULL, NULL);
1174 VECTOR_ELEM(*str, len) = 0;
1178 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1180 int len;
1181 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1183 size_t base = alstr_length(*str);
1184 VECTOR_RESIZE(*str, base+len, base+len+1);
1185 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1186 VECTOR_ELEM(*str, base+len) = 0;
1189 #endif