18 #include "alfstream.h"
19 #include "alnumeric.h"
20 #include "aloptional.h"
28 /* Mixing thread piority level */
31 /* Allow reducing the process's RTTime limit for RTKit. */
32 bool AllowRTTimeLimit
{true};
39 const PathNamePair
&GetProcBinary()
41 static al::optional
<PathNamePair
> procbin
;
42 if(procbin
) return *procbin
;
44 auto fullpath
= al::vector
<WCHAR
>(256);
45 DWORD len
{GetModuleFileNameW(nullptr, fullpath
.data(), static_cast<DWORD
>(fullpath
.size()))};
46 while(len
== fullpath
.size())
48 fullpath
.resize(fullpath
.size() << 1);
49 len
= GetModuleFileNameW(nullptr, fullpath
.data(), static_cast<DWORD
>(fullpath
.size()));
53 ERR("Failed to get process name: error %lu\n", GetLastError());
54 procbin
= al::make_optional
<PathNamePair
>();
59 if(fullpath
.back() != 0)
60 fullpath
.push_back(0);
62 auto sep
= std::find(fullpath
.rbegin()+1, fullpath
.rend(), '\\');
63 sep
= std::find(fullpath
.rbegin()+1, sep
, '/');
64 if(sep
!= fullpath
.rend())
67 procbin
= al::make_optional
<PathNamePair
>(wstr_to_utf8(fullpath
.data()),
68 wstr_to_utf8(&*sep
+ 1));
71 procbin
= al::make_optional
<PathNamePair
>(std::string
{}, wstr_to_utf8(fullpath
.data()));
73 TRACE("Got binary: %s, %s\n", procbin
->path
.c_str(), procbin
->fname
.c_str());
79 void DirectorySearch(const char *path
, const char *ext
, al::vector
<std::string
> *const results
)
81 std::string pathstr
{path
};
84 TRACE("Searching %s\n", pathstr
.c_str());
86 std::wstring wpath
{utf8_to_wstr(pathstr
.c_str())};
87 WIN32_FIND_DATAW fdata
;
88 HANDLE hdl
{FindFirstFileW(wpath
.c_str(), &fdata
)};
89 if(hdl
== INVALID_HANDLE_VALUE
) return;
91 const auto base
= results
->size();
94 results
->emplace_back();
95 std::string
&str
= results
->back();
98 str
+= wstr_to_utf8(fdata
.cFileName
);
99 } while(FindNextFileW(hdl
, &fdata
));
102 const al::span
<std::string
> newlist
{results
->data()+base
, results
->size()-base
};
103 std::sort(newlist
.begin(), newlist
.end());
104 for(const auto &name
: newlist
)
105 TRACE(" got %s\n", name
.c_str());
110 al::vector
<std::string
> SearchDataFiles(const char *ext
, const char *subdir
)
112 auto is_slash
= [](int c
) noexcept
-> int { return (c
== '\\' || c
== '/'); };
114 static std::mutex search_lock
;
115 std::lock_guard
<std::mutex
> _
{search_lock
};
117 /* If the path is absolute, use it directly. */
118 al::vector
<std::string
> results
;
119 if(isalpha(subdir
[0]) && subdir
[1] == ':' && is_slash(subdir
[2]))
121 std::string path
{subdir
};
122 std::replace(path
.begin(), path
.end(), '/', '\\');
123 DirectorySearch(path
.c_str(), ext
, &results
);
126 if(subdir
[0] == '\\' && subdir
[1] == '\\' && subdir
[2] == '?' && subdir
[3] == '\\')
128 DirectorySearch(subdir
, ext
, &results
);
134 /* Search the app-local directory. */
135 if(auto localpath
= al::getenv(L
"ALSOFT_LOCAL_PATH"))
137 path
= wstr_to_utf8(localpath
->c_str());
138 if(is_slash(path
.back()))
141 else if(WCHAR
*cwdbuf
{_wgetcwd(nullptr, 0)})
143 path
= wstr_to_utf8(cwdbuf
);
144 if(is_slash(path
.back()))
150 std::replace(path
.begin(), path
.end(), '/', '\\');
151 DirectorySearch(path
.c_str(), ext
, &results
);
153 /* Search the local and global data dirs. */
154 static const int ids
[2]{ CSIDL_APPDATA
, CSIDL_COMMON_APPDATA
};
157 WCHAR buffer
[MAX_PATH
];
158 if(SHGetSpecialFolderPathW(nullptr, buffer
, id
, FALSE
) == FALSE
)
161 path
= wstr_to_utf8(buffer
);
162 if(!is_slash(path
.back()))
165 std::replace(path
.begin(), path
.end(), '/', '\\');
167 DirectorySearch(path
.c_str(), ext
, &results
);
173 void SetRTPriority(void)
177 if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL
))
178 ERR("Failed to set priority level for thread\n");
184 #include <sys/types.h>
188 #include <sys/sysctl.h>
191 #include <FindDirectory.h>
193 #ifdef HAVE_PROC_PIDPATH
196 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
201 #include <sys/time.h>
202 #include <sys/resource.h>
204 #include "dbus_wrap.h"
206 #ifndef RLIMIT_RTTIME
207 #define RLIMIT_RTTIME 15
211 const PathNamePair
&GetProcBinary()
213 static al::optional
<PathNamePair
> procbin
;
214 if(procbin
) return *procbin
;
216 al::vector
<char> pathname
;
219 int mib
[4] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1 };
220 if(sysctl(mib
, 4, nullptr, &pathlen
, nullptr, 0) == -1)
221 WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno
));
224 pathname
.resize(pathlen
+ 1);
225 sysctl(mib
, 4, pathname
.data(), &pathlen
, nullptr, 0);
226 pathname
.resize(pathlen
);
229 #ifdef HAVE_PROC_PIDPATH
232 char procpath
[PROC_PIDPATHINFO_MAXSIZE
]{};
233 const pid_t pid
{getpid()};
234 if(proc_pidpath(pid
, procpath
, sizeof(procpath
)) < 1)
235 ERR("proc_pidpath(%d, ...) failed: %s\n", pid
, strerror(errno
));
237 pathname
.insert(pathname
.end(), procpath
, procpath
+strlen(procpath
));
243 char procpath
[PATH_MAX
];
244 if(find_path(B_APP_IMAGE_SYMBOL
, B_FIND_PATH_IMAGE_PATH
, NULL
, procpath
, sizeof(procpath
)) == B_OK
)
245 pathname
.insert(pathname
.end(), procpath
, procpath
+strlen(procpath
));
251 static const char SelfLinkNames
[][32]{
258 pathname
.resize(256);
260 const char *selfname
{};
262 for(const char *name
: SelfLinkNames
)
265 len
= readlink(selfname
, pathname
.data(), pathname
.size());
266 if(len
>= 0 || errno
!= ENOENT
) break;
269 while(len
> 0 && static_cast<size_t>(len
) == pathname
.size())
271 pathname
.resize(pathname
.size() << 1);
272 len
= readlink(selfname
, pathname
.data(), pathname
.size());
276 WARN("Failed to readlink %s: %s\n", selfname
, strerror(errno
));
280 pathname
.resize(static_cast<size_t>(len
));
283 while(!pathname
.empty() && pathname
.back() == 0)
286 auto sep
= std::find(pathname
.crbegin(), pathname
.crend(), '/');
287 if(sep
!= pathname
.crend())
288 procbin
= al::make_optional
<PathNamePair
>(std::string(pathname
.cbegin(), sep
.base()-1),
289 std::string(sep
.base(), pathname
.cend()));
291 procbin
= al::make_optional
<PathNamePair
>(std::string
{},
292 std::string(pathname
.cbegin(), pathname
.cend()));
294 TRACE("Got binary: \"%s\", \"%s\"\n", procbin
->path
.c_str(), procbin
->fname
.c_str());
300 void DirectorySearch(const char *path
, const char *ext
, al::vector
<std::string
> *const results
)
302 TRACE("Searching %s for *%s\n", path
, ext
);
303 DIR *dir
{opendir(path
)};
306 const auto base
= results
->size();
307 const size_t extlen
{strlen(ext
)};
309 while(struct dirent
*dirent
{readdir(dir
)})
311 if(strcmp(dirent
->d_name
, ".") == 0 || strcmp(dirent
->d_name
, "..") == 0)
314 const size_t len
{strlen(dirent
->d_name
)};
315 if(len
<= extlen
) continue;
316 if(al::strcasecmp(dirent
->d_name
+len
-extlen
, ext
) != 0)
319 results
->emplace_back();
320 std::string
&str
= results
->back();
322 if(str
.back() != '/')
324 str
+= dirent
->d_name
;
328 const al::span
<std::string
> newlist
{results
->data()+base
, results
->size()-base
};
329 std::sort(newlist
.begin(), newlist
.end());
330 for(const auto &name
: newlist
)
331 TRACE(" got %s\n", name
.c_str());
336 al::vector
<std::string
> SearchDataFiles(const char *ext
, const char *subdir
)
338 static std::mutex search_lock
;
339 std::lock_guard
<std::mutex
> _
{search_lock
};
341 al::vector
<std::string
> results
;
344 DirectorySearch(subdir
, ext
, &results
);
348 /* Search the app-local directory. */
349 if(auto localpath
= al::getenv("ALSOFT_LOCAL_PATH"))
350 DirectorySearch(localpath
->c_str(), ext
, &results
);
353 al::vector
<char> cwdbuf(256);
354 while(!getcwd(cwdbuf
.data(), cwdbuf
.size()))
361 cwdbuf
.resize(cwdbuf
.size() << 1);
364 DirectorySearch(".", ext
, &results
);
367 DirectorySearch(cwdbuf
.data(), ext
, &results
);
372 // Search local data dir
373 if(auto datapath
= al::getenv("XDG_DATA_HOME"))
375 std::string
&path
= *datapath
;
376 if(path
.back() != '/')
379 DirectorySearch(path
.c_str(), ext
, &results
);
381 else if(auto homepath
= al::getenv("HOME"))
383 std::string
&path
= *homepath
;
384 if(path
.back() == '/')
386 path
+= "/.local/share/";
388 DirectorySearch(path
.c_str(), ext
, &results
);
391 // Search global data dirs
392 std::string datadirs
{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
395 while(curpos
< datadirs
.size())
397 size_t nextpos
{datadirs
.find(':', curpos
)};
399 std::string path
{(nextpos
!= std::string::npos
) ?
400 datadirs
.substr(curpos
, nextpos
++ - curpos
) : datadirs
.substr(curpos
)};
403 if(path
.empty()) continue;
404 if(path
.back() != '/')
408 DirectorySearch(path
.c_str(), ext
, &results
);
416 bool SetRTPriorityPthread(int prio
)
419 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
420 /* Get the min and max priority for SCHED_RR. Limit the max priority to
421 * half, for now, to ensure the thread can't take the highest priority and
424 int rtmin
{sched_get_priority_min(SCHED_RR
)};
425 int rtmax
{sched_get_priority_max(SCHED_RR
)};
426 rtmax
= (rtmax
-rtmin
)/2 + rtmin
;
428 struct sched_param param
{};
429 param
.sched_priority
= clampi(prio
, rtmin
, rtmax
);
430 #ifdef SCHED_RESET_ON_FORK
431 err
= pthread_setschedparam(pthread_self(), SCHED_RR
|SCHED_RESET_ON_FORK
, ¶m
);
434 err
= pthread_setschedparam(pthread_self(), SCHED_RR
, ¶m
);
435 if(err
== 0) return true;
441 WARN("pthread_setschedparam failed: %s (%d)\n", std::strerror(err
), err
);
445 bool SetRTPriorityRTKit(int prio
)
450 WARN("D-Bus not available\n");
454 dbus::ConnectionPtr conn
{dbus_bus_get(DBUS_BUS_SYSTEM
, &error
.get())};
457 WARN("D-Bus connection failed with %s: %s\n", error
->name
, error
->message
);
461 /* Don't stupidly exit if the connection dies while doing this. */
462 dbus_connection_set_exit_on_disconnect(conn
.get(), false);
464 auto limit_rttime
= [](DBusConnection
*c
) -> int
466 using ulonglong
= unsigned long long;
467 long long maxrttime
{rtkit_get_rttime_usec_max(c
)};
468 if(maxrttime
<= 0) return static_cast<int>(std::abs(maxrttime
));
469 const ulonglong umaxtime
{static_cast<ulonglong
>(maxrttime
)};
471 struct rlimit rlim
{};
472 if(getrlimit(RLIMIT_RTTIME
, &rlim
) != 0)
475 TRACE("RTTime max: %llu (hard: %llu, soft: %llu)\n", umaxtime
, ulonglong
{rlim
.rlim_max
},
476 ulonglong
{rlim
.rlim_cur
});
477 if(rlim
.rlim_max
> umaxtime
)
479 rlim
.rlim_max
= static_cast<rlim_t
>(umaxtime
);
480 rlim
.rlim_cur
= std::min(rlim
.rlim_cur
, rlim
.rlim_max
);
481 if(setrlimit(RLIMIT_RTTIME
, &rlim
) != 0)
488 int err
{rtkit_get_min_nice_level(conn
.get(), &nicemin
)};
492 ERR("Could not query RTKit: %s (%d)\n", std::strerror(err
), err
);
495 int rtmax
{rtkit_get_max_realtime_priority(conn
.get())};
496 TRACE("Maximum real-time priority: %d, minimum niceness: %d\n", rtmax
, nicemin
);
502 err
= limit_rttime(conn
.get());
504 WARN("Failed to set RLIMIT_RTTIME for RTKit: %s (%d)\n",
505 std::strerror(err
), err
);
508 /* Limit the maximum real-time priority to half. */
510 prio
= clampi(prio
, 1, rtmax
);
512 TRACE("Making real-time with priority %d (max: %d)\n", prio
, rtmax
);
513 err
= rtkit_make_realtime(conn
.get(), 0, prio
);
514 if(err
== 0) return true;
517 WARN("Failed to set real-time priority: %s (%d)\n", std::strerror(err
), err
);
519 /* Don't try to set the niceness for non-Linux systems. Standard POSIX has
520 * niceness as a per-process attribute, while the intent here is for the
521 * audio processing thread only to get a priority boost. Currently only
522 * Linux is known to have per-thread niceness.
527 TRACE("Making high priority with niceness %d\n", nicemin
);
528 err
= rtkit_make_high_priority(conn
.get(), 0, nicemin
);
529 if(err
== 0) return true;
532 WARN("Failed to set high priority: %s (%d)\n", std::strerror(err
), err
);
534 #endif /* __linux__ */
539 WARN("D-Bus not supported\n");
551 if(SetRTPriorityPthread(RTPrioLevel
))
553 if(SetRTPriorityRTKit(RTPrioLevel
))