Clean up some unnecessary includes
[openal-soft.git] / alc / helpers.cpp
blob2d532db17d9627a2f93302e3c540ca9561649b76
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 <algorithm>
32 #include <cerrno>
33 #include <cstdarg>
34 #include <cstdlib>
35 #include <cstdio>
36 #include <cstring>
37 #include <mutex>
38 #include <string>
40 #ifdef HAVE_DIRENT_H
41 #include <dirent.h>
42 #endif
43 #ifdef HAVE_INTRIN_H
44 #include <intrin.h>
45 #endif
46 #ifdef HAVE_CPUID_H
47 #include <cpuid.h>
48 #endif
49 #ifdef HAVE_SSE_INTRINSICS
50 #include <xmmintrin.h>
51 #endif
52 #ifdef HAVE_SYS_SYSCONF_H
53 #include <sys/sysconf.h>
54 #endif
56 #ifdef HAVE_PROC_PIDPATH
57 #include <libproc.h>
58 #endif
60 #ifdef __FreeBSD__
61 #include <sys/types.h>
62 #include <sys/sysctl.h>
63 #endif
65 #ifndef _WIN32
66 #include <unistd.h>
67 #elif defined(_WIN32_IE)
68 #include <shlobj.h>
69 #endif
71 #include "alcmain.h"
72 #include "almalloc.h"
73 #include "alfstream.h"
74 #include "alstring.h"
75 #include "compat.h"
76 #include "cpu_caps.h"
77 #include "fpu_modes.h"
78 #include "logging.h"
79 #include "strutils.h"
80 #include "vector.h"
83 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
84 defined(_M_IX86) || defined(_M_X64))
85 using reg_type = unsigned int;
86 static inline void get_cpuid(unsigned int f, reg_type *regs)
87 { __get_cpuid(f, &regs[0], &regs[1], &regs[2], &regs[3]); }
88 #define CAN_GET_CPUID
89 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
90 defined(_M_IX86) || defined(_M_X64))
91 using reg_type = int;
92 static inline void get_cpuid(unsigned int f, reg_type *regs)
93 { (__cpuid)(regs, f); }
94 #define CAN_GET_CPUID
95 #endif
97 int CPUCapFlags = 0;
99 void FillCPUCaps(int capfilter)
101 int caps = 0;
103 /* FIXME: We really should get this for all available CPUs in case different
104 * CPUs have different caps (is that possible on one machine?). */
105 #ifdef CAN_GET_CPUID
106 union {
107 reg_type regs[4];
108 char str[sizeof(reg_type[4])];
109 } cpuinf[3]{};
111 get_cpuid(0, cpuinf[0].regs);
112 if(cpuinf[0].regs[0] == 0)
113 ERR("Failed to get CPUID\n");
114 else
116 unsigned int maxfunc = cpuinf[0].regs[0];
117 unsigned int maxextfunc;
119 get_cpuid(0x80000000, cpuinf[0].regs);
120 maxextfunc = cpuinf[0].regs[0];
122 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
124 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
125 if(maxextfunc >= 0x80000004)
127 get_cpuid(0x80000002, cpuinf[0].regs);
128 get_cpuid(0x80000003, cpuinf[1].regs);
129 get_cpuid(0x80000004, cpuinf[2].regs);
130 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
133 if(maxfunc >= 1)
135 get_cpuid(1, cpuinf[0].regs);
136 if((cpuinf[0].regs[3]&(1<<25)))
137 caps |= CPU_CAP_SSE;
138 if((caps&CPU_CAP_SSE) && (cpuinf[0].regs[3]&(1<<26)))
139 caps |= CPU_CAP_SSE2;
140 if((caps&CPU_CAP_SSE2) && (cpuinf[0].regs[2]&(1<<0)))
141 caps |= CPU_CAP_SSE3;
142 if((caps&CPU_CAP_SSE3) && (cpuinf[0].regs[2]&(1<<19)))
143 caps |= CPU_CAP_SSE4_1;
146 #else
147 /* Assume support for whatever's supported if we can't check for it */
148 #if defined(HAVE_SSE4_1)
149 #warning "Assuming SSE 4.1 run-time support!"
150 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
151 #elif defined(HAVE_SSE3)
152 #warning "Assuming SSE 3 run-time support!"
153 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
154 #elif defined(HAVE_SSE2)
155 #warning "Assuming SSE 2 run-time support!"
156 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
157 #elif defined(HAVE_SSE)
158 #warning "Assuming SSE run-time support!"
159 caps |= CPU_CAP_SSE;
160 #endif
161 #endif
162 #ifdef HAVE_NEON
163 al::ifstream file{"/proc/cpuinfo"};
164 if(!file.is_open())
165 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
166 else
168 std::string features;
170 auto getline = [](std::istream &f, std::string &output) -> bool
172 while(f.good() && f.peek() == '\n')
173 f.ignore();
174 return std::getline(f, output) && !output.empty();
177 while(getline(file, features))
179 if(features.compare(0, 10, "Features\t:", 10) == 0)
180 break;
182 file.close();
184 size_t extpos{9};
185 while((extpos=features.find("neon", extpos+1)) != std::string::npos)
187 if((extpos == 0 || std::isspace(features[extpos-1])) &&
188 (extpos+4 == features.length() || std::isspace(features[extpos+4])))
190 caps |= CPU_CAP_NEON;
191 break;
195 #endif
197 TRACE("Extensions:%s%s%s%s%s%s\n",
198 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
199 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
200 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
201 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
202 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
203 ((!capfilter) ? " -none-" : "")
205 CPUCapFlags = caps & capfilter;
209 FPUCtl::FPUCtl()
211 #if defined(HAVE_SSE_INTRINSICS)
212 this->sse_state = _mm_getcsr();
213 unsigned int sseState = this->sse_state;
214 sseState |= 0x8000; /* set flush-to-zero */
215 sseState |= 0x0040; /* set denormals-are-zero */
216 _mm_setcsr(sseState);
218 #elif defined(__GNUC__) && defined(HAVE_SSE)
220 if((CPUCapFlags&CPU_CAP_SSE))
222 __asm__ __volatile__("stmxcsr %0" : "=m" (*&this->sse_state));
223 unsigned int sseState = this->sse_state;
224 sseState |= 0x8000; /* set flush-to-zero */
225 if((CPUCapFlags&CPU_CAP_SSE2))
226 sseState |= 0x0040; /* set denormals-are-zero */
227 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
229 #endif
231 this->in_mode = true;
234 void FPUCtl::leave()
236 if(!this->in_mode) return;
238 #if defined(HAVE_SSE_INTRINSICS)
239 _mm_setcsr(this->sse_state);
241 #elif defined(__GNUC__) && defined(HAVE_SSE)
243 if((CPUCapFlags&CPU_CAP_SSE))
244 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&this->sse_state));
245 #endif
246 this->in_mode = false;
250 #ifdef _WIN32
252 const PathNamePair &GetProcBinary()
254 static PathNamePair ret;
255 if(!ret.fname.empty() || !ret.path.empty())
256 return ret;
258 al::vector<WCHAR> fullpath(256);
259 DWORD len;
260 while((len=GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()))) == fullpath.size())
261 fullpath.resize(fullpath.size() << 1);
262 if(len == 0)
264 ERR("Failed to get process name: error %lu\n", GetLastError());
265 return ret;
268 fullpath.resize(len);
269 if(fullpath.back() != 0)
270 fullpath.push_back(0);
272 auto sep = std::find(fullpath.rbegin()+1, fullpath.rend(), '\\');
273 sep = std::find(fullpath.rbegin()+1, sep, '/');
274 if(sep != fullpath.rend())
276 *sep = 0;
277 ret.fname = wstr_to_utf8(&*sep + 1);
278 ret.path = wstr_to_utf8(fullpath.data());
280 else
281 ret.fname = wstr_to_utf8(fullpath.data());
283 TRACE("Got binary: %s, %s\n", ret.path.c_str(), ret.fname.c_str());
284 return ret;
288 void al_print(FILE *logfile, const char *fmt, ...)
290 al::vector<char> dynmsg;
291 char stcmsg[256];
292 char *str{stcmsg};
294 va_list args, args2;
295 va_start(args, fmt);
296 va_copy(args2, args);
297 int msglen{std::vsnprintf(str, sizeof(stcmsg), fmt, args)};
298 if UNLIKELY(msglen >= 0 && static_cast<size_t>(msglen) >= sizeof(stcmsg))
300 dynmsg.resize(static_cast<size_t>(msglen) + 1u);
301 str = dynmsg.data();
302 msglen = std::vsnprintf(str, dynmsg.size(), fmt, args2);
304 va_end(args2);
305 va_end(args);
307 std::wstring wstr{utf8_to_wstr(str)};
308 fprintf(logfile, "%ls", wstr.c_str());
309 fflush(logfile);
313 static inline int is_slash(int c)
314 { return (c == '\\' || c == '/'); }
316 static void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
318 std::string pathstr{path};
319 pathstr += "\\*";
320 pathstr += ext;
321 TRACE("Searching %s\n", pathstr.c_str());
323 std::wstring wpath{utf8_to_wstr(pathstr.c_str())};
324 WIN32_FIND_DATAW fdata;
325 HANDLE hdl{FindFirstFileW(wpath.c_str(), &fdata)};
326 if(hdl != INVALID_HANDLE_VALUE)
328 size_t base = results->size();
329 do {
330 results->emplace_back();
331 std::string &str = results->back();
332 str = path;
333 str += '\\';
334 str += wstr_to_utf8(fdata.cFileName);
335 TRACE(" got %s\n", str.c_str());
336 } while(FindNextFileW(hdl, &fdata));
337 FindClose(hdl);
339 std::sort(results->begin()+base, results->end());
343 al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
345 static std::mutex search_lock;
346 std::lock_guard<std::mutex> _{search_lock};
348 /* If the path is absolute, use it directly. */
349 al::vector<std::string> results;
350 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
352 std::string path{subdir};
353 std::replace(path.begin(), path.end(), '/', '\\');
354 DirectorySearch(path.c_str(), ext, &results);
355 return results;
357 if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
359 DirectorySearch(subdir, ext, &results);
360 return results;
363 std::string path;
365 /* Search the app-local directory. */
366 if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH"))
368 path = wstr_to_utf8(localpath->c_str());
369 if(is_slash(path.back()))
370 path.pop_back();
372 else if(WCHAR *cwdbuf{_wgetcwd(nullptr, 0)})
374 path = wstr_to_utf8(cwdbuf);
375 if(is_slash(path.back()))
376 path.pop_back();
377 free(cwdbuf);
379 else
380 path = ".";
381 std::replace(path.begin(), path.end(), '/', '\\');
382 DirectorySearch(path.c_str(), ext, &results);
384 /* Search the local and global data dirs. */
385 static constexpr int ids[2]{ CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
386 for(int id : ids)
388 WCHAR buffer[MAX_PATH];
389 if(SHGetSpecialFolderPathW(nullptr, buffer, id, FALSE) == FALSE)
390 continue;
392 path = wstr_to_utf8(buffer);
393 if(!is_slash(path.back()))
394 path += '\\';
395 path += subdir;
396 std::replace(path.begin(), path.end(), '/', '\\');
398 DirectorySearch(path.c_str(), ext, &results);
401 return results;
404 void SetRTPriority(void)
406 bool failed = false;
407 if(RTPrioLevel > 0)
408 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
409 if(failed) ERR("Failed to set priority level for thread\n");
412 #else
414 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
415 #include <pthread.h>
416 #include <sched.h>
417 #endif
419 const PathNamePair &GetProcBinary()
421 static PathNamePair ret;
422 if(!ret.fname.empty() || !ret.path.empty())
423 return ret;
425 al::vector<char> pathname;
426 #ifdef __FreeBSD__
427 size_t pathlen;
428 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
429 if(sysctl(mib, 4, nullptr, &pathlen, nullptr, 0) == -1)
430 WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno));
431 else
433 pathname.resize(pathlen + 1);
434 sysctl(mib, 4, pathname.data(), &pathlen, nullptr, 0);
435 pathname.resize(pathlen);
437 #endif
438 #ifdef HAVE_PROC_PIDPATH
439 if(pathname.empty())
441 char procpath[PROC_PIDPATHINFO_MAXSIZE]{};
442 const pid_t pid{getpid()};
443 if(proc_pidpath(pid, procpath, sizeof(procpath)) < 1)
444 ERR("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
445 else
446 pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
448 #endif
449 if(pathname.empty())
451 pathname.resize(256);
453 const char *selfname{"/proc/self/exe"};
454 ssize_t len{readlink(selfname, pathname.data(), pathname.size())};
455 if(len == -1 && errno == ENOENT)
457 selfname = "/proc/self/file";
458 len = readlink(selfname, pathname.data(), pathname.size());
460 if(len == -1 && errno == ENOENT)
462 selfname = "/proc/curproc/exe";
463 len = readlink(selfname, pathname.data(), pathname.size());
465 if(len == -1 && errno == ENOENT)
467 selfname = "/proc/curproc/file";
468 len = readlink(selfname, pathname.data(), pathname.size());
471 while(len > 0 && static_cast<size_t>(len) == pathname.size())
473 pathname.resize(pathname.size() << 1);
474 len = readlink(selfname, pathname.data(), pathname.size());
476 if(len <= 0)
478 WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
479 return ret;
482 pathname.resize(static_cast<size_t>(len));
484 while(!pathname.empty() && pathname.back() == 0)
485 pathname.pop_back();
487 auto sep = std::find(pathname.crbegin(), pathname.crend(), '/');
488 if(sep != pathname.crend())
490 ret.path = std::string(pathname.cbegin(), sep.base()-1);
491 ret.fname = std::string(sep.base(), pathname.cend());
493 else
494 ret.fname = std::string(pathname.cbegin(), pathname.cend());
496 TRACE("Got binary: %s, %s\n", ret.path.c_str(), ret.fname.c_str());
497 return ret;
501 void al_print(FILE *logfile, const char *fmt, ...)
503 va_list ap;
505 va_start(ap, fmt);
506 vfprintf(logfile, fmt, ap);
507 va_end(ap);
509 fflush(logfile);
513 static void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
515 TRACE("Searching %s for *%s\n", path, ext);
516 DIR *dir{opendir(path)};
517 if(dir != nullptr)
519 auto base = results->cend() - results->cbegin();
520 const size_t extlen{strlen(ext)};
522 struct dirent *dirent;
523 while((dirent=readdir(dir)) != nullptr)
525 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
526 continue;
528 size_t len{strlen(dirent->d_name)};
529 if(len <= extlen) continue;
530 if(al::strcasecmp(dirent->d_name+len-extlen, ext) != 0)
531 continue;
533 results->emplace_back();
534 std::string &str = results->back();
535 str = path;
536 if(str.back() != '/')
537 str.push_back('/');
538 str += dirent->d_name;
539 TRACE(" got %s\n", str.c_str());
541 closedir(dir);
543 std::sort(results->begin()+base, results->end());
547 al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
549 static std::mutex search_lock;
550 std::lock_guard<std::mutex> _{search_lock};
552 al::vector<std::string> results;
553 if(subdir[0] == '/')
555 DirectorySearch(subdir, ext, &results);
556 return results;
559 /* Search the app-local directory. */
560 if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH"))
561 DirectorySearch(localpath->c_str(), ext, &results);
562 else
564 al::vector<char> cwdbuf(256);
565 while(!getcwd(cwdbuf.data(), cwdbuf.size()))
567 if(errno != ERANGE)
569 cwdbuf.clear();
570 break;
572 cwdbuf.resize(cwdbuf.size() << 1);
574 if(cwdbuf.empty())
575 DirectorySearch(".", ext, &results);
576 else
578 DirectorySearch(cwdbuf.data(), ext, &results);
579 cwdbuf.clear();
583 // Search local data dir
584 if(auto datapath = al::getenv("XDG_DATA_HOME"))
586 std::string &path = *datapath;
587 if(path.back() != '/')
588 path += '/';
589 path += subdir;
590 DirectorySearch(path.c_str(), ext, &results);
592 else if(auto homepath = al::getenv("HOME"))
594 std::string &path = *homepath;
595 if(path.back() == '/')
596 path.pop_back();
597 path += "/.local/share/";
598 path += subdir;
599 DirectorySearch(path.c_str(), ext, &results);
602 // Search global data dirs
603 std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
605 size_t curpos{0u};
606 while(curpos < datadirs.size())
608 size_t nextpos{datadirs.find(':', curpos)};
610 std::string path{(nextpos != std::string::npos) ?
611 datadirs.substr(curpos, nextpos++ - curpos) : datadirs.substr(curpos)};
612 curpos = nextpos;
614 if(path.empty()) continue;
615 if(path.back() != '/')
616 path += '/';
617 path += subdir;
619 DirectorySearch(path.c_str(), ext, &results);
622 return results;
625 void SetRTPriority()
627 bool failed = false;
628 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
629 if(RTPrioLevel > 0)
631 struct sched_param param;
632 /* Use the minimum real-time priority possible for now (on Linux this
633 * should be 1 for SCHED_RR) */
634 param.sched_priority = sched_get_priority_min(SCHED_RR);
635 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
637 #else
638 /* Real-time priority not available */
639 failed = (RTPrioLevel>0);
640 #endif
641 if(failed)
642 ERR("Failed to set priority level for thread\n");
645 #endif