game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
frame_metrics.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// frame_metrics.h
4// ==============================================================================
5// Frame metrics collection for real-time FPS and frametime display
6// ==============================================================================
7// This file provides classes for reading frame metrics from running games:
8//
9// ## FrameMetrics
10// Data structure containing frame timing information (FPS, frametime, etc.)
11//
12// ## IFrameMetricsReader
13// Abstract interface for reading frame metrics from different sources
14//
15// ## GamescopeMetricsReader
16// Reads metrics via Gamescope's System V message queue (real-time, preferred)
17//
18// ## MangoHudLogReader
19// Reads metrics from MangoHud CSV log files (fallback, slight delay)
20//
21// ## FrameMetricsService
22// Singleton service that manages frame metrics collection for running games
23// ==============================================================================
24
25#pragma once
26
27#include <atomic>
28#include <chrono>
29#include <functional>
30#include <memory>
31#include <mutex>
32#include <string>
33#include <thread>
34#include <unordered_map>
35#include <vector>
36
37// ==============================================================================
38// Frame Metrics Data Structure
39// ==============================================================================
40
41/**
42 * @struct FrameMetrics
43 * @brief Real-time frame timing and performance metrics
44 *
45 * Contains frame-related metrics that can be displayed in the UI while
46 * a game is running. Data is sourced from Gamescope IPC or MangoHud logs.
47 */
49{
50 // Core frame timing
51 double fps = 0.0; ///< Current frames per second
52 double frametime_ms = 0.0; ///< Current frame time in milliseconds
53 double fps_avg = 0.0; ///< Average FPS over sample window
54 double frametime_avg_ms = 0.0; ///< Average frametime over sample window
55
56 // Frame time percentiles (useful for stutter detection)
57 double fps_1_low = 0.0; ///< 1% low FPS (99th percentile frametime)
58 double fps_0_1_low = 0.0; ///< 0.1% low FPS (99.9th percentile frametime)
59
60 // Min/Max for current window
61 double fps_min = 0.0; ///< Minimum FPS in sample window
62 double fps_max = 0.0; ///< Maximum FPS in sample window
63 double frametime_min_ms = 0.0; ///< Minimum frametime in sample window
64 double frametime_max_ms = 0.0; ///< Maximum frametime in sample window
65
66 // Latency (if available from Gamescope)
67 double latency_ms = 0.0; ///< Input-to-display latency in ms
68
69 // Display info (from Gamescope)
70 uint16_t display_refresh = 0; ///< Monitor refresh rate (Hz)
71 uint32_t output_width = 0; ///< Output resolution width
72 uint32_t output_height = 0; ///< Output resolution height
73
74 // Source info
75 std::string source; ///< "gamescope", "mangohud", or empty
76 std::string engine_name; ///< Game engine name (if detected)
77
78 // Timestamp
79 std::chrono::steady_clock::time_point timestamp;
80
81 // Sample count for averaging
82 uint32_t sample_count = 0;
83
84 // Frametime history for graph (last ~2 seconds at 10Hz = 20 samples)
85 static constexpr size_t GRAPH_HISTORY_SIZE = 60;
86 std::vector<double> frametimeHistory; ///< Recent frametimes for graph
87
88 /**
89 * @brief Check if metrics are valid/fresh
90 * @param max_age_ms Maximum age in milliseconds
91 * @return True if metrics are recent and valid
92 */
93 bool isValid(int max_age_ms = 2000) const
94 {
95 if (sample_count == 0)
96 return false;
97 auto age = std::chrono::steady_clock::now() - timestamp;
98 return std::chrono::duration_cast<std::chrono::milliseconds>(age).count() < max_age_ms;
99 }
100
101 /**
102 * @brief Get formatted FPS string
103 * @return FPS as string with 1 decimal place
104 */
105 std::string getFPSString() const
106 {
107 char buf[32];
108 std::snprintf(buf, sizeof(buf), "%.1f", fps);
109 return buf;
110 }
111
112 /**
113 * @brief Get formatted frametime string
114 * @return Frametime as string with 2 decimal places + "ms"
115 */
116 std::string getFrametimeString() const
117 {
118 char buf[32];
119 std::snprintf(buf, sizeof(buf), "%.2f ms", frametime_ms);
120 return buf;
121 }
122
123 /**
124 * @brief Get formatted 1% low string
125 * @return 1% low FPS as string
126 */
127 std::string get1LowString() const
128 {
129 if (fps_1_low <= 0.0)
130 return "N/A";
131 char buf[32];
132 std::snprintf(buf, sizeof(buf), "%.1f", fps_1_low);
133 return buf;
134 }
135
136 /**
137 * @brief Get formatted latency string
138 * @return Latency as string with 1 decimal place + "ms", or "N/A"
139 */
140 std::string getLatencyString() const
141 {
142 if (latency_ms <= 0.0)
143 return "N/A";
144 char buf[32];
145 std::snprintf(buf, sizeof(buf), "%.1f ms", latency_ms);
146 return buf;
147 }
148
149 /**
150 * @brief Get formatted 0.1% low string
151 * @return 0.1% low FPS as string
152 */
153 std::string get01LowString() const
154 {
155 if (fps_0_1_low <= 0.0)
156 return "N/A";
157 char buf[32];
158 std::snprintf(buf, sizeof(buf), "%.1f", fps_0_1_low);
159 return buf;
160 }
161
162 /**
163 * @brief Get age of metrics in milliseconds
164 * @return Age in ms since last update
165 */
166 int64_t getAgeMs() const
167 {
168 auto age = std::chrono::steady_clock::now() - timestamp;
169 return std::chrono::duration_cast<std::chrono::milliseconds>(age).count();
170 }
171
172 /**
173 * @brief Get formatted average FPS string
174 * @return Average FPS as string with 1 decimal place
175 */
176 std::string getFPSAvgString() const
177 {
178 if (fps_avg <= 0.0)
179 return "N/A";
180 char buf[32];
181 std::snprintf(buf, sizeof(buf), "%.1f", fps_avg);
182 return buf;
183 }
184};
185
186// ==============================================================================
187// Frame Metrics Reader Interface
188// ==============================================================================
189
190/**
191 * @class IFrameMetricsReader
192 * @brief Abstract interface for frame metrics sources
193 *
194 * Implementations read frame data from different sources:
195 * - GamescopeMetricsReader: System V message queue from gamescope
196 * - MangoHudLogReader: CSV log files from MangoHud
197 */
199{
200 public:
201 virtual ~IFrameMetricsReader() = default;
202
203 /**
204 * @brief Start collecting metrics for a process
205 * @param pid Process ID of the game
206 * @return True if successfully started
207 */
208 virtual bool start(int pid) = 0;
209
210 /**
211 * @brief Stop collecting metrics
212 */
213 virtual void stop() = 0;
214
215 /**
216 * @brief Check if reader is actively collecting
217 * @return True if collecting metrics
218 */
219 virtual bool isActive() const = 0;
220
221 /**
222 * @brief Get the latest metrics
223 * @return Current frame metrics (check isValid())
224 */
225 virtual FrameMetrics getMetrics() const = 0;
226
227 /**
228 * @brief Get the source name for this reader
229 * @return Source identifier (e.g., "gamescope", "mangohud")
230 */
231 virtual std::string getSourceName() const = 0;
232
233 /**
234 * @brief Check if this reader is available on the system
235 * @return True if the underlying source is available
236 */
237 virtual bool isAvailable() const = 0;
238};
239
240// ==============================================================================
241// Gamescope Metrics Reader (Linux only)
242// ==============================================================================
243
244#ifdef PLATFORM_LINUX
245
246/**
247 * @class GamescopeMetricsReader
248 * @brief Reads frame metrics from Gamescope's MangoApp message queue
249 *
250 * Gamescope exposes frame timing data via System V message queues.
251 * This provides real-time, low-latency metrics including:
252 * - Frame time (nanosecond precision)
253 * - Visible frame time (after compositor)
254 * - Input latency
255 * - Display refresh rate
256 * - Output resolution
257 *
258 * This is the preferred method when running games through gamescope.
259 */
260class GamescopeMetricsReader : public IFrameMetricsReader
261{
262 public:
263 GamescopeMetricsReader();
264 ~GamescopeMetricsReader() override;
265
266 bool start(int pid) override;
267 void stop() override;
268 bool isActive() const override;
269 FrameMetrics getMetrics() const override;
270 std::string getSourceName() const override
271 {
272 return "gamescope";
273 }
274 bool isAvailable() const override;
275
276 private:
277 void readerThread();
278 bool connectToMessageQueue();
279
280 std::thread readerThread_;
281 std::atomic<bool> shouldStop_{false};
282 std::atomic<bool> isActive_{false};
283 mutable std::mutex metricsMutex_;
284 FrameMetrics currentMetrics_;
285
286 int msgQueueId_ = -1;
287 int targetPid_ = -1;
288
289 // Circular buffer for percentile calculations
290 static constexpr size_t SAMPLE_BUFFER_SIZE = 300; // ~5 seconds at 60fps
291 std::vector<double> frametimeBuffer_;
292 size_t bufferIndex_ = 0;
293 size_t bufferCount_ = 0;
294
295 void updatePercentiles();
296};
297
298#endif // PLATFORM_LINUX
299
300// ==============================================================================
301// MangoHud Log Reader
302// ==============================================================================
303
304/**
305 * @class MangoHudLogReader
306 * @brief Reads frame metrics from MangoHud CSV log files
307 *
308 * MangoHud can log metrics to CSV files. This reader tails the log file
309 * and parses the latest entries for frame timing data.
310 *
311 * Requires MangoHud to be launched with logging enabled:
312 * MANGOHUD_CONFIG="output_folder=/tmp/gamelauncher,autostart_log=1"
313 *
314 * This is a fallback when gamescope is not being used.
315 */
317{
318 public:
320 ~MangoHudLogReader() override;
321
322 bool start(int pid) override;
323 void stop() override;
324 bool isActive() const override;
325 FrameMetrics getMetrics() const override;
326 std::string getSourceName() const override
327 {
328 return "mangohud";
329 }
330 bool isAvailable() const override;
331
332 /**
333 * @brief Set the log directory to monitor
334 * @param path Directory path where MangoHud writes logs
335 */
336 void setLogDirectory(const std::string& path);
337
338 /**
339 * @brief Get the MangoHud config string for logging
340 * @return Config string to pass via MANGOHUD_CONFIG
341 */
342 static std::string getLoggingConfig();
343
344 /**
345 * @brief Materialise a complete MangoHud config file for a launch
346 *
347 * Writes our logging keys (output_folder/autostart_log/log_duration/
348 * log_interval) to a file under the log directory. If @p userConfigFile is
349 * non-empty and exists, its contents are copied first so the user's
350 * overlay layout / display options are preserved; our logging keys are
351 * appended last and therefore win because parseConfigLine in
352 * MangoHud's src/config.cpp simply overwrites earlier values in the
353 * options map.
354 *
355 * The returned path is intended to be passed via MANGOHUD_CONFIGFILE,
356 * which causes MangoHud's parseConfigFile (src/config.cpp) to skip
357 * enumerate_config_files and load only this file — fully isolating us
358 * from the user's ~/.config/MangoHud/MangoHud.conf (which goverlay
359 * 1.7.5 may populate with a competing log_duration).
360 *
361 * @param gameId Identifier used to scope the file per-game
362 * @param userConfigFile Optional path to a user-provided MangoHud config
363 * @return Absolute path to the generated config file, or empty on failure
364 */
365 static std::string buildLaunchConfigFile(const std::string& gameId,
366 const std::string& userConfigFile = {});
367
368 /**
369 * @brief Get the default log directory
370 * @return Path to log directory
371 */
372 static std::string getDefaultLogDirectory();
373
374 private:
375 void readerThread();
376 bool findLogFile();
377 bool parseLogLine(const std::string& line);
378 bool parseHeader(const std::string& line);
379
380 std::thread readerThread_;
381 std::atomic<bool> shouldStop_{false};
382 std::atomic<bool> isActive_{false};
383 mutable std::mutex metricsMutex_;
384 FrameMetrics currentMetrics_;
385
386 std::string logDirectory_;
387 std::string currentLogFile_;
388 int targetPid_ = -1;
389 std::streampos lastReadPos_ = 0;
390
391 // CSV column indices (determined from header)
392 int fpsColumn_ = -1;
393 int frametimeColumn_ = -1;
394
395 // Circular buffer for percentile calculations
396 static constexpr size_t SAMPLE_BUFFER_SIZE = 300;
397 std::vector<double> frametimeBuffer_;
398 size_t bufferIndex_ = 0;
399 size_t bufferCount_ = 0;
400
401 int checkCounter_ = 0; // Per-instance log-rotation check counter (replaces former static)
402
403 void updatePercentiles();
404};
405
406// ==============================================================================
407// Frame Metrics Service (Singleton)
408// ==============================================================================
409
410/**
411 * @class FrameMetricsService
412 * @brief Singleton service managing frame metrics collection
413 *
414 * Provides a unified interface for collecting frame metrics from running games.
415 * Automatically selects the best available source (gamescope > mangohud).
416 *
417 * Usage:
418 * @code
419 * // Start collecting for a game
420 * FrameMetricsService::instance().startCollection(gameId, pid, useGamescope);
421 *
422 * // Get current metrics
423 * auto metrics = FrameMetricsService::instance().getMetrics(gameId);
424 * if (metrics.isValid()) {
425 * std::cout << "FPS: " << metrics.fps << std::endl;
426 * }
427 *
428 * // Stop when game exits
429 * FrameMetricsService::instance().stopCollection(gameId);
430 * @endcode
431 */
432class FrameMetricsService
433{
434 public:
435 /**
436 * @brief Get the singleton instance
437 * @return Reference to the service instance
438 */
439 static FrameMetricsService& instance();
440
441 /**
442 * @brief Start collecting metrics for a game
443 * @param gameId Unique game identifier
444 * @param pid Process ID of the game
445 * @param useGamescope True if game is running through gamescope
446 * @param enableMangoHudLogging True to enable MangoHud logging config
447 * @return True if collection started successfully
448 */
449 bool startCollection(const std::string& gameId, int pid, bool useGamescope = false,
450 bool enableMangoHudLogging = true);
451
452 /**
453 * @brief Stop collecting metrics for a game
454 * @param gameId Game identifier to stop
455 */
456 void stopCollection(const std::string& gameId);
457
458 /**
459 * @brief Stop all active collections
460 */
461 void stopAll();
462
463 /**
464 * @brief Get current metrics for a game
465 * @param gameId Game identifier
466 * @return Frame metrics (check isValid() before use)
467 */
468 FrameMetrics getMetrics(const std::string& gameId) const;
469
470 /**
471 * @brief Check if collection is active for a game
472 * @param gameId Game identifier
473 * @return True if actively collecting
474 */
475 bool isCollecting(const std::string& gameId) const;
476
477 /**
478 * @brief Check if gamescope is available
479 * @return True if gamescope metrics can be collected
480 */
481 bool isGamescopeAvailable() const;
482
483 /**
484 * @brief Check if MangoHud logging is available
485 * @return True if MangoHud log reading is available
486 */
487 bool isMangoHudLoggingAvailable() const;
488
489 /**
490 * @brief Get MangoHud config for enabling logging
491 * @return Config string to append to MANGOHUD_CONFIG
492 */
493 std::string getMangoHudLoggingConfig() const;
494
495 /**
496 * @brief Materialise a complete MangoHud config file for a launch
497 *
498 * Thin wrapper over MangoHudLogReader::buildLaunchConfigFile. Returns a
499 * path suitable for passing via MANGOHUD_CONFIGFILE, which fully replaces
500 * the user's ~/.config/MangoHud/MangoHud.conf during the launch.
501 *
502 * @param gameId Identifier used to scope the file per-game
503 * @param userConfigFile Optional path to a user-provided MangoHud config
504 * @return Absolute path to the generated config file, or empty on failure
505 */
506 std::string buildMangoHudLaunchConfigFile(const std::string& gameId,
507 const std::string& userConfigFile = {}) const;
508
509 /**
510 * @brief Clean up old MangoHud log files
511 * @param maxAgeHours Delete completed logs older than this (default 24 hours)
512 * @return Number of files deleted
513 *
514 * Deletes completed MangoHud log files (those with _summary.csv siblings)
515 * that are older than the specified age. Active logs are never deleted.
516 */
517 int cleanupOldLogs(int maxAgeHours = 24);
518
519 private:
520 FrameMetricsService();
521 ~FrameMetricsService();
522 FrameMetricsService(const FrameMetricsService&) = delete;
523 FrameMetricsService& operator=(const FrameMetricsService&) = delete;
524
525 struct GameMetricsContext
526 {
527 std::unique_ptr<IFrameMetricsReader> reader;
528 int pid = -1;
529 };
530
531 mutable std::mutex contextsMutex_;
532 std::unordered_map<std::string, GameMetricsContext> contexts_;
533};
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.
Abstract interface for frame metrics sources.
virtual FrameMetrics getMetrics() const =0
Get the latest metrics.
virtual bool isAvailable() const =0
Check if this reader is available on the system.
virtual ~IFrameMetricsReader()=default
virtual std::string getSourceName() const =0
Get the source name for this reader.
virtual void stop()=0
Stop collecting metrics.
virtual bool start(int pid)=0
Start collecting metrics for a process.
virtual bool isActive() const =0
Check if reader is actively collecting.
bool isActive() const override
Check if reader is actively collecting.
std::string getSourceName() const override
Get the source name for this reader.
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.
Real-time frame timing and performance metrics.
uint32_t output_width
Output resolution width.
double fps_min
Minimum FPS in sample window.
std::string getFrametimeString() const
Get formatted frametime string.
double fps_0_1_low
0.1% low FPS (99.9th percentile frametime)
uint32_t output_height
Output resolution height.
std::vector< double > frametimeHistory
Recent frametimes for graph.
std::string getFPSAvgString() const
Get formatted average FPS string.
double frametime_ms
Current frame time in milliseconds.
double frametime_min_ms
Minimum frametime in sample window.
std::string getFPSString() const
Get formatted FPS string.
static constexpr size_t GRAPH_HISTORY_SIZE
std::chrono::steady_clock::time_point timestamp
std::string get01LowString() const
Get formatted 0.1% low string.
std::string getLatencyString() const
Get formatted latency string.
bool isValid(int max_age_ms=2000) const
Check if metrics are valid/fresh.
double frametime_avg_ms
Average frametime over sample window.
int64_t getAgeMs() const
Get age of metrics in milliseconds.
double fps
Current frames per second.
double fps_max
Maximum FPS in sample window.
uint32_t sample_count
double latency_ms
Input-to-display latency in ms.
std::string engine_name
Game engine name (if detected).
double fps_1_low
1% low FPS (99th percentile frametime)
double fps_avg
Average FPS over sample window.
std::string get1LowString() const
Get formatted 1% low string.
std::string source
"gamescope", "mangohud", or empty
double frametime_max_ms
Maximum frametime in sample window.
uint16_t display_refresh
Monitor refresh rate (Hz).