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
23 #define _WIN32_IE 0x501
25 #define _WIN32_IE 0x400
49 #ifdef HAVE_SSE_INTRINSICS
50 #include <xmmintrin.h>
52 #ifdef HAVE_SYS_SYSCONF_H
53 #include <sys/sysconf.h>
56 #ifdef HAVE_PROC_PIDPATH
61 #include <sys/types.h>
62 #include <sys/sysctl.h>
67 #elif defined(_WIN32_IE)
73 #include "alfstream.h"
77 #include "fpu_modes.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
, ®s
[0], ®s
[1], ®s
[2], ®s
[3]); }
89 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
90 defined(_M_IX86) || defined(_M_X64))
92 static inline void get_cpuid(unsigned int f
, reg_type
*regs
)
93 { (__cpuid
)(regs
, f
); }
99 void FillCPUCaps(int capfilter
)
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?). */
108 char str
[sizeof(reg_type
[4])];
111 get_cpuid(0, cpuinf
[0].regs
);
112 if(cpuinf
[0].regs
[0] == 0)
113 ERR("Failed to get CPUID\n");
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
);
135 get_cpuid(1, cpuinf
[0].regs
);
136 if((cpuinf
[0].regs
[3]&(1<<25)))
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
;
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!"
163 al::ifstream file
{"/proc/cpuinfo"};
165 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
168 std::string features
;
170 auto getline
= [](std::istream
&f
, std::string
&output
) -> bool
172 while(f
.good() && f
.peek() == '\n')
174 return std::getline(f
, output
) && !output
.empty();
177 while(getline(file
, features
))
179 if(features
.compare(0, 10, "Features\t:", 10) == 0)
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
;
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
;
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
));
231 this->in_mode
= true;
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
));
246 this->in_mode
= false;
252 const PathNamePair
&GetProcBinary()
254 static PathNamePair ret
;
255 if(!ret
.fname
.empty() || !ret
.path
.empty())
258 al::vector
<WCHAR
> fullpath(256);
260 while((len
=GetModuleFileNameW(nullptr, fullpath
.data(), static_cast<DWORD
>(fullpath
.size()))) == fullpath
.size())
261 fullpath
.resize(fullpath
.size() << 1);
264 ERR("Failed to get process name: error %lu\n", GetLastError());
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())
277 ret
.fname
= wstr_to_utf8(&*sep
+ 1);
278 ret
.path
= wstr_to_utf8(fullpath
.data());
281 ret
.fname
= wstr_to_utf8(fullpath
.data());
283 TRACE("Got binary: %s, %s\n", ret
.path
.c_str(), ret
.fname
.c_str());
288 void al_print(FILE *logfile
, const char *fmt
, ...)
290 al::vector
<char> dynmsg
;
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);
302 msglen
= std::vsnprintf(str
, dynmsg
.size(), fmt
, args2
);
307 std::wstring wstr
{utf8_to_wstr(str
)};
308 fprintf(logfile
, "%ls", wstr
.c_str());
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
};
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();
330 results
->emplace_back();
331 std::string
&str
= results
->back();
334 str
+= wstr_to_utf8(fdata
.cFileName
);
335 TRACE(" got %s\n", str
.c_str());
336 } while(FindNextFileW(hdl
, &fdata
));
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
);
357 if(subdir
[0] == '\\' && subdir
[1] == '\\' && subdir
[2] == '?' && subdir
[3] == '\\')
359 DirectorySearch(subdir
, ext
, &results
);
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()))
372 else if(WCHAR
*cwdbuf
{_wgetcwd(nullptr, 0)})
374 path
= wstr_to_utf8(cwdbuf
);
375 if(is_slash(path
.back()))
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
};
388 WCHAR buffer
[MAX_PATH
];
389 if(SHGetSpecialFolderPathW(nullptr, buffer
, id
, FALSE
) == FALSE
)
392 path
= wstr_to_utf8(buffer
);
393 if(!is_slash(path
.back()))
396 std::replace(path
.begin(), path
.end(), '/', '\\');
398 DirectorySearch(path
.c_str(), ext
, &results
);
404 void SetRTPriority(void)
408 failed
= !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL
);
409 if(failed
) ERR("Failed to set priority level for thread\n");
414 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
419 const PathNamePair
&GetProcBinary()
421 static PathNamePair ret
;
422 if(!ret
.fname
.empty() || !ret
.path
.empty())
425 al::vector
<char> pathname
;
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
));
433 pathname
.resize(pathlen
+ 1);
434 sysctl(mib
, 4, pathname
.data(), &pathlen
, nullptr, 0);
435 pathname
.resize(pathlen
);
438 #ifdef HAVE_PROC_PIDPATH
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
));
446 pathname
.insert(pathname
.end(), procpath
, procpath
+strlen(procpath
));
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());
478 WARN("Failed to readlink %s: %s\n", selfname
, strerror(errno
));
482 pathname
.resize(static_cast<size_t>(len
));
484 while(!pathname
.empty() && pathname
.back() == 0)
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());
494 ret
.fname
= std::string(pathname
.cbegin(), pathname
.cend());
496 TRACE("Got binary: %s, %s\n", ret
.path
.c_str(), ret
.fname
.c_str());
501 void al_print(FILE *logfile
, const char *fmt
, ...)
506 vfprintf(logfile
, fmt
, ap
);
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
)};
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)
528 size_t len
{strlen(dirent
->d_name
)};
529 if(len
<= extlen
) continue;
530 if(al::strcasecmp(dirent
->d_name
+len
-extlen
, ext
) != 0)
533 results
->emplace_back();
534 std::string
&str
= results
->back();
536 if(str
.back() != '/')
538 str
+= dirent
->d_name
;
539 TRACE(" got %s\n", str
.c_str());
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
;
555 DirectorySearch(subdir
, ext
, &results
);
559 /* Search the app-local directory. */
560 if(auto localpath
= al::getenv("ALSOFT_LOCAL_PATH"))
561 DirectorySearch(localpath
->c_str(), ext
, &results
);
564 al::vector
<char> cwdbuf(256);
565 while(!getcwd(cwdbuf
.data(), cwdbuf
.size()))
572 cwdbuf
.resize(cwdbuf
.size() << 1);
575 DirectorySearch(".", ext
, &results
);
578 DirectorySearch(cwdbuf
.data(), ext
, &results
);
583 // Search local data dir
584 if(auto datapath
= al::getenv("XDG_DATA_HOME"))
586 std::string
&path
= *datapath
;
587 if(path
.back() != '/')
590 DirectorySearch(path
.c_str(), ext
, &results
);
592 else if(auto homepath
= al::getenv("HOME"))
594 std::string
&path
= *homepath
;
595 if(path
.back() == '/')
597 path
+= "/.local/share/";
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/")};
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
)};
614 if(path
.empty()) continue;
615 if(path
.back() != '/')
619 DirectorySearch(path
.c_str(), ext
, &results
);
628 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
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
, ¶m
);
638 /* Real-time priority not available */
639 failed
= (RTPrioLevel
>0);
642 ERR("Failed to set priority level for thread\n");