Stats overlay: Graphs style (MangoHud-like): frametime, pipeline, delay and GPU graphs with 1% lows

This commit is contained in:
bonzi committed 2026-11-20 12:28:31 +00:00
1 parent a6486a61e5
commit 06bdf44674
6 files changed
+230 -12

No files matched your search

+6
View File
@@ -2,6 +2,12 @@
## 0.3.8
**Stats overlay**
- **A Graphs style, like MangoHud's.** Press S to cycle Off, Minimal, Detailed, Graphs (or pick it in Settings). Live
scrolling graphs of the time between frames on screen (with 1% lows), the pipeline's time per tick against its
budget, SmoovPlay's delay, and the graphics card's load, power, temperature, clock and memory (read with
`nvidia-smi`; the GPU row is left out without it). Bars turn amber and red when a frame is late.
**Settings**
- **Capture card resolution is greyed out unless a capture card is your source** (picked on the Play page), with a
note saying why: PS5 Remote Play streams 1080p at most, and App window capture is scaled to 1080p. Before, you
+53
View File
@@ -0,0 +1,53 @@
"""GPU numbers for the Graphs stats overlay: utilisation, power, temperature, clock and memory from `nvidia-smi`, read
once a second on a thread of its own so the video loop never waits for it. No NVIDIA driver tools, or any trouble: the
numbers are simply missing (`latest` stays None) and the overlay leaves the row out."""
from __future__ import annotations
import collections
import subprocess
import sys
import threading
QUERY = "utilization.gpu,power.draw,temperature.gpu,memory.used,memory.total,clocks.sm"
class GpuStats:
def __init__(self, history: int = 120) -> None:
self.latest: dict | None = None # {"util", "power", "temp", "mem", "mem_total", "clock"}
self.util = collections.deque(maxlen=history)
self._proc = None
self._stop = False
threading.Thread(target=self._run, name="gpustats", daemon=True).start()
@staticmethod
def parse(line: str) -> dict | None:
"""One csv line (units off) as numbers; None if it isn't one."""
try:
u, p, t, m, mt, c = (float(x) for x in line.split(","))
except ValueError:
return None
return {"util": u, "power": p, "temp": t, "mem": m, "mem_total": mt, "clock": c}
def _run(self) -> None:
try:
flags = 0x08000000 if sys.platform == "win32" else 0 # no console window on Windows
self._proc = subprocess.Popen(
["nvidia-smi", f"--query-gpu={QUERY}", "--format=csv,noheader,nounits", "-l", "1"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, creationflags=flags)
for line in self._proc.stdout:
if self._stop:
break
d = self.parse(line)
if d is not None:
self.latest = d
self.util.append(d["util"])
except Exception: # noqa: BLE001 - no nvidia-smi: no GPU row
self.latest = None
def close(self) -> None:
self._stop = True
if self._proc is not None:
try:
self._proc.terminate()
except Exception: # noqa: BLE001
pass
+125 -3
View File
@@ -8,6 +8,7 @@ import random
import subprocess
import sys
import threading
import collections
import time
from collections import OrderedDict
from dataclasses import dataclass, field
@@ -417,11 +418,12 @@ class MiniText(str):
parts: tuple = ()
health: str = ""
second: str = ""
graph: dict | None = None # the Graphs overlay's data (pipeline: hz, tick_ms, busy, delay), else None
@classmethod
def make(cls, parts, health: str = "", second: str = "") -> "MiniText":
def make(cls, parts, health: str = "", second: str = "", graph: dict | None = None) -> "MiniText":
t = cls(" ".join(x for x, _ in parts) + (f"\n{second}" if second else ""))
t.parts, t.health, t.second = tuple(parts), health, second
t.parts, t.health, t.second, t.graph = tuple(parts), health, second, graph
return t
@@ -455,6 +457,102 @@ def _mini(t: MiniText, ui: float) -> np.ndarray:
return img
GRAPH_BG, GRAPH_PLOT = (30, 27, 25), (44, 40, 37)
GRAPH_GOOD, GRAPH_TIGHT, GRAPH_BAD = (110, 200, 80), (40, 180, 250), (70, 70, 235)
def _plot(img, x: int, y: int, w: int, h: int, series, vmax: float, target: float | None, ui: float, colour) -> None:
"""A MangoHud-style bar graph: one vertical line per sample, newest on the right, coloured by `colour(v)`, with a
thin line at `target` (the budget). The box is x, y (top-left), w by h."""
cv2.rectangle(img, (x, y), (x + w - 1, y + h - 1), GRAPH_PLOT, -1)
vals = list(series)[-w:]
x0 = x + w - len(vals)
for i, v in enumerate(vals):
bar = max(1, int(round(min(v, vmax) / vmax * (h - 1))))
cv2.line(img, (x0 + i, y + h - 1), (x0 + i, y + h - bar), colour(v), 1)
if target is not None and 0 < target < vmax:
ty = y + h - 1 - int(round(target / vmax * (h - 1)))
cv2.line(img, (x, ty), (x + w - 1, ty), (150, 150, 150), 1, cv2.LINE_AA)
def _graphs(t: MiniText, frametimes, ui: float, gpu=None) -> np.ndarray:
"""The Graphs overlay (Stats overlay style: Graphs), like MangoHud's: the frame rate in big numbers, then a graph each
for the time between frames on screen (what you see), the pipeline's time per tick against its budget, SmoovPlay's
delay, and the graphics card's load. t.graph, from the pipeline: hz, tick_ms (the budget), busy, delay (lists, newest
last). frametimes: milliseconds between the window's last presents, newest last. gpu: framegen.gpustats.GpuStats."""
g = t.graph
font = cv2.FONT_HERSHEY_SIMPLEX
fs, small, big = 0.46 * ui, 0.40 * ui, 0.95 * ui
th = 1 if ui < 1.6 else 2
pad, gw, gh, gap = int(10 * ui), int(300 * ui), int(46 * ui), int(8 * ui)
ft = list(frametimes)[-gw:]
target = 1000.0 / max(1, g.get("hz", 60))
colour_ft = lambda v: GRAPH_GOOD if v <= 1.35 * target else GRAPH_TIGHT if v <= 2.2 * target else GRAPH_BAD # noqa: E731
tick = g.get("tick_ms", 1000 / 60)
colour_busy = lambda v: GRAPH_GOOD if v < 0.75 * tick else GRAPH_TIGHT if v < tick else GRAPH_BAD # noqa: E731
colour_delay = lambda v: GRAPH_GOOD if v < 45 else GRAPH_TIGHT if v < 80 else GRAPH_BAD # noqa: E731
def label(img, text, y, colour=MINI_TEXT["dim"], x=None, scale=small):
cv2.putText(img, text, (pad if x is None else x, y), font, scale, colour, 1, cv2.LINE_AA)
rows = [("frametime", ft, max(3 * target, float(np.percentile(ft, 99)) * 1.15 if ft else 3 * target), target,
colour_ft), ("pipeline", g.get("busy", [])[-gw:], 2 * tick, tick, colour_busy),
("delay", g.get("delay", [])[-gw:], 120.0, None, colour_delay)]
th_big = cv2.getTextSize("120", font, big, th + 1)[0][1]
th_lbl = cv2.getTextSize("Ag", font, small, 1)[0][1]
gpu_d = gpu.latest if gpu is not None else None
w = 2 * pad + gw
h = 2 * pad + th_big + gap + len(rows) * (th_lbl + int(4 * ui) + gh + gap)
if gpu_d:
h += th_lbl + int(4 * ui) + int(26 * ui) + gap + th_lbl
h += (th_lbl + gap) if t.second else 0
img = np.full((h, w, 3), GRAPH_BG, np.uint8)
y = pad + th_big
cv2.circle(img, (pad + int(5 * ui), y - th_big // 2), max(3, int(5 * ui)), HEALTH_COLORS.get(t.health, HEALTH_COLORS[""]), -1,
cv2.LINE_AA)
x = pad + int(18 * ui)
for text, kind in t.parts:
sc = big if text.endswith(" fps") and kind == "main" else fs
cv2.putText(img, text, (x, y), font, sc, MINI_TEXT.get(kind, MINI_TEXT["dim"]), th if sc == big else 1, cv2.LINE_AA)
x += cv2.getTextSize(text, font, sc, th if sc == big else 1)[0][0] + int(12 * ui)
y += gap
for name, series, vmax, tgt, colour in rows:
series = list(series)
y += th_lbl
if series:
last = series[-1]
srt = sorted(series)
p99 = srt[min(len(srt) - 1, int(0.99 * len(srt)))]
if name == "frametime":
text = f"{last:5.1f} ms avg {sum(series) / len(series):4.1f} 1% low {1000.0 / max(p99, 0.1):.0f} fps"
elif name == "pipeline":
text = f"{last:5.1f} ms avg {sum(series) / len(series):4.1f} budget {tick:.1f}"
else:
text = f"{last:5.0f} ms avg {sum(series) / len(series):4.0f} max {max(series):.0f}"
else:
text = "-"
label(img, name, y, MINI_TEXT["main"])
label(img, text, y, MINI_TEXT["dim"], x=pad + int(80 * ui))
y += int(4 * ui)
_plot(img, pad, y, gw, gh, series, max(vmax, 1.0), tgt, ui, colour)
y += gh + gap
if gpu_d:
y += th_lbl
label(img, "gpu", y, MINI_TEXT["main"])
label(img, f"{gpu_d['util']:3.0f}% {gpu_d['power']:3.0f} W {gpu_d['temp']:.0f} C "
f"{gpu_d['clock']:.0f} MHz vram {gpu_d['mem'] / 1024:.1f}/{gpu_d['mem_total'] / 1024:.0f} GB",
y, MINI_TEXT["dim"], x=pad + int(40 * ui))
y += int(4 * ui)
_plot(img, pad, y, gw, int(26 * ui), list(gpu.util), 100.0, None, ui,
lambda v: GRAPH_GOOD if v < 80 else GRAPH_TIGHT if v < 95 else GRAPH_BAD)
y += int(26 * ui) + gap
if t.second:
y += th_lbl
label(img, t.second, y, MINI_TEXT["dim"])
return img
def _pill(text: str, ui: float, color=(238, 238, 238)) -> np.ndarray:
"""A short message (one line, or a few split by newlines) on a dark rounded-off box."""
fs, th = 0.7 * ui, 1 if ui < 1.4 else 2
@@ -650,6 +748,7 @@ class GLWindowSink:
self.menu = Menu(st, allowed=self.allowed, disabled=self.disabled, restart_reasons=restart_reasons)
self.menu_panel, self.toast_panel = _Panel(GL, self.hdr10), _Panel(GL, self.hdr10)
self.mini_panel, self._mini_state = _Panel(GL, self.hdr10), None
self._frametimes, self._last_write, self._graph_drawn, self._gpu = collections.deque(maxlen=480), 0.0, 0.0, None
self._menu_top = None # (GL y of the menu's top, the picture's (y0, height) it was placed in) while it's open
self._menu_state = self._toast_state = None
self._toast_text, self._toast_until = "M: menu F: fullscreen Esc: quit", time.perf_counter() + 8.0
@@ -1132,6 +1231,8 @@ class GLWindowSink:
st.set("overlay", True)
elif st.overlay_style == "minimal":
st.set("overlay_style", "detailed")
elif st.overlay_style == "detailed":
st.set("overlay_style", "graphs")
else:
st.set("overlay", False)
elif key == glfw.KEY_U:
@@ -1268,6 +1369,10 @@ class GLWindowSink:
def write(self, frame, text: str | None = None) -> str | None:
"""frame: HxWx3 uint8 BGR, a numpy array or a CUDA tensor."""
GL, glfw = self.GL, self.glfw
now = time.perf_counter() # the Graphs overlay's frametime: the time between this window's frames
if self._last_write and now - self._last_write < 0.5:
self._frametimes.append((now - self._last_write) * 1000)
self._last_write = now
if self._waited >= 0: # a picture again after a wait: its note goes
self._waited, self._toast_until = -1, 0.0
if self.overlay_of is not None:
@@ -1328,7 +1433,9 @@ class GLWindowSink:
self.panorama.draw(screen, fw, fh, panorama_t(fw, fh, self.w, self.h))
label += " + panorama"
self.timer.end(q, f"{label} {dw}x{dh}")
if self.overlay and isinstance(text, MiniText):
if self.overlay and isinstance(text, MiniText) and getattr(text, "graph", None):
self._draw_graphs(text, ux, uy, uh)
elif self.overlay and isinstance(text, MiniText):
self._draw_mini(text, ux, uy, uh)
elif self.overlay and text:
first, nl, rest = text.partition("\n") # the upscaler goes on the first line; a second is the test line
@@ -1414,6 +1521,19 @@ class GLWindowSink:
m = int(12 * ui)
self.mini_panel.blit(x0 + m, y0 + dh - m)
def _draw_graphs(self, text: MiniText, x0: int, y0: int, dh: int) -> None:
"""The Graphs overlay in the top-left corner (drawn about 30 times a second: the graphs scroll)."""
if self._gpu is None:
from .gpustats import GpuStats
self._gpu = GpuStats()
ui = max(0.5, dh / 1080)
now = time.perf_counter()
if now - self._graph_drawn >= 1 / 30 or self._mini_state != ("graphs", round(ui, 3)):
self.mini_panel.update(_graphs(text, self._frametimes, ui, self._gpu))
self._graph_drawn, self._mini_state = now, ("graphs", round(ui, 3))
m = int(12 * ui)
self.mini_panel.blit(x0 + m, y0 + dh - m)
def _blit_text(self, text: str, x0: int, top: int, s: float) -> None:
GL = self.GL
if text != self._ov_text:
@@ -1510,6 +1630,8 @@ class GLWindowSink:
self.menu_panel.close()
self.toast_panel.close()
self.mini_panel.close()
if self._gpu is not None:
self._gpu.close()
if self.vsr is not None:
self._vsr_target_free()
self.vsr.close()
+8 -5
View File
@@ -434,8 +434,8 @@ class Pipeline:
proc = st.proc_interp_ms[n0:]
shown, skipped = st.quarter_shown - s0, st.quarter_skipped - k0
testing = settings is not None and settings.simulate_30
if settings is not None and settings.overlay_style == "minimal":
return mini_text(g, s, proc, shown, skipped, testing)
if settings is not None and settings.overlay_style in ("minimal", "graphs"):
return mini_text(g, s, proc, shown, skipped, testing, settings.overlay_style == "graphs")
rates = (f"game {g:.0f} fps{' evened out' if timed else ''}, showing {s:.0f}"
if g is not None and s is not None else "")
if not enabled:
@@ -452,7 +452,7 @@ class Pipeline:
text += "\n" + test_line()
return text
def mini_text(g, s, proc, shown: int, skipped: int, testing: bool) -> MiniText:
def mini_text(g, s, proc, shown: int, skipped: int, testing: bool, graphs: bool = False) -> MiniText:
"""Stats overlay style Minimal: frames on screen, the game's rate (amber while it's off the rate that's
needed, which the message about it explains), SmoovPlay's delay, and how well the PC keeps up: at 90 and
120 fps by the extra frames shown, at 60 by the AI's share of each frame's time."""
@@ -474,7 +474,9 @@ class Pipeline:
# Under the numbers, only while a test runs: the delay test, or test mode (with the advice, when the game
# isn't the 60 fps it needs; outside tests that advice is a message and the amber game rate).
second = (delay_test.status() if delay_test is not None else (note or test_line()) if testing else "")
return MiniText.make(parts, health, second)
graph = ({"hz": hz, "tick_ms": TICK * 1000, "busy": st.busy_ms[-300:], "delay": st.real_delay_ms[-300:]}
if graphs else None)
return MiniText.make(parts, health, second, graph)
for tick in source:
self.beat = time.perf_counter()
@@ -741,7 +743,8 @@ class Pipeline:
print(f"[pipeline] {advice}")
if hasattr(sink, "toast"):
sink.toast(advice, 8.0)
ov_text, ov_next = overlay_text(), t_ready + 0.25
ov_text = overlay_text()
ov_next = t_ready + (0.05 if getattr(ov_text, 'graph', None) else 0.25)
cmd = present(out, ov_text) or early_cmd
t_shown = time.perf_counter()
st.busy_ms.append((t_shown - t0) * 1000)
+6 -4
View File
@@ -275,13 +275,15 @@ SPECS: tuple[Spec, ...] = (
impact={"speed": "Low delay should save the 12 ms a window adds. Still being measured."}),
Spec("overlay", "Stats overlay", (True, False), True, ON_OFF, group="Display",
help="Numbers in a corner of the video: how many frames a second are on screen, the game's own frame rate, "
"and whether your PC keeps up. Key: S (Off, Minimal, Detailed)."),
Spec("overlay_style", "Stats overlay style", ("minimal", "detailed"), "minimal",
{"minimal": "Minimal", "detailed": "Detailed"}, group="Display", applies=("overlay", (True,)),
"and whether your PC keeps up. Key: S (Off, Minimal, Detailed, Graphs)."),
Spec("overlay_style", "Stats overlay style", ("minimal", "detailed", "graphs"), "minimal",
{"minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs"}, group="Display", applies=("overlay", (True,)),
hints={"minimal": "A small line: frames on screen, the game's frame rate, the delay, and a dot for how well "
"your PC keeps up.",
"detailed": "Everything: AI frame time, the upscaler, and at 90 and 120 fps the share of extra frames "
"shown."},
"shown.",
"graphs": "Like MangoHud: live graphs of frametime, the pipeline's time against its budget, delay and "
"the graphics card's load, with 1% lows."},
help="Minimal: frames on screen, the game's frame rate (amber when it isn't 30 fps) and the delay, with a "
"dot: green, your PC keeps up; amber, it's tight; red, it's falling behind, so try a lower frame rate. "
"Detailed adds the AI frame time, the upscaler and, at 90 and 120 fps, the extra frames shown (below "
+32
View File
@@ -0,0 +1,32 @@
"""The Graphs stats overlay (framegen/io._graphs) and the GPU reader's parsing: no window or GPU needed."""
import numpy as np
from framegen import io
from framegen.gpustats import GpuStats
def _text(**kw):
graph = {"hz": 120, "tick_ms": 16.7, "busy": [8 + (i % 7) for i in range(200)], "delay": [30 + (i % 20) for i in range(200)]}
return io.MiniText.make([("118 fps", "main"), ("game 30", "dim"), ("delay 35 ms", "dim")], "good", kw.get("second", ""), graph)
def test_graphs_draws_a_picture_that_grows_with_the_ui_scale():
ft = [8.3] * 150 + [25.0] * 3 + [8.3] * 100
a, b = io._graphs(_text(), ft, 1.0), io._graphs(_text(), ft, 2.0)
assert a.ndim == 3 and a.shape[2] == 3 and a.dtype == np.uint8
assert b.shape[0] > a.shape[0] * 1.8 and b.shape[1] > a.shape[1] * 1.8
def test_graphs_with_no_history_or_gpu_still_draws():
t = io.MiniText.make([("60 fps", "main")], "", "", {"hz": 60, "tick_ms": 16.7, "busy": [], "delay": []})
assert io._graphs(t, [], 1.0).size > 0
def test_a_test_line_makes_it_taller():
assert io._graphs(_text(second="TEST"), [8.3] * 50, 1.0).shape[0] > io._graphs(_text(), [8.3] * 50, 1.0).shape[0]
def test_gpu_line_parsing():
d = GpuStats.parse("97, 288.25, 61, 9120, 16303, 2737")
assert d == {"util": 97.0, "power": 288.25, "temp": 61.0, "mem": 9120.0, "mem_total": 16303.0, "clock": 2737.0}
assert GpuStats.parse("N/A, 1, 2, 3, 4, 5") is None and GpuStats.parse("") is None