17 #include "alfstream.h"
18 #include "alnumeric.h"
19 #include "aloptional.h"
27 /* Mixing thread piority level */
30 /* Allow reducing the process's RTTime limit for RTKit. */
31 bool AllowRTTimeLimit
{true};
38 const PathNamePair
&GetProcBinary()
40 static al::optional
<PathNamePair
> procbin
;
41 if(procbin
) return *procbin
;
43 auto fullpath
= al::vector
<WCHAR
>(256);
44 DWORD len
{GetModuleFileNameW(nullptr, fullpath
.data(), static_cast<DWORD
>(fullpath
.size()))};
45 while(len
== fullpath
.size())
47 fullpath
.resize(fullpath
.size() << 1);
48 len
= GetModuleFileNameW(nullptr, fullpath
.data(), static_cast<DWORD
>(fullpath
.size()));
52 ERR("Failed to get process name: error %lu\n", GetLastError());
53 procbin
= al::make_optional
<PathNamePair
>();
58 if(fullpath
.back() != 0)
59 fullpath
.push_back(0);
61 auto sep
= std::find(fullpath
.rbegin()+1, fullpath
.rend(), '\\');
62 sep
= std::find(fullpath
.rbegin()+1, sep
, '/');
63 if(sep
!= fullpath
.rend())
66 procbin
= al::make_optional
<PathNamePair
>(wstr_to_utf8(fullpath
.data()),
67 wstr_to_utf8(&*sep
+ 1));
70 procbin
= al::make_optional
<PathNamePair
>(std::string
{}, wstr_to_utf8(fullpath
.data()));
72 TRACE("Got binary: %s, %s\n", procbin
->path
.c_str(), procbin
->fname
.c_str());
78 void DirectorySearch(const char *path
, const char *ext
, al::vector
<std::string
> *const results
)
80 std::string pathstr
{path
};
83 TRACE("Searching %s\n", pathstr
.c_str());
85 std::wstring wpath
{utf8_to_wstr(pathstr
.c_str())};
86 WIN32_FIND_DATAW fdata
;
87 HANDLE hdl
{FindFirstFileW(wpath
.c_str(), &fdata
)};
88 if(hdl
== INVALID_HANDLE_VALUE
) return;
90 const auto base
= results
->size();
93 results
->emplace_back();
94 std::string
&str
= results
->back();
97 str
+= wstr_to_utf8(fdata
.cFileName
);
98 } while(FindNextFileW(hdl
, &fdata
));
101 const al::span
<std::string
> newlist
{results
->data()+base
, results
->size()-base
};
102 std::sort(newlist
.begin(), newlist
.end());
103 for(const auto &name
: newlist
)
104 TRACE(" got %s\n", name
.c_str());
109 al::vector
<std::string
> SearchDataFiles(const char *ext
, const char *subdir
)
111 auto is_slash
= [](int c
) noexcept
-> int { return (c
== '\\' || c
== '/'); };
113 static std::mutex search_lock
;
114 std::lock_guard
<std::mutex
> _
{search_lock
};
116 /* If the path is absolute, use it directly. */
117 al::vector
<std::string
> results
;
118 if(isalpha(subdir
[0]) && subdir
[1] == ':' && is_slash(subdir
[2]))
120 std::string path
{subdir
};
121 std::replace(path
.begin(), path
.end(), '/', '\\');
122 DirectorySearch(path
.c_str(), ext
, &results
);
125 if(subdir
[0] == '\\' && subdir
[1] == '\\' && subdir
[2] == '?' && subdir
[3] == '\\')
127 DirectorySearch(subdir
, ext
, &results
);
133 /* Search the app-local directory. */
134 if(auto localpath
= al::getenv(L
"ALSOFT_LOCAL_PATH"))
136 path
= wstr_to_utf8(localpath
->c_str());
137 if(is_slash(path
.back()))
140 else if(WCHAR
*cwdbuf
{_wgetcwd(nullptr, 0)})
142 path
= wstr_to_utf8(cwdbuf
);
143 if(is_slash(path
.back()))
149 std::replace(path
.begin(), path
.end(), '/', '\\');
150 DirectorySearch(path
.c_str(), ext
, &results
);
152 /* Search the local and global data dirs. */
153 static const int ids
[2]{ CSIDL_APPDATA
, CSIDL_COMMON_APPDATA
};
156 WCHAR buffer
[MAX_PATH
];
157 if(SHGetSpecialFolderPathW(nullptr, buffer
, id
, FALSE
) == FALSE
)
160 path
= wstr_to_utf8(buffer
);
161 if(!is_slash(path
.back()))
164 std::replace(path
.begin(), path
.end(), '/', '\\');
166 DirectorySearch(path
.c_str(), ext
, &results
);
172 void SetRTPriority(void)
176 if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL
))
177 ERR("Failed to set priority level for thread\n");
183 #include <sys/types.h>
187 #include <sys/sysctl.h>
190 #include <FindDirectory.h>
192 #ifdef HAVE_PROC_PIDPATH
195 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
200 #include <sys/time.h>
201 #include <sys/resource.h>
203 #include "dbus_wrap.h"
205 #ifndef RLIMIT_RTTIME
206 #define RLIMIT_RTTIME 15
210 const PathNamePair
&GetProcBinary()
212 static al::optional
<PathNamePair
> procbin
;
213 if(procbin
) return *procbin
;
215 al::vector
<char> pathname
;
218 int mib
[4] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1 };
219 if(sysctl(mib
, 4, nullptr, &pathlen
, nullptr, 0) == -1)
220 WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno
));
223 pathname
.resize(pathlen
+ 1);
224 sysctl(mib
, 4, pathname
.data(), &pathlen
, nullptr, 0);
225 pathname
.resize(pathlen
);
228 #ifdef HAVE_PROC_PIDPATH
231 char procpath
[PROC_PIDPATHINFO_MAXSIZE
]{};
232 const pid_t pid
{getpid()};
233 if(proc_pidpath(pid
, procpath
, sizeof(procpath
)) < 1)
234 ERR("proc_pidpath(%d, ...) failed: %s\n", pid
, strerror(errno
));
236 pathname
.insert(pathname
.end(), procpath
, procpath
+strlen(procpath
));
242 char procpath
[PATH_MAX
];
243 if(find_path(B_APP_IMAGE_SYMBOL
, B_FIND_PATH_IMAGE_PATH
, NULL
, procpath
, sizeof(procpath
)) == B_OK
)
244 pathname
.insert(pathname
.end(), procpath
, procpath
+strlen(procpath
));
250 static const char SelfLinkNames
[][32]{
257 pathname
.resize(256);
259 const char *selfname
{};
261 for(const char *name
: SelfLinkNames
)
264 len
= readlink(selfname
, pathname
.data(), pathname
.size());
265 if(len
>= 0 || errno
!= ENOENT
) break;
268 while(len
> 0 && static_cast<size_t>(len
) == pathname
.size())
270 pathname
.resize(pathname
.size() << 1);
271 len
= readlink(selfname
, pathname
.data(), pathname
.size());
275 WARN("Failed to readlink %s: %s\n", selfname
, strerror(errno
));
279 pathname
.resize(static_cast<size_t>(len
));
282 while(!pathname
.empty() && pathname
.back() == 0)
285 auto sep
= std::find(pathname
.crbegin(), pathname
.crend(), '/');
286 if(sep
!= pathname
.crend())
287 procbin
= al::make_optional
<PathNamePair
>(std::string(pathname
.cbegin(), sep
.base()-1),
288 std::string(sep
.base(), pathname
.cend()));
290 procbin
= al::make_optional
<PathNamePair
>(std::string
{},
291 std::string(pathname
.cbegin(), pathname
.cend()));
293 TRACE("Got binary: \"%s\", \"%s\"\n", procbin
->path
.c_str(), procbin
->fname
.c_str());
299 void DirectorySearch(const char *path
, const char *ext
, al::vector
<std::string
> *const results
)
301 TRACE("Searching %s for *%s\n", path
, ext
);
302 DIR *dir
{opendir(path
)};
305 const auto base
= results
->size();
306 const size_t extlen
{strlen(ext
)};
308 while(struct dirent
*dirent
{readdir(dir
)})
310 if(strcmp(dirent
->d_name
, ".") == 0 || strcmp(dirent
->d_name
, "..") == 0)
313 const size_t len
{strlen(dirent
->d_name
)};
314 if(len
<= extlen
) continue;
315 if(al::strcasecmp(dirent
->d_name
+len
-extlen
, ext
) != 0)
318 results
->emplace_back();
319 std::string
&str
= results
->back();
321 if(str
.back() != '/')
323 str
+= dirent
->d_name
;
327 const al::span
<std::string
> newlist
{results
->data()+base
, results
->size()-base
};
328 std::sort(newlist
.begin(), newlist
.end());
329 for(const auto &name
: newlist
)
330 TRACE(" got %s\n", name
.c_str());
335 al::vector
<std::string
> SearchDataFiles(const char *ext
, const char *subdir
)
337 static std::mutex search_lock
;
338 std::lock_guard
<std::mutex
> _
{search_lock
};
340 al::vector
<std::string
> results
;
343 DirectorySearch(subdir
, ext
, &results
);
347 /* Search the app-local directory. */
348 if(auto localpath
= al::getenv("ALSOFT_LOCAL_PATH"))
349 DirectorySearch(localpath
->c_str(), ext
, &results
);
352 al::vector
<char> cwdbuf(256);
353 while(!getcwd(cwdbuf
.data(), cwdbuf
.size()))
360 cwdbuf
.resize(cwdbuf
.size() << 1);
363 DirectorySearch(".", ext
, &results
);
366 DirectorySearch(cwdbuf
.data(), ext
, &results
);
371 // Search local data dir
372 if(auto datapath
= al::getenv("XDG_DATA_HOME"))
374 std::string
&path
= *datapath
;
375 if(path
.back() != '/')
378 DirectorySearch(path
.c_str(), ext
, &results
);
380 else if(auto homepath
= al::getenv("HOME"))
382 std::string
&path
= *homepath
;
383 if(path
.back() == '/')
385 path
+= "/.local/share/";
387 DirectorySearch(path
.c_str(), ext
, &results
);
390 // Search global data dirs
391 std::string datadirs
{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
394 while(curpos
< datadirs
.size())
396 size_t nextpos
{datadirs
.find(':', curpos
)};
398 std::string path
{(nextpos
!= std::string::npos
) ?
399 datadirs
.substr(curpos
, nextpos
++ - curpos
) : datadirs
.substr(curpos
)};
402 if(path
.empty()) continue;
403 if(path
.back() != '/')
407 DirectorySearch(path
.c_str(), ext
, &results
);
415 bool SetRTPriorityPthread(int prio
)
418 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
419 /* Get the min and max priority for SCHED_RR. Limit the max priority to
420 * half, for now, to ensure the thread can't take the highest priority and
423 int rtmin
{sched_get_priority_min(SCHED_RR
)};
424 int rtmax
{sched_get_priority_max(SCHED_RR
)};
425 rtmax
= (rtmax
-rtmin
)/2 + rtmin
;
427 struct sched_param param
{};
428 param
.sched_priority
= clampi(prio
, rtmin
, rtmax
);
429 #ifdef SCHED_RESET_ON_FORK
430 err
= pthread_setschedparam(pthread_self(), SCHED_RR
|SCHED_RESET_ON_FORK
, ¶m
);
433 err
= pthread_setschedparam(pthread_self(), SCHED_RR
, ¶m
);
434 if(err
== 0) return true;
437 WARN("pthread_setschedparam failed: %s (%d)\n", std::strerror(err
), err
);
441 bool SetRTPriorityRTKit(int prio
)
446 WARN("D-Bus not available\n");
450 dbus::ConnectionPtr conn
{dbus_bus_get(DBUS_BUS_SYSTEM
, &error
.get())};
453 WARN("D-Bus connection failed with %s: %s\n", error
->name
, error
->message
);
457 /* Don't stupidly exit if the connection dies while doing this. */
458 dbus_connection_set_exit_on_disconnect(conn
.get(), false);
460 auto limit_rttime
= [](DBusConnection
*c
) -> int
462 using ulonglong
= unsigned long long;
463 long long maxrttime
{rtkit_get_rttime_usec_max(c
)};
464 if(maxrttime
<= 0) return static_cast<int>(std::abs(maxrttime
));
465 const ulonglong umaxtime
{static_cast<ulonglong
>(maxrttime
)};
467 struct rlimit rlim
{};
468 if(getrlimit(RLIMIT_RTTIME
, &rlim
) != 0)
471 TRACE("RTTime max: %llu (hard: %llu, soft: %llu)\n", umaxtime
, ulonglong
{rlim
.rlim_max
},
472 ulonglong
{rlim
.rlim_cur
});
473 if(rlim
.rlim_max
> umaxtime
)
475 rlim
.rlim_max
= static_cast<rlim_t
>(umaxtime
);
476 rlim
.rlim_cur
= std::min(rlim
.rlim_cur
, rlim
.rlim_max
);
477 if(setrlimit(RLIMIT_RTTIME
, &rlim
) != 0)
484 int err
{rtkit_get_min_nice_level(conn
.get(), &nicemin
)};
488 ERR("Could not query RTKit: %s (%d)\n", std::strerror(err
), err
);
491 int rtmax
{rtkit_get_max_realtime_priority(conn
.get())};
492 TRACE("Maximum real-time priority: %d, minimum niceness: %d\n", rtmax
, nicemin
);
498 err
= limit_rttime(conn
.get());
500 WARN("Failed to set RLIMIT_RTTIME for RTKit: %s (%d)\n",
501 std::strerror(err
), err
);
504 /* Limit the maximum real-time priority to half. */
506 prio
= clampi(prio
, 1, rtmax
);
508 TRACE("Making real-time with priority %d (max: %d)\n", prio
, rtmax
);
509 err
= rtkit_make_realtime(conn
.get(), 0, prio
);
510 if(err
== 0) return true;
513 WARN("Failed to set real-time priority: %s (%d)\n", std::strerror(err
), err
);
515 /* Don't try to set the niceness for non-Linux systems. Standard POSIX has
516 * niceness as a per-process attribute, while the intent here is for the
517 * audio processing thread only to get a priority boost. Currently only
518 * Linux is known to have per-thread niceness.
523 TRACE("Making high priority with niceness %d\n", nicemin
);
524 err
= rtkit_make_high_priority(conn
.get(), 0, nicemin
);
525 if(err
== 0) return true;
528 WARN("Failed to set high priority: %s (%d)\n", std::strerror(err
), err
);
530 #endif /* __linux__ */
534 WARN("D-Bus not supported\n");
546 if(SetRTPriorityPthread(RTPrioLevel
))
548 if(SetRTPriorityRTKit(RTPrioLevel
))