game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
frame_metrics.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// frame_metrics.cpp
4// ==============================================================================
5// Implementation of frame metrics collection from Gamescope and MangoHud
6// ==============================================================================
7
8#include "frame_metrics.h"
10#include "logger.h"
11
12#include <algorithm>
13#include <cstring>
14#include <filesystem>
15#include <fstream>
16#include <limits>
17#include <regex>
18#include <sstream>
19
20#ifdef PLATFORM_LINUX
21#include <dirent.h>
22#include <sys/ipc.h>
23#include <sys/msg.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26#include <unistd.h>
27#endif
28
29// ==============================================================================
30// Gamescope MangoApp Message Structure
31// ==============================================================================
32// These structures match the MangoApp protocol used by Gamescope
33// See: https://github.com/ValveSoftware/gamescope
34
35#ifdef PLATFORM_LINUX
36
37// __attribute__((packed)) is GCC/Clang's native packed-layout directive and
38// matches what gamescope/MangoHud upstream use for these wire-format structs
39// (see ValveSoftware/gamescope src/mangoapp.h). Per-struct application is
40// preferable to a #pragma pack(push)/pop pair: clangd's index doesn't track
41// pragma state through macro-conditional regions and emits spurious
42// "unterminated #pragma pack" diagnostics even when the matching pop is
43// present in the same file. Per-struct attributes are immune to that.
44
45struct __attribute__((packed)) mangoapp_msg_header
46{
47 long msg_type; // Message queue type (always 1)
48 uint32_t version; // Protocol version
49};
50
51// Version 1 message structure
52struct __attribute__((packed)) mangoapp_msg_v1
53{
54 mangoapp_msg_header hdr;
55 uint32_t pid;
56 uint64_t app_frametime_ns; // Application frame time in nanoseconds
57 uint8_t fsrUpscale; // FSR upscaling factor
58 uint8_t fsrSharpness; // FSR sharpness setting
59 uint64_t visible_frametime_ns; // Visible frame time after compositor
60 uint64_t latency_ns; // Input-to-display latency
61 uint32_t outputWidth; // Output resolution width
62 uint32_t outputHeight; // Output resolution height
63 uint16_t displayRefresh; // Display refresh rate (Hz)
64 // Bitfields
65 uint8_t flags; // bAppWantsHDR (bit 0), bSteamFocused (bit 1)
66 char engineName[40]; // Game engine name
67};
68
69// ==============================================================================
70// GamescopeMetricsReader Implementation
71// ==============================================================================
72
73GamescopeMetricsReader::GamescopeMetricsReader()
74{
75 frametimeBuffer_.resize(SAMPLE_BUFFER_SIZE, 0.0);
76}
77
78GamescopeMetricsReader::~GamescopeMetricsReader()
79{
80 // Explicitly qualify the call so it's clear we mean THIS class's
81 // override, not a virtual dispatch (which is bypassed during
82 // destruction anyway per [class.cdtor]/4 — calls land on the static
83 // type's version). Silences clang-analyzer-optin.cplusplus.VirtualCall.
84 GamescopeMetricsReader::stop();
85}
86
87bool GamescopeMetricsReader::isAvailable() const
88{
89 // Check if gamescope mangoapp message queue exists
90 // Key is generated the same way gamescope does it
91 key_t key = ftok("mangoapp", 65);
92 if (key == -1)
93 return false;
94
95 int msgid = msgget(key, 0);
96 return msgid != -1;
97}
98
99bool GamescopeMetricsReader::connectToMessageQueue()
100{
101 // Generate key the same way gamescope does
102 key_t key = ftok("mangoapp", 65);
103 if (key == -1)
104 {
105 Logger::debug("[FrameMetrics] Failed to generate message queue key");
106 return false;
107 }
108
109 // Try to get existing message queue (don't create)
110 msgQueueId_ = msgget(key, 0666);
111 if (msgQueueId_ == -1)
112 {
113 Logger::debug("[FrameMetrics] Gamescope message queue not found");
114 return false;
115 }
116
117 return true;
118}
119
120bool GamescopeMetricsReader::start(int pid)
121{
122 if (isActive_)
123 stop();
124
125 targetPid_ = pid;
126
127 if (!connectToMessageQueue())
128 {
129 return false;
130 }
131
132 // Reset state
133 {
134 std::lock_guard<std::mutex> lock(metricsMutex_);
135 currentMetrics_ = FrameMetrics();
136 currentMetrics_.source = "gamescope";
137 bufferIndex_ = 0;
138 bufferCount_ = 0;
139 std::fill(frametimeBuffer_.begin(), frametimeBuffer_.end(), 0.0);
140 }
141
142 shouldStop_ = false;
143 isActive_ = true;
144 readerThread_ = std::thread(&GamescopeMetricsReader::readerThread, this);
145
146 return true;
147}
148
149void GamescopeMetricsReader::stop()
150{
151 shouldStop_ = true;
152 if (readerThread_.joinable())
153 {
154 readerThread_.join();
155 }
156 isActive_ = false;
157 msgQueueId_ = -1;
158}
159
160bool GamescopeMetricsReader::isActive() const
161{
162 return isActive_;
163}
164
165FrameMetrics GamescopeMetricsReader::getMetrics() const
166{
167 std::lock_guard<std::mutex> lock(metricsMutex_);
168 return currentMetrics_;
169}
170
171void GamescopeMetricsReader::readerThread()
172{
173 mangoapp_msg_v1 msg;
174
175 while (!shouldStop_)
176 {
177 // Non-blocking receive with small timeout
178 ssize_t received = msgrcv(msgQueueId_, &msg, sizeof(msg) - sizeof(long), 1, IPC_NOWAIT);
179
180 if (received > 0)
181 {
182 // Process the message
183 double frametime_ns = static_cast<double>(msg.app_frametime_ns);
184 double frametime_ms = frametime_ns / 1000000.0;
185 double fps = (frametime_ms > 0) ? (1000.0 / frametime_ms) : 0.0;
186
187 double latency_ms = static_cast<double>(msg.latency_ns) / 1000000.0;
188
189 {
190 std::lock_guard<std::mutex> lock(metricsMutex_);
191
192 currentMetrics_.fps = fps;
193 currentMetrics_.frametime_ms = frametime_ms;
194 currentMetrics_.latency_ms = latency_ms;
195 currentMetrics_.display_refresh = msg.displayRefresh;
196 currentMetrics_.output_width = msg.outputWidth;
197 currentMetrics_.output_height = msg.outputHeight;
198 currentMetrics_.timestamp = std::chrono::steady_clock::now();
199 currentMetrics_.sample_count++;
200
201 // Extract engine name (null-terminated string)
202 currentMetrics_.engine_name =
203 std::string(msg.engineName, strnlen(msg.engineName, sizeof(msg.engineName)));
204
205 // Add to circular buffer for percentile calculation
206 frametimeBuffer_[bufferIndex_] = frametime_ms;
207 bufferIndex_ = (bufferIndex_ + 1) % SAMPLE_BUFFER_SIZE;
208 if (bufferCount_ < SAMPLE_BUFFER_SIZE)
209 bufferCount_++;
210
211 // Update percentiles every 60 samples (~1 second at 60fps)
212 if (currentMetrics_.sample_count % 60 == 0)
213 {
214 updatePercentiles();
215 }
216
217 // Update average, min, and max
218 double sum = 0.0;
219 double minFt = std::numeric_limits<double>::max();
220 double maxFt = 0.0;
221 for (size_t i = 0; i < bufferCount_; i++)
222 {
223 sum += frametimeBuffer_[i];
224 if (frametimeBuffer_[i] < minFt)
225 minFt = frametimeBuffer_[i];
226 if (frametimeBuffer_[i] > maxFt)
227 maxFt = frametimeBuffer_[i];
228 }
229 currentMetrics_.frametime_avg_ms = sum / static_cast<double>(bufferCount_);
230 currentMetrics_.fps_avg = (currentMetrics_.frametime_avg_ms > 0)
231 ? (1000.0 / currentMetrics_.frametime_avg_ms)
232 : 0.0;
233 currentMetrics_.frametime_min_ms =
234 minFt < std::numeric_limits<double>::max() ? minFt : 0.0;
235 currentMetrics_.frametime_max_ms = maxFt;
236 currentMetrics_.fps_min = (maxFt > 0) ? (1000.0 / maxFt) : 0.0;
237 currentMetrics_.fps_max = (minFt > 0 && minFt < std::numeric_limits<double>::max())
238 ? (1000.0 / minFt)
239 : 0.0;
240 }
241 }
242 else
243 {
244 // No message available, sleep briefly
245 std::this_thread::sleep_for(std::chrono::milliseconds(5));
246 }
247 }
248}
249
250void GamescopeMetricsReader::updatePercentiles()
251{
252 if (bufferCount_ < 10)
253 return;
254
255 // Copy and sort for percentile calculation
256 std::vector<double> sorted(frametimeBuffer_.begin(),
257 frametimeBuffer_.begin() +
258 static_cast<std::ptrdiff_t>(bufferCount_));
259 std::sort(sorted.begin(), sorted.end());
260
261 // 99th percentile frametime -> 1% low FPS
262 size_t idx99 = static_cast<size_t>(static_cast<double>(bufferCount_) * 0.99);
263 if (idx99 >= bufferCount_)
264 idx99 = bufferCount_ - 1;
265 double p99_frametime = sorted[idx99];
266 currentMetrics_.fps_1_low = (p99_frametime > 0) ? (1000.0 / p99_frametime) : 0.0;
267
268 // 99.9th percentile frametime -> 0.1% low FPS
269 size_t idx999 = static_cast<size_t>(static_cast<double>(bufferCount_) * 0.999);
270 if (idx999 >= bufferCount_)
271 idx999 = bufferCount_ - 1;
272 double p999_frametime = sorted[idx999];
273 currentMetrics_.fps_0_1_low = (p999_frametime > 0) ? (1000.0 / p999_frametime) : 0.0;
274}
275
276#endif // PLATFORM_LINUX
277
278// ==============================================================================
279// MangoHudLogReader Implementation
280// ==============================================================================
281
283{
284 frametimeBuffer_.resize(SAMPLE_BUFFER_SIZE, 0.0);
285 logDirectory_ = getDefaultLogDirectory();
286}
287
289{
290 // See GamescopeMetricsReader::~GamescopeMetricsReader for the
291 // rationale on the explicit qualification.
293}
294
296{
297 const char* homeEnv = std::getenv("HOME");
298
299 // Default mode: isolate per-game logs under $XDG_STATE_HOME so they don't
300 // pollute $HOME (the user's goverlay-managed output_folder is often $HOME
301 // itself). Per the XDG Base Directory Specification:
302 // "$XDG_STATE_HOME defines the base directory relative to which
303 // user-specific state files should be stored."
304 // "It may contain: actions history (logs, history, recently used
305 // files, …)"
306 // "If $XDG_STATE_HOME is either not set or empty, a default equal to
307 // $HOME/.local/state should be used."
308 // Logs are explicitly listed as appropriate $XDG_STATE_HOME content.
310 {
311 const char* stateHome = std::getenv("XDG_STATE_HOME");
312 std::string base;
313 if (stateHome && *stateHome != '\0')
314 {
315 base = stateHome;
316 }
317 else if (homeEnv)
318 {
319 base = std::string(homeEnv) + "/.local/state";
320 }
321 if (!base.empty())
322 {
323 return base + "/gamelauncher/mangohud-logs";
324 }
325 // No HOME and no XDG_STATE_HOME — fall through to legacy logic below.
326 }
327
328 // Compatibility mode: read output_folder from user's MangoHud config so
329 // goverlay's "Logs" analysis tab finds the same files.
330 std::string configPath =
331 std::string(homeEnv ? homeEnv : "") + "/.config/MangoHud/MangoHud.conf";
332 std::ifstream configFile(configPath);
333 if (configFile.is_open())
334 {
335 std::string line;
336 while (std::getline(configFile, line))
337 {
338 // Skip comments and empty lines
339 if (line.empty() || line[0] == '#')
340 continue;
341
342 // Look for output_folder= (could be at start or after other content on same line)
343 size_t pos = line.find("output_folder=");
344 if (pos != std::string::npos)
345 {
346 std::string folder = line.substr(pos + 14);
347 // Trim whitespace and trailing newline/carriage return
348 size_t start = folder.find_first_not_of(" \t");
349 size_t end = folder.find_last_not_of(" \t\r\n");
350 if (start != std::string::npos && end != std::string::npos && end >= start)
351 {
352 folder = folder.substr(start, end - start + 1);
353 if (!folder.empty())
354 {
355 return folder;
356 }
357 }
358 }
359 }
360 }
361
362 // Last-resort fallback when neither XDG_STATE_HOME nor a user config is
363 // available — use $XDG_RUNTIME_DIR (per spec, runtime data; cleaned at
364 // logout) and finally the system temp directory.
365 const char* runtimeDir = std::getenv("XDG_RUNTIME_DIR");
366 if (runtimeDir && std::filesystem::is_directory(runtimeDir))
367 {
368 return std::string(runtimeDir) + "/gamelauncher_mangologs";
369 }
370 return (std::filesystem::temp_directory_path() / "gamelauncher_mangologs").string();
371}
372
374{
375 // MangoHud config for logging
376 // output_folder: where to write logs (must be set for logging to work)
377 // autostart_log: start logging N seconds after launch (e.g., 3 = start after 3 seconds)
378 // log_duration: 0 = unlimited duration
379 // log_interval: milliseconds between log entries (0 = default ~100ms)
380 // Note: The config is comma-separated, key=value format
381 std::string logDir = getDefaultLogDirectory();
382 // MangoHud parses MANGOHUD_CONFIG as comma-separated key=value pairs.
383 // A comma in the directory path would be misinterpreted as a separator
384 // and inject unexpected config options. Reject and fall back to /tmp.
385 if (logDir.find(',') != std::string::npos)
386 {
387 logDir = "/tmp/gamelauncher_mangologs";
388 }
389 return "output_folder=" + logDir + ",autostart_log=3,log_duration=0,log_interval=100";
390}
391
392std::string MangoHudLogReader::buildLaunchConfigFile(const std::string& gameId,
393 const std::string& userConfigFile)
394{
395 namespace fs = std::filesystem;
396
397 std::string logDir = getDefaultLogDirectory();
398 if (logDir.empty())
399 return {};
400
401 std::error_code ec;
402 fs::create_directories(logDir, ec);
403 if (ec)
404 {
405 Logger::warn("[FrameMetrics] Failed to create log dir {}: {}", logDir, ec.message());
406 return {};
407 }
408
409 // Sanitise gameId for filesystem use: keep alnum/dash/underscore, others -> _
410 std::string safeId;
411 safeId.reserve(gameId.size());
412 for (char c : gameId)
413 {
414 unsigned char uc = static_cast<unsigned char>(c);
415 if (std::isalnum(uc) || c == '-' || c == '_')
416 safeId.push_back(c);
417 else
418 safeId.push_back('_');
419 }
420 if (safeId.empty())
421 safeId = "default";
422
423 fs::path outPath = fs::path(logDir) / ("mangohud-launch-" + safeId + ".conf");
424
425 std::ofstream out(outPath, std::ios::trunc);
426 if (!out.is_open())
427 {
428 Logger::warn("[FrameMetrics] Failed to open MangoHud launch config {} for writing",
429 outPath.string());
430 return {};
431 }
432
433 // 1a. Copy the user's global MangoHud config (~/.config/MangoHud/MangoHud.conf)
434 // so visual preferences they've set via Goverlay (position, font_size,
435 // fps_color_change, toggle_hud bindings, blacklist, etc.) carry over
436 // to launches via this launcher. Without this, MANGOHUD_CONFIGFILE
437 // causes MangoHud's parseConfigFile to skip enumerate_config_files
438 // entirely (per upstream src/config.cpp), so the user's overlay would
439 // fall back to MangoHud's hard-coded defaults.
440 const char* homeEnv = std::getenv("HOME");
441 if (homeEnv)
442 {
443 fs::path globalCfg = fs::path(homeEnv) / ".config" / "MangoHud" / "MangoHud.conf";
444 if (fs::exists(globalCfg))
445 {
446 std::ifstream in(globalCfg);
447 if (in.is_open())
448 {
449 out << "# --- merged from user global config: " << globalCfg.string() << " ---\n";
450 out << in.rdbuf();
451 out << '\n';
452 }
453 else
454 {
455 Logger::warn("[FrameMetrics] Could not read global MangoHud config {}",
456 globalCfg.string());
457 }
458 }
459 }
460
461 // 1b. Copy any per-game override the user wired through runnerConfig.
462 // MangoHud's parseConfigLine writes into a single options map, so any
463 // keys we set after this block win on duplicates.
464 if (!userConfigFile.empty() && fs::exists(userConfigFile))
465 {
466 std::ifstream in(userConfigFile);
467 if (in.is_open())
468 {
469 out << "# --- merged from per-game config: " << userConfigFile << " ---\n";
470 out << in.rdbuf();
471 out << '\n';
472 }
473 else
474 {
475 Logger::warn("[FrameMetrics] Could not read user MangoHud config {}", userConfigFile);
476 }
477 }
478
479 // 2. Append our logging settings. log_duration=0 means "log forever" per
480 // MangoHud's src/logging.cpp: `if(log_duration && elapsedLog >= ...)`.
481 //
482 // Note: do NOT set no_display=1 here. MangoHud's src/overlay.cpp gates
483 // the autostart_log trigger inside update_hud_info_with_frametime, which
484 // is only called when `!no_display || logger->is_active()`. With
485 // no_display=1 and the logger not yet active, that function is skipped,
486 // autostart_log never fires, and the logger never starts — a permanent
487 // chicken-and-egg deadlock. Users who want to hide the overlay can
488 // toggle it at runtime with MangoHud's default F12 binding.
489 out << "# --- gamelauncher logging block (overrides any earlier values) ---\n";
490 out << "output_folder=" << logDir << "\n";
491 out << "autostart_log=3\n";
492 out << "log_duration=0\n";
493 out << "log_interval=100\n";
494
495 out.close();
496 if (out.fail())
497 {
498 Logger::warn("[FrameMetrics] Write failed for MangoHud launch config {}", outPath.string());
499 return {};
500 }
501
502 return outPath.string();
503}
504
505void MangoHudLogReader::setLogDirectory(const std::string& path)
506{
507 std::lock_guard<std::mutex> lock(metricsMutex_);
508 logDirectory_ = path;
509}
510
512{
513 // Check if mangohud is installed
514#ifdef PLATFORM_LINUX
515 return access("/usr/bin/mangohud", X_OK) == 0 || access("/usr/local/bin/mangohud", X_OK) == 0;
516#else
517 return false;
518#endif
519}
520
521bool MangoHudLogReader::findLogFile()
522{
523#ifdef PLATFORM_LINUX
524 // Take a local copy under lock to avoid racing with setLogDirectory()
525 std::string logDir;
526 {
527 std::lock_guard<std::mutex> lock(metricsMutex_);
528 logDir = logDirectory_;
529 }
530
531 // Create log directory if it doesn't exist
532 mkdir(logDir.c_str(), 0700);
533
534 // Find the most recent .csv file in the log directory that:
535 // 1. Is not a _summary.csv file (MangoHud creates these when logging stops)
536 // 2. Does NOT have a corresponding _summary.csv file (indicating active session)
537 // 3. Is the newest such file
538 DIR* dir = opendir(logDir.c_str());
539 if (!dir)
540 {
541 return false;
542 }
543
544 std::string newestFile;
545 time_t newestTime = 0;
546
547 struct dirent* entry;
548 while ((entry = readdir(dir)) != nullptr)
549 {
550 std::string filename = entry->d_name;
551 // Skip if not a .csv file
552 if (filename.size() <= 4 || filename.substr(filename.size() - 4) != ".csv")
553 continue;
554
555 // Skip MangoHud summary files - they don't contain realtime data
556 if (filename.find("_summary.csv") != std::string::npos)
557 continue;
558
559 std::string fullPath = logDir + "/" + filename;
560
561 // Check if this log file has a corresponding _summary.csv file
562 // If it does, the logging session for this file has ended
563 std::string summaryPath = fullPath.substr(0, fullPath.size() - 4) + "_summary.csv";
564 struct stat summaryStat;
565 if (stat(summaryPath.c_str(), &summaryStat) == 0)
566 {
567 // Summary file exists - this log is from a completed session, skip it
568 continue;
569 }
570
571 struct stat st;
572 if (stat(fullPath.c_str(), &st) == 0)
573 {
574 if (st.st_mtime > newestTime)
575 {
576 newestTime = st.st_mtime;
577 newestFile = fullPath;
578 }
579 }
580 }
581 closedir(dir);
582
583 if (!newestFile.empty())
584 {
585 currentLogFile_ = newestFile;
586 return true;
587 }
588#endif
589 return false;
590}
591
592bool MangoHudLogReader::parseHeader(const std::string& line)
593{
594 // Parse CSV header to find column indices
595 // MangoHud logs have a 2-line header:
596 // Line 1: os,cpu,gpu,ram,kernel,driver,cpuscheduler (system info header)
597 // Line 2: <system info values>
598 // Line 3: fps,frametime,cpu_load,... (actual data header)
599 // Line 4+: data
600 //
601 // We need to find the line that starts with "fps" to get the data header
602
603 // Check if this looks like the data header (contains "fps" as first column)
604 if (line.substr(0, 4) != "fps," && line.substr(0, 3) != "fps")
605 {
606 // Not the data header, skip it
607 return false;
608 }
609
610 fpsColumn_ = -1;
611 frametimeColumn_ = -1;
612
613 std::istringstream iss(line);
614 std::string token;
615 int col = 0;
616
617 while (std::getline(iss, token, ','))
618 {
619 // Trim whitespace
620 size_t start = token.find_first_not_of(" \t\r\n");
621 size_t end = token.find_last_not_of(" \t\r\n");
622 if (start != std::string::npos && end != std::string::npos)
623 {
624 token = token.substr(start, end - start + 1);
625 }
626
627 if (token == "fps")
628 fpsColumn_ = col;
629 else if (token == "frametime")
630 frametimeColumn_ = col;
631
632 col++;
633 }
634
635 return fpsColumn_ >= 0 || frametimeColumn_ >= 0;
636}
637
638bool MangoHudLogReader::parseLogLine(const std::string& line)
639{
640 if (fpsColumn_ < 0 && frametimeColumn_ < 0)
641 return false;
642
643 std::istringstream iss(line);
644 std::string token;
645 int col = 0;
646 double fps = 0.0;
647 double frametime = 0.0;
648
649 while (std::getline(iss, token, ','))
650 {
651 if (col == fpsColumn_)
652 {
653 try
654 {
655 fps = std::stod(token);
656 }
657 catch (...)
658 {
659 }
660 }
661 else if (col == frametimeColumn_)
662 {
663 try
664 {
665 frametime = std::stod(token);
666 }
667 catch (...)
668 {
669 }
670 }
671 col++;
672 }
673
674 // If we only have FPS, calculate frametime
675 if (frametime <= 0 && fps > 0)
676 {
677 frametime = 1000.0 / fps;
678 }
679 // If we only have frametime, calculate FPS
680 if (fps <= 0 && frametime > 0)
681 {
682 fps = 1000.0 / frametime;
683 }
684
685 if (fps > 0 || frametime > 0)
686 {
687 std::lock_guard<std::mutex> lock(metricsMutex_);
688
689 currentMetrics_.fps = fps;
690 currentMetrics_.frametime_ms = frametime;
691 currentMetrics_.timestamp = std::chrono::steady_clock::now();
692 currentMetrics_.sample_count++;
693
694 // Add to circular buffer for percentile calculations
695 frametimeBuffer_[bufferIndex_] = frametime;
696 bufferIndex_ = (bufferIndex_ + 1) % SAMPLE_BUFFER_SIZE;
697 if (bufferCount_ < SAMPLE_BUFFER_SIZE)
698 bufferCount_++;
699
700 // Maintain frametime history for graph display (subsample to ~10Hz for UI)
701 // Only add every 10th sample to keep history manageable
702 if (currentMetrics_.sample_count % 10 == 0)
703 {
704 if (currentMetrics_.frametimeHistory.size() >= FrameMetrics::GRAPH_HISTORY_SIZE)
705 {
706 currentMetrics_.frametimeHistory.erase(currentMetrics_.frametimeHistory.begin());
707 }
708 currentMetrics_.frametimeHistory.push_back(frametime);
709 }
710
711 // Update percentiles periodically
712 if (currentMetrics_.sample_count % 60 == 0)
713 {
714 updatePercentiles();
715 }
716
717 // Update average and min/max
718 double sum = 0.0;
719 double minFt = std::numeric_limits<double>::max();
720 double maxFt = 0.0;
721 for (size_t i = 0; i < bufferCount_; i++)
722 {
723 sum += frametimeBuffer_[i];
724 if (frametimeBuffer_[i] < minFt)
725 minFt = frametimeBuffer_[i];
726 if (frametimeBuffer_[i] > maxFt)
727 maxFt = frametimeBuffer_[i];
728 }
729 currentMetrics_.frametime_avg_ms = sum / static_cast<double>(bufferCount_);
730 currentMetrics_.fps_avg = (currentMetrics_.frametime_avg_ms > 0)
731 ? (1000.0 / currentMetrics_.frametime_avg_ms)
732 : 0.0;
733
734 // Store min/max (convert frametime to FPS for min/max FPS)
735 currentMetrics_.frametime_min_ms = minFt;
736 currentMetrics_.frametime_max_ms = maxFt;
737 currentMetrics_.fps_min = (maxFt > 0) ? (1000.0 / maxFt) : 0.0; // Max frametime = min FPS
738 currentMetrics_.fps_max = (minFt > 0) ? (1000.0 / minFt) : 0.0; // Min frametime = max FPS
739
740 return true;
741 }
742
743 return false;
744}
745
746void MangoHudLogReader::updatePercentiles()
747{
748 if (bufferCount_ < 10)
749 return;
750
751 std::vector<double> sorted(frametimeBuffer_.begin(),
752 frametimeBuffer_.begin() +
753 static_cast<std::ptrdiff_t>(bufferCount_));
754 std::sort(sorted.begin(), sorted.end());
755
756 size_t idx99 = static_cast<size_t>(static_cast<double>(bufferCount_) * 0.99);
757 if (idx99 >= bufferCount_)
758 idx99 = bufferCount_ - 1;
759 double p99_frametime = sorted[idx99];
760 currentMetrics_.fps_1_low = (p99_frametime > 0) ? (1000.0 / p99_frametime) : 0.0;
761
762 size_t idx999 = static_cast<size_t>(static_cast<double>(bufferCount_) * 0.999);
763 if (idx999 >= bufferCount_)
764 idx999 = bufferCount_ - 1;
765 double p999_frametime = sorted[idx999];
766 currentMetrics_.fps_0_1_low = (p999_frametime > 0) ? (1000.0 / p999_frametime) : 0.0;
767}
768
770{
771 if (isActive_)
772 stop();
773
774 targetPid_ = pid;
775
776 // Reset state
777 {
778 std::lock_guard<std::mutex> lock(metricsMutex_);
779 currentMetrics_ = FrameMetrics();
780 currentMetrics_.source = "mangohud";
781 bufferIndex_ = 0;
782 bufferCount_ = 0;
783 fpsColumn_ = -1;
784 frametimeColumn_ = -1;
785 lastReadPos_ = 0;
786 currentLogFile_.clear();
787 std::fill(frametimeBuffer_.begin(), frametimeBuffer_.end(), 0.0);
788 }
789
790 shouldStop_ = false;
791 isActive_ = true;
792 readerThread_ = std::thread(&MangoHudLogReader::readerThread, this);
793
794 return true;
795}
796
798{
799 shouldStop_ = true;
800 if (readerThread_.joinable())
801 {
802 readerThread_.join();
803 }
804 isActive_ = false;
805}
806
808{
809 return isActive_;
810}
811
813{
814 std::lock_guard<std::mutex> lock(metricsMutex_);
815 return currentMetrics_;
816}
817
818void MangoHudLogReader::readerThread()
819{
820 // Wait a bit for MangoHud to start logging
821 std::this_thread::sleep_for(std::chrono::seconds(2));
822
823 {
824 std::lock_guard<std::mutex> lock(metricsMutex_);
825 Logger::debug("[FrameMetrics] MangoHud reader thread started, log dir: {}", logDirectory_);
826 }
827
828 while (!shouldStop_)
829 {
830 // Try to find log file if we don't have one
831 if (currentLogFile_.empty())
832 {
833 if (!findLogFile())
834 {
835 std::this_thread::sleep_for(std::chrono::milliseconds(500));
836 continue;
837 }
838 Logger::debug("[FrameMetrics] Found log file: {}", currentLogFile_);
839 }
840
841 // Open and read new lines
842 std::ifstream file(currentLogFile_);
843 if (!file.is_open())
844 {
845 Logger::debug("[FrameMetrics] Failed to open: {}", currentLogFile_);
846 currentLogFile_.clear(); // Reset to try finding again
847 std::this_thread::sleep_for(std::chrono::milliseconds(100));
848 continue;
849 }
850
851 // Seek to last position
852 file.seekg(lastReadPos_);
853
854 std::string line;
855 while (std::getline(file, line))
856 {
857 if (shouldStop_)
858 break;
859
860 // Skip empty lines
861 if (line.empty())
862 continue;
863
864 // If we haven't parsed header yet, try to parse it
865 if (fpsColumn_ < 0 && frametimeColumn_ < 0)
866 {
867 if (parseHeader(line))
868 {
869 Logger::debug("[FrameMetrics] Found header, fps col={}, frametime col={}",
870 fpsColumn_, frametimeColumn_);
871 }
872 // Even if we found the header, this line IS the header, not data
873 continue;
874 }
875
876 // Parse data line
877 parseLogLine(line);
878 }
879
880 // Save position for next read
881 // Clear any error flags (like EOF) before getting position
882 file.clear();
883 lastReadPos_ = file.tellg();
884
885 // If tellg() failed, get file size as fallback position
886 if (lastReadPos_ == std::streampos(-1))
887 {
888 file.seekg(0, std::ios::end);
889 lastReadPos_ = file.tellg();
890 }
891
892 file.close();
893
894 // Periodically check for newer log files (every ~5 seconds worth of iterations)
895 if (++checkCounter_ >= 50) // 50 * 100ms = 5 seconds
896 {
897 checkCounter_ = 0;
898 std::string oldFile = currentLogFile_;
899 std::string potentialNewFile;
900
901 // Temporarily clear to search
902 currentLogFile_.clear();
903 if (findLogFile())
904 {
905 potentialNewFile = currentLogFile_;
906 }
907
908 if (!potentialNewFile.empty() && potentialNewFile != oldFile)
909 {
910 Logger::debug("[FrameMetrics] Switched to newer log: {}", potentialNewFile);
911 currentLogFile_ = potentialNewFile;
912 lastReadPos_ = 0;
913 fpsColumn_ = -1;
914 frametimeColumn_ = -1;
915 }
916 else
917 {
918 currentLogFile_ = oldFile; // Keep the old file
919 }
920 }
921
922 // Wait before next read
923 std::this_thread::sleep_for(std::chrono::milliseconds(100));
924 }
925}
926
927// ==============================================================================
928// FrameMetricsService Implementation
929// ==============================================================================
930
931FrameMetricsService& FrameMetricsService::instance()
932{
933 static FrameMetricsService instance;
934 return instance;
935}
936
937FrameMetricsService::FrameMetricsService() = default;
938
939FrameMetricsService::~FrameMetricsService()
940{
941 stopAll();
942}
943
944bool FrameMetricsService::startCollection(const std::string& gameId, int pid, bool useGamescope,
945 bool enableMangoHudLogging)
946{
947 std::lock_guard<std::mutex> lock(contextsMutex_);
948
949 // Stop any existing collection for this game
950 auto it = contexts_.find(gameId);
951 if (it != contexts_.end())
952 {
953 it->second.reader->stop();
954 contexts_.erase(it);
955 }
956
957 GameMetricsContext ctx;
958 ctx.pid = pid;
959
960#ifdef PLATFORM_LINUX
961 // Try gamescope first if requested
962 if (useGamescope)
963 {
964 auto gamescopeReader = std::make_unique<GamescopeMetricsReader>();
965 if (gamescopeReader->isAvailable() && gamescopeReader->start(pid))
966 {
967 ctx.reader = std::move(gamescopeReader);
968 contexts_[gameId] = std::move(ctx);
969 Logger::info("[FrameMetrics] Started Gamescope collection for {}", gameId);
970 return true;
971 }
972 }
973#endif
974
975 // Fall back to MangoHud logging
976 if (enableMangoHudLogging)
977 {
978 auto mangoReader = std::make_unique<MangoHudLogReader>();
979 if (mangoReader->isAvailable() && mangoReader->start(pid))
980 {
981 ctx.reader = std::move(mangoReader);
982 contexts_[gameId] = std::move(ctx);
983 Logger::info("[FrameMetrics] Started MangoHud collection for {}", gameId);
984 return true;
985 }
986 }
987
988 Logger::debug("[FrameMetrics] No frame metrics source available for {}", gameId);
989 return false;
990}
991
992void FrameMetricsService::stopCollection(const std::string& gameId)
993{
994 std::lock_guard<std::mutex> lock(contextsMutex_);
995
996 auto it = contexts_.find(gameId);
997 if (it != contexts_.end())
998 {
999 it->second.reader->stop();
1000 contexts_.erase(it);
1001 Logger::debug("[FrameMetrics] Stopped collection for {}", gameId);
1002 }
1003}
1004
1006{
1007 std::lock_guard<std::mutex> lock(contextsMutex_);
1008
1009 for (auto& [gameId, ctx] : contexts_)
1010 {
1011 ctx.reader->stop();
1012 }
1013 contexts_.clear();
1014}
1015
1016FrameMetrics FrameMetricsService::getMetrics(const std::string& gameId) const
1017{
1018 std::lock_guard<std::mutex> lock(contextsMutex_);
1019
1020 auto it = contexts_.find(gameId);
1021 if (it != contexts_.end() && it->second.reader)
1022 {
1023 return it->second.reader->getMetrics();
1024 }
1025
1026 return FrameMetrics();
1027}
1028
1029bool FrameMetricsService::isCollecting(const std::string& gameId) const
1030{
1031 std::lock_guard<std::mutex> lock(contextsMutex_);
1032
1033 auto it = contexts_.find(gameId);
1034 return it != contexts_.end() && it->second.reader && it->second.reader->isActive();
1035}
1036
1038{
1039#ifdef PLATFORM_LINUX
1040 GamescopeMetricsReader reader;
1041 return reader.isAvailable();
1042#else
1043 return false;
1044#endif
1045}
1046
1048{
1049 MangoHudLogReader reader;
1050 return reader.isAvailable();
1051}
1052
1057
1058std::string
1060 const std::string& userConfigFile) const
1061{
1062 return MangoHudLogReader::buildLaunchConfigFile(gameId, userConfigFile);
1063}
1064
1066{
1067#ifdef PLATFORM_LINUX
1068 std::string logDir = MangoHudLogReader::getDefaultLogDirectory();
1069 DIR* dir = opendir(logDir.c_str());
1070 if (!dir)
1071 return 0;
1072
1073 int deletedCount = 0;
1074 const time_t now = time(nullptr);
1075 const time_t maxAgeSeconds = static_cast<time_t>(maxAgeHours) * 3600;
1076 const time_t orphanAgeSeconds = 3600; // 1 hour
1077 const time_t activeWriteWindowSeconds = 300; // 5 minutes — protects active sessions
1078
1079 // Strict filename matchers — only delete files we created or that match
1080 // MangoHud's naming convention. The log directory is often the user's
1081 // $HOME (when goverlay sets `output_folder=/home/user/`), so a loose
1082 // `*.csv` match would risk deleting unrelated user files.
1083 //
1084 // MangoHud writes logs as: <exename>_YYYY-MM-DD_HH-MM-SS.csv (and a
1085 // matching _summary.csv on session end). Source: src/logging.cpp
1086 // generate_log_filename().
1087 static const std::regex mangoLogPattern(R"(^.+_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.csv$)");
1088 static const std::regex mangoSummaryPattern(
1089 R"(^.+_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_summary\.csv$)");
1090 // Our own per-launch config files written by buildLaunchConfigFile().
1091 static const std::regex ourConfigPattern(R"(^mangohud-launch-.+\.conf$)");
1092
1093 struct dirent* entry;
1094 while ((entry = readdir(dir)) != nullptr)
1095 {
1096 const std::string filename = entry->d_name;
1097 const std::string fullPath = logDir + "/" + filename;
1098
1099 // Skip symlinks before any stat-based decision so we never unlink()
1100 // through one (would let an attacker who can write the log dir
1101 // remove arbitrary filesystem targets).
1102 struct stat linkStat;
1103 if (lstat(fullPath.c_str(), &linkStat) != 0)
1104 continue;
1105 if (S_ISLNK(linkStat.st_mode))
1106 {
1107 Logger::warn("[FrameMetrics] Skipping symlink in log dir: {}", filename);
1108 continue;
1109 }
1110 if (!S_ISREG(linkStat.st_mode))
1111 continue;
1112
1113 const time_t age = now - linkStat.st_mtime;
1114
1115 // Active-write protection: a file written to within the last few
1116 // minutes is almost certainly an in-flight session log (MangoHud
1117 // appends every log_interval=100ms). Never delete one, even if it
1118 // would otherwise be eligible — beats any heuristic about whether
1119 // the session is "complete".
1120 if (age < activeWriteWindowSeconds)
1121 continue;
1122
1123 // 1. Our own per-launch MangoHud config files
1124 if (std::regex_match(filename, ourConfigPattern))
1125 {
1126 if (age > maxAgeSeconds)
1127 {
1128 if (unlink(fullPath.c_str()) == 0)
1129 {
1130 deletedCount++;
1131 Logger::debug("[FrameMetrics] Deleted old launch config: {}", filename);
1132 }
1133 }
1134 continue;
1135 }
1136
1137 // 2. MangoHud session logs — only the data file (not _summary).
1138 // Skip anything that doesn't match MangoHud's strict naming so
1139 // user-owned CSVs in the same directory stay safe.
1140 if (!std::regex_match(filename, mangoLogPattern))
1141 continue;
1142 if (std::regex_match(filename, mangoSummaryPattern))
1143 continue;
1144
1145 const std::string summaryPath = fullPath.substr(0, fullPath.size() - 4) + "_summary.csv";
1146
1147 struct stat summaryStat;
1148 const bool hasCompleted = (stat(summaryPath.c_str(), &summaryStat) == 0);
1149
1150 if (hasCompleted)
1151 {
1152 // Completed log — keep until maxAgeHours so users can review
1153 // recent sessions in tools like goverlay.
1154 if (age > maxAgeSeconds)
1155 {
1156 if (unlink(fullPath.c_str()) == 0)
1157 {
1158 deletedCount++;
1159 Logger::debug("[FrameMetrics] Deleted old completed log: {}", filename);
1160 }
1161 unlink(summaryPath.c_str());
1162 }
1163 }
1164 else
1165 {
1166 // No summary — game was force-killed or crashed before MangoHud
1167 // could close the session. The active-write check above already
1168 // protected logs being written to right now; anything older than
1169 // the orphan window with no summary is genuinely abandoned.
1170 if (age > orphanAgeSeconds)
1171 {
1172 if (unlink(fullPath.c_str()) == 0)
1173 {
1174 deletedCount++;
1175 Logger::debug("[FrameMetrics] Deleted orphaned log: {}", filename);
1176 }
1177 }
1178 }
1179 }
1180 closedir(dir);
1181
1182 if (deletedCount > 0)
1183 {
1184 Logger::info("[FrameMetrics] Cleaned up {} old MangoHud files", deletedCount);
1185 }
1186
1187 return deletedCount;
1188#else
1189 return 0;
1190#endif
1191}
bool startCollection(const std::string &gameId, int pid, bool useGamescope=false, bool enableMangoHudLogging=true)
Start collecting metrics for a game.
bool isCollecting(const std::string &gameId) const
Check if collection is active for a game.
std::string getMangoHudLoggingConfig() const
Get MangoHud config for enabling logging.
FrameMetrics getMetrics(const std::string &gameId) const
Get current metrics for a game.
static FrameMetricsService & instance()
Get the singleton instance.
int cleanupOldLogs(int maxAgeHours=24)
Clean up old MangoHud log files.
bool isGamescopeAvailable() const
Check if gamescope is available.
std::string buildMangoHudLaunchConfigFile(const std::string &gameId, const std::string &userConfigFile={}) const
Materialise a complete MangoHud config file for a launch.
bool isMangoHudLoggingAvailable() const
Check if MangoHud logging is available.
void stopAll()
Stop all active collections.
void stopCollection(const std::string &gameId)
Stop collecting metrics for a game.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
Reads frame metrics from MangoHud CSV log files.
bool isActive() const override
Check if reader is actively collecting.
static std::string getDefaultLogDirectory()
Get the default log directory.
bool start(int pid) override
Start collecting metrics for a process.
FrameMetrics getMetrics() const override
Get the latest metrics.
static std::string getLoggingConfig()
Get the MangoHud config string for logging.
void setLogDirectory(const std::string &path)
Set the log directory to monitor.
~MangoHudLogReader() override
static std::string buildLaunchConfigFile(const std::string &gameId, const std::string &userConfigFile={})
Materialise a complete MangoHud config file for a launch.
void stop() override
Stop collecting metrics.
bool isAvailable() const override
Check if this reader is available on the system.
static bool readIsolateMangoHudLogsFromDisk()
Read just isolateMangoHudLogs directly from the settings file.
Real-time frame timing and performance metrics.
static constexpr size_t GRAPH_HISTORY_SIZE