diff --git a/engine/devtools/render_stats_samples.py b/engine/devtools/render_stats_samples.py new file mode 100644 index 0000000..dbea7ea --- /dev/null +++ b/engine/devtools/render_stats_samples.py @@ -0,0 +1,100 @@ +"""Renders every stats overlay style to PNG without a GPU or a window, from made-up numbers (clearly labelled on the +picture): `python devtools/render_stats_samples.py OUT_DIR [--ui 1.0]`. For looking at the layout and the colours; the +numbers are NOT measurements. tests/test_stats_hud.py builds the same data.""" +from __future__ import annotations + +import argparse +import pathlib +import sys +import types + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import numpy as np +from PIL import Image + +from framegen import hud, stats as S +from framegen.io import MiniText + +LABEL = "SAMPLE DATA, not measured" + + +def sample_collector(hz: int = 120, stutter: bool = True, seconds: float = 40.0, seed: int = 1) -> S.Collector: + """A collector fed 40 s of made-up frames at `hz` (a stutter now and then), stage times and system numbers.""" + rng = np.random.default_rng(seed) + c = S.Collector(window_s=30.0) + c.set_target(hz) + c.set_config(model="RIFE 4.22", frame_generation=True, multiplier=f"{hz // 30}x", hz=hz, upscaler="FSR 1", + quality="sharpness 0.5", output="2560x1440", source="1920x1080", look="none") + t, i = 1000.0, 0 + base = 1000.0 / hz + c.present(t, False) + while t < 1000.0 + seconds: + ms = base * (1 + 0.04 * rng.standard_normal()) + if stutter and rng.random() < 0.004: + ms = base * rng.uniform(2.0, 4.5) + t += ms / 1000.0 + i += 1 + c.present(t, i % 4 != 0) + c.tick(i % 2 == 0) + c.stage("capture", float(abs(rng.normal(0.4, 0.1))), t) + c.stage("interp", float(abs(rng.normal(5.2, 0.6))), t) + c.stage("upscale", float(abs(rng.normal(1.3, 0.1))), t) + c.stage("look", float(abs(rng.normal(0.2, 0.03))), t) + c.stage("present", float(abs(rng.normal(0.8, 0.2))), t) + c.drop(3, t - 5) + c.repeat(2, t - 8) + c.attach(types.SimpleNamespace(real_delay_ms=list(rng.normal(28, 4, 300)))) + c.sampler = types.SimpleNamespace(latest={"cpu": 34.0, "gpu": {"util": 87.0, "power": 232.0, "temp": 76.0, "mem": 7340.0, + "mem_total": 24576.0, "clock": 1890.0}}, + history=[{"cpu": 30.0 + k % 9, "gpu": {"util": 80.0 + k % 14, "power": 220.0 + k % 20, "temp": 70.0 + k % 7, + "mem": 7100.0 + k * 3, "mem_total": 24576.0}} for k in range(40)]) + return c + + +def text_for(c: S.Collector, style: str, colours: bool = True, items=None) -> MiniText: + snap = c.snapshot(game_fps=30.0) + items = items or S.wanted(style, lambda k: "auto") + parts = [(f"{snap['fps']:.0f} fps", "main"), ("game 30", "dim"), (f"delay {snap['delay']:.0f} ms", "dim")] + if style == "detailed": + head = [k for k in items if k in ("fps", "game", "delay")] + cells, rows = S.all_cells(snap, head, colours, True), S.all_cells(snap, [k for k in items if k not in head], colours, False) + else: + cells, rows = S.all_cells(snap, items, colours, True), () + graph = None + if style == "graphs": + rng = np.random.default_rng(3) + graph = {"hz": c.hz, "tick_ms": 16.7, "busy": list(rng.normal(9, 2, 300)), "delay": list(rng.normal(28, 5, 300)), + "show": None, "low1": snap["low1"], "low01": snap["low01"]} + return MiniText.make(parts, "good", LABEL, graph, cells=cells, rows=rows) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("out") + ap.add_argument("--ui", type=float, default=1.0) + a = ap.parse_args() + out = pathlib.Path(a.out) + out.mkdir(parents=True, exist_ok=True) + c = sample_collector() + rng = np.random.default_rng(2) + ft = list(np.abs(rng.normal(8.3, 0.4, 300))) + bg = np.full((1080, 1920, 4), (46, 70, 52, 255), np.uint8) # a plain "game" colour behind them + shots = {"minimal": hud.stats(text_for(c, "minimal"), a.ui, 0.8), "detailed": hud.stats(text_for(c, "detailed"), a.ui, 0.8), + "graphs": hud.graphs(text_for(c, "graphs"), ft, a.ui, 0.8), + "bar": hud.bar(text_for(c, "bar"), 1920, a.ui, 0.8)} + summ = c.summary(reason="sample data") + summ["benchmark"] = {"seconds": 40} + shots["card"] = hud.card(summ, a.ui, 0.96, "(sample data, not saved)") + for name, img in shots.items(): + canvas = bg.copy() + h, w = img.shape[:2] + x, y = (0, 0) if name == "bar" else (16, 16) if name != "card" else ((1920 - w) // 2, (1080 - h) // 2) + region = canvas[y:y + h, x:x + w] + a_ = img[..., 3:4].astype(np.float32) / 255 + region[..., :3] = (img[..., :3] * a_ + region[..., :3] * (1 - a_)).astype(np.uint8) + Image.fromarray(canvas[: max(y + h + 16, 120) if name != "card" else 1080, : (1920 if name in ("bar", "card") else x + w + 16)]).save(out / f"sample-{name}.png") + print(out / f"sample-{name}.png", img.shape) + + +if __name__ == "__main__": + main() diff --git a/engine/framegen/fsr.py b/engine/framegen/fsr.py index 1b11cf0..b2160b9 100644 --- a/engine/framegen/fsr.py +++ b/engine/framegen/fsr.py @@ -149,8 +149,9 @@ class FsrScaler: class GpuTimer: """Time GL work with timer queries, read back a few frames later so it never stalls the pipeline.""" - def __init__(self, GL, ring: int = 4) -> None: + def __init__(self, GL, ring: int = 4, on_sample=None) -> None: self.GL, self.ring = GL, ring + self.on_sample = on_sample # on_sample(label, ms) for each result, as it is read back self.queries = list(GL.glGenQueries(ring)) self.pending: list[tuple[int, str]] = [] # (query, label) in flight self.ms: dict[str, list[float]] = {} @@ -178,6 +179,8 @@ class GpuTimer: return ns = GL.glGetQueryObjectuiv(q, GL.GL_QUERY_RESULT) # 32-bit: fine below 4 s (PyOpenGL's ui64v is broken) self.ms.setdefault(label, []).append(int(ns) / 1e6) + if self.on_sample is not None: + self.on_sample(label, int(ns) / 1e6) self.pending.pop(0) def close(self) -> None: diff --git a/engine/framegen/hud.py b/engine/framegen/hud.py index 3631402..1998f40 100644 --- a/engine/framegen/hud.py +++ b/engine/framegen/hud.py @@ -1,14 +1,20 @@ """The performance overlay and the messages over the picture, as images (framegen/ui_draw.py draws them, the GL window -blits them): stats in three styles (settings "overlay_style": Minimal, Detailed, Graphs) and toast(). +blits them): stats in four styles (settings "overlay_style": Minimal, Detailed, Graphs, Bar), the benchmark's result card +and toast(). Each takes the pipeline's io.MiniText (its parts, health, second line, details and graph data), `ui` (1.0 at 1080p, times the settings' size) and `opacity` (how solid the background is; text and graph lines stay solid), and returns an RGBA image with rounded corners. + +The numbers come as io.MiniText.cells (framegen/stats.py Cell): each has a name, a value, a unit and a colour level, and a +`hint`, the widest the value gets. Every cell sits in a slot as wide as its hint, the value right-aligned in it, so the +overlay's size and its numbers' places don't change as digits do (digits are tabular in the fonts Summit uses). """ from __future__ import annotations import numpy as np +from . import stats as S from . import ui_draw as U PART = {"main": U.TEXT, "dim": U.DIM, "warn": U.TIGHT} # io.MiniText part kinds @@ -28,7 +34,158 @@ def _draw_parts(c: U.Canvas, x: int, y: int, parts, f_main, f_rest, gap: int) -> return x - gap +LEVEL = {"good": U.GOOD, "tight": U.TIGHT, "bad": U.BAD, "": U.TEXT} # stats.Cell.level -> the value's colour + + +class _Fonts: + def __init__(self, px) -> None: + self.val, self.name, self.unit = U.font(px(15), "semibold"), U.font(px(12)), U.font(px(12)) + self.row_val, self.row_name = U.font(px(13), "medium"), U.font(px(12)) + + +def _val_w(c, f) -> int: + """The width of a cell's value slot: its widest, so the slot never changes with the digits.""" + return max(U.text_w(c.value, f), U.text_w(c.hint, f)) + + +def _cell_w(c, f: _Fonts, sep: int) -> int: + w = _val_w(c, f.val) + if c.name: + w += U.text_w(c.name, f.name) + sep + if c.unit: + w += U.text_w(c.unit, f.unit) + max(1, sep // 3) + return w + + +def _draw_cell(cv: U.Canvas, x: int, y: int, c, f: _Fonts, sep: int) -> int: + """A cell on a line, left-middle at (x, y): its name, the value right-aligned in its slot, its unit. Returns its width.""" + x0 = x + if c.name: + x += cv.text(x, y, c.name, f.name, U.FAINT if c.key not in ("bench",) else U.TIGHT) + sep + vw = _val_w(c, f.val) + cv.text(x + vw, y, c.value, f.val, LEVEL.get(c.level, U.TEXT), "rm") + x += vw + if c.unit: + x += max(1, sep // 3) + x += cv.text(x, y + 1, c.unit, f.unit, U.DIM) + return x - x0 + + +def _flow(cells, f: _Fonts, sep: int, gap: int, room: int) -> list[list]: + """The cells as lines no wider than `room`.""" + lines, line, w = [], [], 0 + for c in cells: + cw = _cell_w(c, f, sep) + if line and w + gap + cw > room: + lines.append(line) + line, w = [], 0 + w += (gap if line else 0) + cw + line.append(c) + return lines + ([line] if line else []) + + +def _rows(rows, f: _Fonts, px, cv: U.Canvas | None, x0: int, y0: int, line_h: int, colw: list | None = None): + """Detailed's rows in one or two columns. With cv=None just measures: returns (width, height, column widths).""" + cols = [rows] if len(rows) <= 9 else [rows[: (len(rows) + 1) // 2], rows[(len(rows) + 1) // 2:]] + widths = [] + for col in cols: + nw = max((U.text_w(c.name, f.row_name) for c in col), default=0) + vw = max((max(U.text_w(c.value, f.row_val), U.text_w(c.hint, f.row_val)) + (U.text_w(c.unit, f.unit) + px(4) if c.unit else 0) + + (px(10) + U.text_w(c.detail_name, f.unit) + px(4) + max(U.text_w(c.detail, f.row_val), U.text_w("88.8", f.row_val)) + if c.detail_name else 0) for c in col), default=0) + widths.append((nw, vw)) + total = sum(nw + px(14) + vw for nw, vw in widths) + px(26) * (len(cols) - 1) + if cv is None: + return total, max(len(c) for c in cols) * line_h, widths + x = x0 + for col, (nw, vw) in zip(cols, widths): + for i, c in enumerate(col): + y = y0 + i * line_h + line_h // 2 + cv.text(x, y, c.name, f.row_name, U.FAINT) + vx = x + nw + px(14) + if c.key in ("config",) or (c.hint == "" and c.unit == ""): # words: left-aligned + cv.text(vx, y, c.value, f.row_val, U.DIM) + continue + num_w = max(U.text_w(c.value, f.row_val), U.text_w(c.hint, f.row_val)) + cv.text(vx + num_w, y, c.value, f.row_val, LEVEL.get(c.level, U.TEXT), "rm") + ex = vx + num_w + if c.unit: + ex += px(4) + cv.text(vx + num_w + px(4), y + 1, c.unit, f.unit, U.DIM) + if c.detail_name: + ex += px(10) + ex += cv.text(ex, y + 1, c.detail_name, f.unit, U.FAINT) + px(4) + dw = max(U.text_w(c.detail, f.row_val), U.text_w("88.8", f.row_val)) + cv.text(ex + dw, y, c.detail, f.row_val, U.DIM, "rm") + x += nw + px(14) + vw + px(26) + return total, max(len(c) for c in cols) * line_h, widths + + def stats(t, ui: float = 1.0, opacity: float = 1.0, details=()) -> np.ndarray: + """Minimal: a pill with a dot (green keeping up, yellow tight, red falling behind) and the numbers (t.cells), in + lines if there are many. A second line (the test line, while a test runs) goes under them. Detailed: the same + header with rows under it (t.rows, or `details`, (name, value) pairs, for the old kind of text).""" + cells, rows = getattr(t, "cells", None), list(getattr(t, "rows", None) or ()) + if cells is None: # numbers as parts, from a caller that has no cells + return _stats_parts(t, ui, opacity, details) + px = _px(ui) + f = _Fonts(px) + f_small = U.font(px(12)) + pad, gap, sep, r = px(13), px(13), px(5), px(5) + dot_w = 2 * r + px(9) + lines = _flow(cells, f, sep, gap, px(620) - dot_w) + second = U.wrap(t.second, f_small, px(520)) if t.second else [] + row_h, small_row = px(32), px(19) + line_w = max((sum(_cell_w(c, f, sep) for c in ln) + gap * (len(ln) - 1) for ln in lines), default=0) + dot_w + rows_w, rows_h = (_rows(rows, f, px, None, 0, 0, small_row)[:2]) if rows else (0, 0) + w = 2 * pad + max([line_w, rows_w] + [U.text_w(x, f_small) for x in second]) + head_h = row_h + (len(lines) - 1) * px(26) + extra = rows_h + len(second) * small_row + h = head_h + (extra + px(10) + (px(6) if rows and second else 0) if extra else 0) + c = U.Canvas(w, h, U.BG, row_h // 2 if not extra and len(lines) <= 1 else px(12), border=U.BORDER) + c.circle(pad + r, row_h // 2, r, U.HEALTH.get(t.health, U.FAINT)) + for i, ln in enumerate(lines): + x, y = pad + dot_w, row_h // 2 + i * px(26) + for cell in ln: + x += _draw_cell(c, x, y, cell, f, sep) + gap + y = head_h - px(2) + if rows: + c.line(pad, y, w - pad, y, U.BORDER, 1) + _rows(rows, f, px, c, pad, y + px(5), small_row) + y += rows_h + px(10) + elif extra: + y += px(8) + y += px(6) if rows and second else 0 + for s in second: + c.text(pad, y + small_row // 2, s, f_small, U.TIGHT) + y += small_row + return c.rgba(opacity) + + +def bar(t, width: int, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray: + """The Bar style: one line as wide as the picture (`width`), the dot and then the cells (t.cells) with thin dividers, + as many as fit: the last ones are left out when the picture is narrow.""" + px = _px(ui) + f = _Fonts(px) + pad, gap, sep, r = px(14), px(14), px(5), px(5) + h = px(30) + c = U.Canvas(max(1, width), h, U.BG, 0, border=None) + c.circle(pad + r, h // 2, r, U.HEALTH.get(t.health, U.FAINT)) + x = pad + 2 * r + px(10) + shown = 0 + for cell in t.cells: + cw = _cell_w(cell, f, sep) + if x + cw + pad > width: + break + if shown: + c.line(x - gap // 2, px(8), x - gap // 2, h - px(8), U.BORDER, 1) + x += _draw_cell(c, x, h // 2, cell, f, sep) + gap + shown += 1 + if t.second: # a test's line, if there is room: at the right end + c.text(width - pad, h // 2, U.fit(t.second, U.font(px(12)), max(0, width - x - pad)), U.font(px(12)), U.TIGHT, "rm") + return c.rgba(opacity) + + +def _stats_parts(t, ui: float = 1.0, opacity: float = 1.0, details=()) -> np.ndarray: """Minimal: a pill with a dot (green keeping up, yellow tight, red falling behind) and a few numbers. A second line (the test line, while a test runs) goes under them. Detailed: the same with `details`, (name, value) rows, under it.""" @@ -98,7 +255,7 @@ def graphs(t, frametimes, ui: float = 1.0, opacity: float = 1.0, gpu=None) -> np g = t.graph f_big, f_main, f_rest = U.font(px(26), "bold"), U.font(px(15), "semibold"), U.font(px(13)) f_name, f_num = U.font(px(12), "semibold"), U.font(px(12)) - pad, gw, gh, gap = px(14), px(300), px(44), px(10) + pad, gw, gh, gap = px(14), px(320), px(44), px(10) target = 1000.0 / max(1, g.get("hz", 60)) tick = g.get("tick_ms", 1000 / 60) ft = list(frametimes)[-gw:] @@ -139,8 +296,9 @@ def graphs(t, frametimes, ui: float = 1.0, opacity: float = 1.0, gpu=None) -> np if series: last, avg = series[-1], sum(series) / len(series) if name == "Frametime": - p99 = sorted(series)[min(len(series) - 1, int(0.99 * len(series)))] - text = f"{last:.1f} ms avg {avg:.1f} 1% low {1000.0 / max(p99, 0.1):.0f} fps" + l1, l01 = (g["low1"], g["low01"]) if "low1" in g else S.lows(series) # the collector's window, if given + dash = lambda v: "--" if v is None else f"{v:.0f}" # noqa: E731 + text = f"avg {avg:.1f} ms 1% low {dash(l1)} 0.1% {dash(l01)}" elif name == "Pipeline": text = f"{last:.1f} ms avg {avg:.1f} budget {tick:.1f}" else: @@ -166,6 +324,67 @@ def graphs(t, frametimes, ui: float = 1.0, opacity: float = 1.0, gpu=None) -> np return c.rgba(opacity, (U.SURFACE,)) +def card(summary: dict, ui: float = 1.0, opacity: float = 1.0, saved: str = "") -> np.ndarray: + """The benchmark's result card (and the session summary's): the big numbers, then the rest in a table. summary is + framegen.stats.Collector.summary(); `saved` is where the files went.""" + px = _px(ui) + f_title, f_big = U.font(px(20), "bold"), U.font(px(34), "bold") + f_lab, f_row, f_val = U.font(px(12)), U.font(px(13)), U.font(px(14), "semibold") + pad, w = px(24), px(680) + fr, ft = summary["frames"], summary["frametime"] + sy, d = summary["system"], summary.get("delay") + v = lambda x, nd=0, unit="": "--" if x is None else f"{x:.{nd}f}{unit}" # noqa: E731 + big = [("average", v(summary["fps_avg"]), "fps"), ("1% low", v(ft["low1_fps"]), "fps"), + ("0.1% low", v(ft["low01_fps"]), "fps"), ("frametime", v(ft["avg_ms"], 1), "ms")] + rows = [("Worst frametime / jitter", f"{v(ft['worst_ms'], 1)} ms / {v(ft['jitter_ms'], 2)} ms"), + ("Dropped / repeated / late", f"{fr['dropped']} / {fr['repeated']} / {fr['late']} of {fr['presented']} frames"), + ("Generated share, game's rate", f"{v(fr['generated_share_pct'])}%, {v(fr['game_fps_avg'])} fps"), + ("Delay (median / 95th)", "--" if not d else f"{v(d['median_ms'])} ms / {v(d['p95_ms'])} ms")] + for name in S.STAGES: + st = summary["stages"].get(name) + if st: + rows.append((S.STAGE_NAMES[name], f"{st['avg_ms']:.2f} ms avg, {st['worst_ms']:.1f} ms worst")) + rows.append(("Graphics card", f"{v(sy['gpu_util_avg_pct'])}% load, {v(sy['gpu_temp_max_c'])} C max, " + f"{v(sy['gpu_power_avg_w'])} W, {v(sy['vram_max_mb'] and sy['vram_max_mb'] / 1024, 1)} GB")) + sub = S.config_line(summary["config"]) or "settings unknown" + sub_lines = U.wrap(sub, f_lab, w - 2 * pad) + bench = summary.get("benchmark") + title = f"Benchmark result: {bench['seconds']} s" if bench else "Session summary" + row_h, big_h = px(24), px(78) + h = px(18) + px(30) + len(sub_lines) * px(18) + px(10) + big_h + px(8) + len(rows) * row_h + px(14) + (px(24) if saved else 0) + c = U.Canvas(w, h, U.BG, px(16), border=U.BORDER) + c.logo(pad, px(18), px(24)) + y = px(18) + px(12) + c.text(pad + px(34), y, title, f_title, U.TEXT) + c.text(w - pad, y, f"{_clock(summary['duration_s'])} played", f_lab, U.DIM, "rm") + y += px(24) + for line in sub_lines: + c.text(pad, y, line, f_lab, U.DIM) + y += px(18) + y += px(10) + cw = (w - 2 * pad) // len(big) + for i, (name, val, unit) in enumerate(big): + x = pad + i * cw + c.rrect(x, y, x + cw - px(8), y + big_h, px(10), fill=U.SURFACE, outline=U.BORDER) + c.text(x + px(12), y + px(14), name, f_lab, U.FAINT) + n = c.text(x + px(12), y + px(46), val, f_big, U.TEXT) + c.text(x + px(12) + n + px(6), y + px(52), unit, f_lab, U.DIM) + y += big_h + px(8) + for name, text in rows: + y += row_h + c.text(pad, y - row_h // 2, name, f_row, U.FAINT) + c.text(w - pad, y - row_h // 2, text, f_val, U.TEXT, "rm") + c.line(pad, y, w - pad, y, U.BORDER, 1) + if saved: + c.text(pad, h - px(22), U.fit("Saved: " + saved, f_lab, w - 2 * pad), f_lab, U.DIM) + return c.rgba(opacity) + + +def _clock(seconds: float) -> str: + s = int(round(seconds)) + return f"{s // 60}:{s % 60:02d}" + + def toast(text: str, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray: """A short message (one line, or a few split by newlines) on a rounded card with Summit's mark.""" px = _px(ui) diff --git a/engine/framegen/io.py b/engine/framegen/io.py index e0aa580..b012947 100644 --- a/engine/framegen/io.py +++ b/engine/framegen/io.py @@ -516,14 +516,17 @@ class MiniText(str): second: str = "" graph: dict | None = None # the Graphs overlay's data (pipeline: hz, tick_ms, busy, delay), else None details: tuple | None = None + cells: tuple | None = None # framegen.stats.Cell numbers for the line (Minimal, Bar, Detailed's header); None: parts + rows: tuple = () # Detailed's rows under the line (stats.Cell) @classmethod def make(cls, parts, health: str = "", second: str = "", graph: dict | None = None, details=None, - plain: str | None = None) -> "MiniText": + plain: str | None = None, cells=None, rows=()) -> "MiniText": """plain: the text for sinks that only print (default: the parts in a line, then `second`).""" t = cls(plain if plain is not None else " ".join(x for x, _ in parts) + (f"\n{second}" if second else "")) t.parts, t.health, t.second, t.graph = tuple(parts), health, second, graph t.details = tuple(details) if details is not None else None + t.cells, t.rows = (tuple(cells) if cells is not None else None), tuple(rows) return t @@ -707,7 +710,10 @@ class GLWindowSink: details = {"fsr": f" (sharpness {sharpness:g})", "vsr": f" (quality {vsr_quality})", "bilinear": "", "off": ""} print(f"[display] upscaling with {self._name(self.mode)}{details[self.mode]}; u cycles " + " / ".join(self._name(m) for m in self.modes)) - self.timer = GpuTimer(GL) # GPU time of the scale/draw step, reported on close + self.collector = None # framegen.stats.Collector (run.py sets it): the stage times go there + self._cfg_seen, self._vsr_seen = None, 0 + self.timer = GpuTimer(GL, on_sample=self._gl_sample) # GPU time of the scale/draw step, reported on close + self.look_timer = GpuTimer(GL, on_sample=lambda label, ms: self._stage("look", ms)) # ...and of the look # Looks: which one is on (the settings, or the launcher's Looks page while it edits one) and its drawing. from .looks import LookState @@ -743,6 +749,7 @@ class GLWindowSink: self.mini_panel, self._mini_state = _Panel(GL, self.hdr10), None self.wm_panel, self._wm_state = _Panel(GL, self.hdr10), None # the Summit watermark self._frametimes, self._last_write, self._graph_drawn, self._gpu = collections.deque(maxlen=480), 0.0, 0.0, None + self._gpu_own = False self._menu_top = None # (GL y of the menu's top, the picture's (y0, height) it was placed in, on the left?) while open self._menu_at = None # (x, GL y of the top) the menu was last drawn at, for the mouse self._menu_off = (0, 0) # where the player dragged the overlay to, from where it opens (framebuffer px; kept @@ -1426,6 +1433,55 @@ class GLWindowSink: self._borderless = on _say_if_slow("borderless fullscreen " + ("on" if on else "off"), t0) + def _stage(self, name: str, ms: float) -> None: + if self.collector is not None: + self.collector.stage(name, ms) + + def _gl_sample(self, label: str, ms: float) -> None: + if "RTX VSR" not in label: # (RTX VSR's own time is read from its CUDA events: see _report_config) + self._stage("upscale", ms) + + def _report_config(self, mode: str, out: tuple[int, int]) -> None: + """What the picture is made with, in words, for the stats overlay (only when it changes).""" + c = self.collector + if c is None: + return + st = self.settings + quality = {"fsr": f"sharpness {st.fsr_sharpness:g}", "vsr": f"quality {st.vsr_quality}"}.get(mode) + key = (mode, quality, out, st.look_on and st.look) + if key != self._cfg_seen: + self._cfg_seen = key + c.set_config(upscaler=self.NAMES[mode], + quality=quality, look=self.looks.name() or "none", + output=f"{out[0]}x{out[1]}", source=f"{self.w}x{self.h}") + if mode == "vsr" and self.vsr is not None: # RTX VSR's time: CUDA events, read as they finish + for ms in self.vsr.gpu_ms[self._vsr_seen:]: + c.stage("upscale", ms) + self._vsr_seen = len(self.vsr.gpu_ms) + + def show_card(self, make, seconds: float) -> None: + """A card in the middle of the last picture for `seconds`, the window answering its keys meanwhile (Ctrl+Q quits). + make(ui) -> the card as an RGBA image (hud.card), `ui` being the size to draw it at for this picture.""" + GL = self.GL + panel = _Panel(GL, self.hdr10) + panel.update_rgba(make(max(0.5, self._layout()[4] / 1080))) + end = time.perf_counter() + seconds + self.menu.open, self._toast_until = False, 0.0 + while time.perf_counter() < end and not self.glfw.window_should_close(self.win) and self.cmd != "quit": + fw, fh, s, dw, dh, x0, y0 = self._layout() + GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self._target()) + GL.glViewport(0, 0, fw, fh) + GL.glClear(GL.GL_COLOR_BUFFER_BIT) + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo) + GL.glBlitFramebuffer(0, 0, self.w, self.h, x0, y0 + dh, x0 + dw, y0, GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR) + ux, uy, uw, uh = self._ui_rect(fw, fh, dw, dh, x0, y0) + panel.blit(ux + max(0, (uw - panel.w) // 2), uy + (uh + panel.h) // 2, self._target()) + self._present() + self._events() + self.settle() + time.sleep(0.03) + panel.close() + def toast(self, text: str, seconds: float = 2.0) -> None: """A short message in the top-right corner.""" self._toast_text, self._toast_until = text, time.perf_counter() + seconds @@ -1440,7 +1496,7 @@ class GLWindowSink: elif r in ("restart", "quit"): self.menu.open = False self.cmd = r - elif r == "save_replay": + elif r in ("save_replay", "save_summary"): self.cmd = r def _do(self, action: str) -> None: @@ -1455,7 +1511,7 @@ class GLWindowSink: st.set("fullscreen", not st.fullscreen) elif action == "smooth": st.override("interp", not st.interp) # a quick A/B, not saved - elif action == "stats": # Off, Minimal, Detailed, Graphs, Off... + elif action == "stats": # Off, Minimal, Detailed, Graphs, Bar, Off... if not st.overlay: st.set("overlay_style", "minimal") st.set("overlay", True) @@ -1463,6 +1519,8 @@ class GLWindowSink: st.set("overlay_style", "detailed") elif st.overlay_style == "detailed": st.set("overlay_style", "graphs") + elif st.overlay_style == "graphs": + st.set("overlay_style", "bar") else: st.set("overlay", False) @@ -1517,6 +1575,8 @@ class GLWindowSink: self.cmd = "save_replay" # instant replay (framegen/replay.py), through the pipeline elif key == glfw.KEY_B: self.cmd = "save_compare" + elif key == glfw.KEY_P: + self.cmd = "save_summary" # the session's numbers to a file (framegen/stats.py), through the pipeline # ---- drawing ------------------------------------------------------------- def _layout(self) -> tuple[int, int, float, int, int, int, int]: @@ -1690,6 +1750,7 @@ class GLWindowSink: if self.overlay_of is not None: self._follow() on_gpu = _is_cuda(frame) and self.interop is not None + t_up = time.perf_counter() if on_gpu: self.interop.upload(frame) else: @@ -1697,6 +1758,7 @@ class GLWindowSink: host = np.ascontiguousarray(_host(frame)) GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self.w, self.h, GL.GL_BGR, GL.GL_HALF_FLOAT if host.dtype == np.float16 else GL.GL_UNSIGNED_BYTE, host) + t_up = time.perf_counter() - t_up fw, fh, s, dw, dh, x0, y0 = self._layout() target = screen = self._target() GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target) @@ -1725,6 +1787,7 @@ class GLWindowSink: ow, oh = round(self.w * k), round(self.h * k) x0, y0, dw, dh = x0 + (dw - ow) // 2, y0 + (dh - oh) // 2, ow, oh upscale = dw > self.w or dh > self.h + out_px = (dw, dh) # the size the picture is drawn at, for the stats' words if mode == "vsr" and not on_gpu: # a CPU frame: VSR needs it on the GPU mode = "fsr" if self.fsr is not None else "bilinear" ss = SUPERSAMPLE if (mode == "vsr" and not upscale) else 1.0 @@ -1743,7 +1806,11 @@ class GLWindowSink: src, flip_in = self.vsr_out[0], False else: src, flip_in = self.tex, False # the look's first pass resizes it + self.timer.end(q, f"{label} (upscale)") # (the look has its own query: they can't overlap) + lq = self.look_timer.begin() self.look_gl.draw(plan, src, flip_in, target, x0, y0, dw, dh, True, self._frame_no) + self.look_timer.end(lq, "look") + q = None GL.glViewport(0, 0, fw, fh) label += " + look" elif upscale and mode == "fsr": @@ -1768,6 +1835,7 @@ 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}") + self._report_config(mode if upscale else "off", out_px) if isinstance(text, MiniText) and self.menu.open and now - self._status_at >= 1.0 and text.parts: self._status_at = now # the overlay's header: the same numbers, once a second self.menu.status = (text.health, text.parts[0][0], " \u00b7 ".join(x for x, _ in text.parts[1:])) @@ -1781,7 +1849,9 @@ class GLWindowSink: if self.settings.watermark: self._draw_watermark(ux, uy, uw, uh) self._draw_ui(ux, uy, uw, uh) + t_pr = time.perf_counter() self._present() + self._stage("present", (time.perf_counter() - t_pr + t_up) * 1000) # upload and swap (with vsync: and the wait) self.settle() self._events() if self.remote is not None: @@ -1884,21 +1954,33 @@ class GLWindowSink: def _draw_stats(self, text: MiniText, picture: str, x0: int, y0: int, dw: int, dh: int) -> None: """The Minimal or Detailed stats in a corner, at the screen's own size (drawn again only when they change). picture: the upscaler and the size it draws at, a row of Detailed.""" - from .hud import stats + from .hud import bar, stats ui = self._stats_ui(dh) - details = (*text.details, ("Picture", picture)) if text.details is not None else () - state = (text.parts, text.health, text.second, details, round(ui, 3), self.settings.overlay_opacity) + style = self.settings.overlay_style + details = (*text.details, ("Picture", picture)) if text.details is not None and text.cells is None else () + state = (text.parts, text.health, text.second, details, text.cells, text.rows, style, round(ui, 3), + self.settings.overlay_opacity, dw if style == "bar" else 0) if state != self._mini_state: - self.mini_panel.update_rgba(stats(text, ui, self.settings.overlay_opacity, details)) + img = (bar(text, dw, ui, self.settings.overlay_opacity) if style == "bar" and text.cells is not None + else stats(text, ui, self.settings.overlay_opacity, details)) + self.mini_panel.update_rgba(img) self._mini_state = state - self._blit_corner(self.mini_panel, x0, y0, dw, dh, ui) + if style == "bar" and text.cells is not None: # along the top or bottom edge, the picture's width + p = self.mini_panel + p.blit(x0, y0 + p.h if self.settings.bar_position == "bottom" else y0 + dh, self._target()) + else: + self._blit_corner(self.mini_panel, x0, y0, dw, dh, ui) def _draw_graphs(self, text: MiniText, x0: int, y0: int, dw: int, dh: int) -> None: """The Graphs overlay in a corner (drawn about 30 times a second: the graphs scroll).""" from .hud import graphs if self._gpu is None and self.settings.graph_gpu: - from .gpustats import GpuStats - self._gpu = GpuStats() + shared = getattr(getattr(self.collector, "sampler", None), "gpu", None) # the stats' own, if it has one + if shared is not None: + self._gpu = shared + else: + from .gpustats import GpuStats + self._gpu, self._gpu_own = GpuStats(), True ui = self._stats_ui(dh) now = time.perf_counter() key = ("graphs", round(ui, 3), self.settings.overlay_opacity) @@ -1916,7 +1998,10 @@ class GLWindowSink: self.wm_panel.update_rgba(wm.render_rgba(ui)) self._wm_state = round(ui, 3) p = self.wm_panel - x, top = wm.place(wm.corner(self.settings.overlay_corner, bool(self.overlay)), p.w, p.h, x0, y0, dw, dh, + where = wm.corner(self.settings.overlay_corner, bool(self.overlay)) + if self.overlay and self.settings.overlay_style == "bar" and self.settings.bar_position == "bottom": + where = "top-left" # the bar has the bottom edge + x, top = wm.place(where, p.w, p.h, x0, y0, dw, dh, int(12 * ui)) p.blit(x, top, self._target()) @@ -2019,8 +2104,9 @@ class GLWindowSink: self.menu_panel.close() self.toast_panel.close() self.mini_panel.close() - if self._gpu is not None: + if self._gpu is not None and self._gpu_own: self._gpu.close() + self.look_timer.close() if self.vsr is not None: self._vsr_target_free() self.vsr.close() diff --git a/engine/framegen/menu.py b/engine/framegen/menu.py index bf5187b..dbd612a 100644 --- a/engine/framegen/menu.py +++ b/engine/framegen/menu.py @@ -33,15 +33,18 @@ HOME = "Home" TAB_NAMES: dict[str, str] = {} # shorter names for the tab strip, if a section's is too long PERF = "perf" # Home's "Performance overlay": the settings "overlay" and "overlay_style" as one row -PERF_CHOICES = ("off", "minimal", "detailed", "graphs") -PERF_NAMES = {"off": "Off", "minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs"} +PERF_CHOICES = ("off", "minimal", "detailed", "graphs", "bar") +PERF_NAMES = {"off": "Off", "minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs", "bar": "Bar"} PERF_HELP = ("Live numbers in a corner of the picture. Minimal: frames on screen, the game's own frame rate, the delay, " "and a dot for how well your PC keeps up. Detailed adds the AI's time per frame and the upscaler. Graphs " - "draws frametime, the pipeline's time, delay and the graphics card's load over time. Its corner, size and " - "opacity are on the Display tab.") + "draws frametime, the pipeline's time, delay and the graphics card's load over time. Bar is one line along the " + "top or bottom edge. Which numbers show, and the corner, size and colours, are on the Overlay tab.") ACTION_HELP = { "restart": "Restarts Summit's pipeline with the new settings. The game keeps running; it takes a few seconds.", "clip": "Saves what you just played to your Videos folder. Ctrl+Alt+R does the same without opening this.", + "summary": "Writes this session's numbers so far (averages, lows, the time of each stage, the settings and what " + "changed) to a .json and a .txt file in Summit's data folder, and shows where. Summit also does it when " + "it stops.", } QUIT_HELP = "Closes Summit's picture. A game started from Summit's launcher is closed with it." @@ -144,6 +147,7 @@ class Menu: if tab is None: if values.get("replay"): rows.append(Row("action", "clip", "Save a clip")) + rows.append(Row("action", "summary", "Save a stats summary")) rows.append(Row("action", "quit", self.quit_label)) return rows @@ -267,6 +271,8 @@ class Menu: return "restart" if row.key == "clip": return "save_replay" + if row.key == "summary": + return "save_summary" if self.armed: self.armed = False return "quit" diff --git a/engine/framegen/pipeline.py b/engine/framegen/pipeline.py index eeae360..1332ee7 100644 --- a/engine/framegen/pipeline.py +++ b/engine/framegen/pipeline.py @@ -9,7 +9,7 @@ from dataclasses import dataclass, field import numpy as np import torch -from . import delaytest +from . import delaytest, stats as stat_lib from .cadence import Action, CadenceScheduler, CutDetector, DipWatch, DuplicateDetector, FrameTimeline, RhythmLock from .hdr import level8, to_u8 from .interpolator import STEADY_HUD_THRESHOLD, RifeInterpolator @@ -355,7 +355,8 @@ class Pipeline: self.waiting = None # the source's Waiting while no frame is coming, else None (the watchdog reads it too) def run(self, source, sink=None, enabled: bool = True, score: bool = False, label: str = "", - on_tick=None, hz: int = 60, settings=None, gt=None, remote=None, replay=None) -> Stats: + on_tick=None, hz: int = 60, settings=None, gt=None, remote=None, replay=None, + collector: "stat_lib.Collector | None" = None) -> Stats: """on_tick(tick, diff, action, proc_ms, t_start), if given, is called after each tick is processed. remote: the source, when it can press a button for the delay test (L: PS5 Remote Play's chiaki-ng, framegen.chiaki_tap.ChiakiSource) or hold its sound back to meet the picture (settings.audio_sync: chiaki-ng, @@ -366,6 +367,8 @@ class Pipeline: `enabled` and `hz`. replay (framegen.replay.Recorder): instant replay. It gets every frame shown, each new frame from the game and the pipeline's delay, and the window's R and B keys save it. + collector (framegen.stats.Collector): the stats overlay's numbers and the session summary's; one for a whole + run of the engine (run.py makes it), so it outlives a restart. Without one, this run keeps its own. hz=120 or 90 (needs a sink): more generated frames per 30 fps frame, shown at least 1/hz apart. 120: a new frame B after A shows A->B at 1/4 then 1/2; its repeat tick shows 3/4 then B. @@ -379,6 +382,11 @@ class Pipeline: it, sched, st = self.interp, CadenceScheduler(), Stats(private=bool(getattr(self.interp, "private", False))) steady = None # Steady HUD as last applied to the interpolator (followed live from settings) self.stats = st + coll = collector if collector is not None else stat_lib.Collector() + coll.attach(st) + coll.set_target(hz) + if settings is not None: + coll.set_window(settings.stats_window) quarter_due = False # 120 Hz: the previous tick interpolated, so this repeat tick owes the 3/4 frame behind_ms = 1000 * TICK * 0.6 # start-of-tick lag above which the extra frames are skipped gap = 0.95 / hz # time between two presents, 5% short so the schedule has slack to catch up @@ -423,6 +431,13 @@ class Pipeline: off_since: float | None = None # since when the game has been off the rate that's needed note, toasted = "", set() + def ai(slot_: int, t_: float): + """A generated frame, waited for, its time to the stats.""" + a = time.perf_counter() + frame = self._generated(it.interpolate(slot_, t_), gpu_out) + coll.stage("interp", (time.perf_counter() - a) * 1000, a) + return frame + def test_line() -> str: """Test mode's badge, and quality over the last ~30 scored frames (about a second). 90 fps draws frames at 1/3 and 2/3, where a 60 fps game has no real frame to compare against.""" @@ -443,7 +458,7 @@ 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 in ("minimal", "graphs"): + if settings is not None and settings.overlay_style in ("minimal", "graphs", "bar"): 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 "") @@ -467,12 +482,18 @@ class Pipeline: if hz > 60 and shown + skipped: details.append(("Extra frames shown", f"{100 * shown / (shown + skipped):.0f}%")) m = mini_text(g, s, proc, shown, skipped, testing) - return MiniText.make(m.parts, m.health, second, details=details, plain=text) + return MiniText.make(m.parts, m.health, m.second, details=details, plain=text, cells=m.cells, rows=m.rows) 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.""" + coll.set_config(frame_generation=enabled, hz=hz, + multiplier=f"{settings.hz // 30}x" if settings is not None else None) + coll.poll() + snap = coll.snapshot(game_fps=g) + if snap["fps"] is not None: + s = snap["fps"] # one frame rate for the numbers and the overlay's header parts = [(f"{s:.0f} fps" if s is not None else f"{hz} fps", "main")] if g is not None: parts.append((f"game {g:.0f}", "warn" if note else "dim")) @@ -494,13 +515,31 @@ class Pipeline: show = [k for k, on in (("frametime", settings.graph_frametime), ("pipeline", settings.graph_pipeline), ("delay", settings.graph_delay), ("gpu", settings.graph_gpu)) if on] if graphs else None graph = ({"hz": hz, "tick_ms": TICK * 1000, "busy": st.busy_ms[-300:], "delay": st.real_delay_ms[-300:], - "show": show} if graphs else None) - return MiniText.make(parts, health, second, graph) + "show": show, "low1": snap["low1"], "low01": snap["low01"]} if graphs else None) + left = coll.bench_left() + if left is not None and graphs and not second: # (the other styles have it as a number) + second = f"Benchmark: {int(left) // 60}:{int(left) % 60:02d} left" + cells, rows = None, () + if settings is not None and not graphs: + items = stat_lib.wanted(settings.overlay_style, lambda k: getattr(settings, "stat_" + k)) + colours = settings.overlay_colours + if settings.overlay_style == "detailed": # the line (fps, game, delay), then a row for each of the rest + head = [i for i in items if i in ("fps", "game", "delay")] + cells = stat_lib.all_cells(snap, head, colours, True, bool(note)) + rows = stat_lib.all_cells(snap, [i for i in items if i not in head], colours, False) + else: + cells = stat_lib.all_cells(snap, items, colours, True, bool(note)) + if left is not None: + cells = [stat_lib.bench_cell(left), *cells] + return MiniText.make(parts, health, second, graph, cells=cells, rows=rows) for tick in source: self.beat = time.perf_counter() if isinstance(tick, Waiting): # no frame for a moment: keep the window answering until one comes self.waiting = tick + if coll.bench_over(time.perf_counter()): + st.exit = "end" + break if sink is not None and hasattr(sink, "wait"): cmd = sink.wait(tick) if cmd in ("quit", "restart"): @@ -517,6 +556,7 @@ class Pipeline: if want_hz != hz: hz, gap, quarter_due, ov_next = want_hz, 0.95 / want_hz, False, 0.0 st.hz_used.add(hz) + coll.set_target(hz) if replay is not None and hasattr(replay, "set_output_hz"): replay.set_output_hz(hz) print(f"[pipeline] output {hz} Hz") @@ -539,6 +579,7 @@ class Pipeline: print(f"[pipeline] steady HUD {'ON' if steady else 'OFF'}") t0 = time.perf_counter() st.queue_ms.append((t0 - tick.t_arrival) * 1000) + coll.stage("capture", st.queue_ms[-1], t0) if torch.is_tensor(tick.frame): # already on the GPU (hardware decoder) it.load(tick.frame) else: @@ -571,6 +612,7 @@ class Pipeline: rhythm_note = t0 + 10.0 print(f"[pipeline] 30 fps: the game's frames moved by a tick ({rhythm_moves} so far)") seen_rate.add(is_new) + coll.tick(is_new) # In test mode the source's own word on the game's frame (TestMode puts it in extra["game_new"]). game_new = tick.extra["game_new"] if "game_new" in tick.extra else is_new game_rate.add(game_new) @@ -620,7 +662,7 @@ class Pipeline: st.behind += behind extra_ok = hz > 60 and sink is not None and not behind - def present(frame, text: str): + def present(frame, text: str, generated: bool = False): # Frame pacer: each present is due one gap after the previous one was *due*, so sleep overshoot and # present time don't accumulate; when late it goes straight away and the schedule restarts from now. nonlocal next_due @@ -632,6 +674,7 @@ class Pipeline: cmd = sink.write(frame, text) t_now = time.perf_counter() shown_rate.add(t_now) + coll.present(t_now, generated) if replay is not None: replay.frame(frame, t_now) # after it's on screen, so it adds no delay return cmd @@ -640,8 +683,9 @@ class Pipeline: nonlocal early_cmd if not extra_ok: st.quarter_skipped += 1 + coll.drop(1, time.perf_counter()) return False - early_cmd = present(self._generated(it.interpolate(slot, t), gpu_out), ov_text) or early_cmd + early_cmd = present(ai(slot, t), ov_text, True) or early_cmd st.quarter_shown += 1 return True @@ -705,6 +749,7 @@ class Pipeline: phases = timeline.slots(hz) if len(phases) > 1 and not extra_ok: st.quarter_skipped += len(phases) - 1 + coll.drop(len(phases) - 1, time.perf_counter()) phases = phases[-1:] else: st.quarter_shown += len(phases) - 1 @@ -714,10 +759,11 @@ class Pipeline: frame = pl.a.frame else: slot = self._timed_pair(pl.a, pl.b, slot, in_slot) - frame = self._generated(it.interpolate(slot, pl.t), gpu_out) + frame = ai(slot, pl.t) st.uneven_waits += pl.waiting + coll.repeat(int(pl.waiting), time.perf_counter()) if k < len(phases) - 1: - early_cmd = present(frame, ov_text) or early_cmd + early_cmd = present(frame, ov_text, pl.b is not None) or early_cmd t_now = time.perf_counter() st.real_delay_ms.extend((t_now - f.t_arrival) * 1000 for f in pl.reached) else: @@ -741,7 +787,7 @@ class Pipeline: if timed: pass # shown above elif action is Action.INTERP: - out = self._generated(it.interpolate(slot, mid_t), gpu_out) + out = ai(slot, mid_t) # --score has ground truth only at the midpoint if gt_fn is not None and key_gpu is not None and mid_t == 0.5: to_score = (key_frame, key_content) # scored once the frame is on screen @@ -786,7 +832,7 @@ class Pipeline: sink.toast(advice, 8.0) 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 + cmd = present(out, ov_text, action is Action.INTERP) or early_cmd t_shown = time.perf_counter() st.busy_ms.append((t_shown - t0) * 1000) if sink is not None: @@ -815,10 +861,17 @@ class Pipeline: self._score(st, tick, prev_key, *to_score, gt_fn, keep_worst=score) st.score_ms.append((time.perf_counter() - t_shown) * 1000) + if coll.bench_over(t_shown): # a benchmark's time is up + st.exit = "end" + break if sink is not None: if cmd in ("quit", "restart"): st.exit = cmd break + if cmd == "save_summary": # P, or the overlay's Save a stats summary + msg = coll.save_hook("asked for") if coll.save_hook is not None else None + if hasattr(sink, "toast"): + sink.toast(msg or "Saving a summary isn't available here", 5.0) if cmd == "delay_test" and delay_test is None: if remote is None or not remote.can_press(): msg = ("The delay test works with PS5 Remote Play, through the chiaki-ng that comes with this " diff --git a/engine/framegen/settings.py b/engine/framegen/settings.py index 941a923..bff129f 100644 --- a/engine/framegen/settings.py +++ b/engine/framegen/settings.py @@ -17,7 +17,7 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable -from . import fill, looks, oslayer +from . import fill, looks, oslayer, stats DEFAULT_PATH = oslayer.config_dir() / "settings.json" # %APPDATA%\\framegen (Windows), ~/.config/smoovplay (Linux) @@ -105,6 +105,15 @@ IMPACT_PC = "an RTX 4070 Ti SUPER" # where the numbers in `impact` and the hint LOOK_SPEED = "About 0.02 to 0.35 ms a frame of graphics card time for SmoovPlay's looks (1440p)." LOOK_CLIPS_SPEED = "Up to about 0.2 ms more a frame of graphics card time, to draw it again at 1080p." +STAT_CHOICES = ("auto", "on", "off") +STAT_NAMES = {"auto": "Style's own", "on": "Show", "off": "Hide"} +# One row per number the stats overlay can show (framegen/stats.py ITEMS): the style's own list, or always, or never. +STAT_SPECS = tuple( + Spec("stat_" + k, label, STAT_CHOICES, "auto", STAT_NAMES, group="Display", + applies=("overlay_style", ("minimal", "detailed", "bar")), + help=text + " Style's own: shown or not as the style decides; Show and Hide override it.") + for k, (label, text) in stats.ITEMS.items()) + SPECS: tuple[Spec, ...] = ( Spec("interp", "Frame generation", (True, False), True, ON_OFF, group="Smoothness", quick=True, hints={False: "No new frames: the stream exactly as the game sends it, with the least delay."}, @@ -339,20 +348,26 @@ SPECS: tuple[Spec, ...] = ( "Low delay, so fullscreen keeps HDR on. Experimental; applies the next time you press Play.", 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, Graphs)."), - Spec("overlay_style", "Stats overlay style", ("minimal", "detailed", "graphs"), "minimal", - {"minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs"}, group="Display", applies=("overlay", (True,)), + help="Numbers over the video: the frames a second on screen, the game's own frame rate, how your PC keeps up, " + "and more if you pick it (Items, below). Key: S (Off, Minimal, Detailed, Graphs, Bar)."), + Spec("overlay_style", "Stats overlay style", ("minimal", "detailed", "graphs", "bar"), "minimal", + {"minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs", "bar": "Bar"}, 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.", + "detailed": "A card with a row for everything: frametime and lows, dropped and late frames, the time " + "of each stage, the graphics card, and the settings in words.", "graphs": "Like MangoHud: live graphs of frametime, the pipeline's time against its budget, delay and " - "the graphics card's load, with 1% lows."}, + "the graphics card's load, with 1% lows.", + "bar": "One thin line across the top or bottom edge with the numbers that matter, green, yellow or " + "red."}, 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 " - "about 95%, your PC is falling behind)."), + "Detailed: a card with all the numbers. Graphs: live graphs. Bar: one line along the top or bottom " + "edge. Which numbers each shows is yours to change under Items."), + Spec("bar_position", "Bar position", ("top", "bottom"), "top", {"top": "Top edge", "bottom": "Bottom edge"}, + group="Display", applies=("overlay_style", ("bar",)), + help="Which edge of the picture the bar goes along."), Spec("overlay_corner", "Stats overlay corner", ("top-left", "top-right", "bottom-left", "bottom-right"), "top-left", {"top-left": "Top left", "top-right": "Top right", "bottom-left": "Bottom left", "bottom-right": "Bottom right"}, group="Display", applies=("overlay", (True,)), @@ -373,6 +388,23 @@ SPECS: tuple[Spec, ...] = ( Spec("graph_gpu", "Graph: graphics card", (True, False), True, ON_OFF, group="Display", applies=("overlay_style", ("graphs",)), help="Graphs style: the graphics card's load, power, temperature, clock and memory (needs nvidia-smi)."), + Spec("overlay_colours", "Colour by threshold", (True, False), True, ON_OFF, group="Display", + applies=("overlay", (True,)), + help="Colours the numbers: green when all is well, yellow when it is tight, red when it is bad. Frame rates " + "and lows are judged against the output rate, frametimes against its frame time, the graphics card " + "against its load and temperature. Off draws every number in white."), + Spec("stats_window", "Averaging window", (10, 30, 60), 30, {10: "10 seconds", 30: "30 seconds", 60: "1 minute"}, + group="Display", applies=("overlay", (True,)), + help="How far back averages, lows, jitter and worst frametime look. A longer window is steadier and has " + "enough frames for the 0.1% low (it needs 1000); a shorter one follows a change sooner."), + *STAT_SPECS, + Spec("session_summary", "Save a summary when Summit stops", (True, False), True, ON_OFF, group="Display", + help="When Summit's picture closes, writes the session's numbers (averages, lows, the time of each stage, the " + "settings used and what changed during it) as a .json and a .txt file in Summit's data folder " + "(~/.local/share/smoovplay/sessions on Linux). Key P writes one at any time."), + Spec("frametime_log", "Log every frame (CSV)", (False, True), False, ON_OFF, group="Display", + help="Writes a line for every frame shown to a .csv in the sessions folder, with MangoHud's columns, so you " + "can graph a session elsewhere."), Spec("watermark", "Summit watermark", (True, False), True, ON_OFF, group="Display", help="A small line in a corner of the video: summit - git.molberg.cloud/alex/summit. It moves out of the " "stats overlay's way. Only in the video window, never in saved clips or files."), @@ -451,8 +483,11 @@ LAYOUT: tuple[tuple[str, str, tuple[str, ...]], ...] = ( ("Upscaling", "Output", ("output_res", "fill")), ("Display", "Window", ("fullscreen", "vsync", "present")), ("Display", "Colour and look", ("hdr", "look_on", "look")), - ("Overlay", "Stats", ("overlay", "overlay_style", "overlay_corner", "overlay_scale", "overlay_opacity")), + ("Overlay", "Stats", ("overlay", "overlay_style", "bar_position", "overlay_corner", "overlay_scale", + "overlay_opacity", "overlay_colours", "stats_window")), + ("Overlay", "Items", tuple("stat_" + k for k in stats.ITEMS)), ("Overlay", "Graphs", ("graph_frametime", "graph_pipeline", "graph_delay", "graph_gpu")), + ("Overlay", "Session", ("session_summary", "frametime_log")), ("Overlay", "This menu", ("ui_scale", "ui_opacity")), ("Overlay", "Branding", ("watermark",)), ("Clips", "Instant replay", ("replay", "replay_clip")), diff --git a/engine/framegen/stats.py b/engine/framegen/stats.py index 6c4726a..d07e283 100644 --- a/engine/framegen/stats.py +++ b/engine/framegen/stats.py @@ -135,7 +135,7 @@ class SystemSampler: self.latest: dict = {} self.history: list[dict] = [] # one entry a second, for the session summary (capped) self._stop = threading.Event() - self._gpu = None + self.gpu = None # framegen.gpustats.GpuStats, once started (the window's graphs share it) self._want_gpu = gpu self._prev = None self._thread = threading.Thread(target=self._run, name="sysstats", daemon=True) @@ -144,9 +144,9 @@ class SystemSampler: if self._want_gpu: try: from .gpustats import GpuStats - self._gpu = GpuStats() + self.gpu = GpuStats() except Exception: # noqa: BLE001 - no GPU numbers - self._gpu = None + self.gpu = None self._thread.start() return self @@ -197,7 +197,7 @@ class SystemSampler: return out def sample(self) -> dict: - s = {"t": time.time(), "cpu": self._cpu(), **self._memory(), "gpu": dict(self._gpu.latest) if self._gpu and self._gpu.latest else None} + s = {"t": time.time(), "cpu": self._cpu(), **self._memory(), "gpu": dict(self.gpu.latest) if self.gpu and self.gpu.latest else None} self.latest = s if len(self.history) < 6 * 3600: self.history.append(s) @@ -209,8 +209,8 @@ class SystemSampler: def close(self) -> None: self._stop.set() - if self._gpu is not None: - self._gpu.close() + if self.gpu is not None: + self.gpu.close() # ---- the collector --------------------------------------------------------------------------------------------------- @@ -242,7 +242,8 @@ class Collector: self._stats: list = [] # the pipelines' Stats, for the delay lists self.changes: list[dict] = [] self.csv: CsvLog | None = None - self.benchmark: dict | None = None # {"seconds": N, "start": t or None} + self.benchmark: dict | None = None # {"seconds": N, "start": t or None, "done": bool} + self.save_hook = None # save_hook(reason) -> a line saying where the summary went (run.py sets it) self.cost_ns = 0 # time spent in present() self.snap_ms = 0.0 # last snapshot's cost self.snaps = 0 @@ -267,6 +268,30 @@ class Collector: if stats not in self._stats: self._stats.append(stats) + # -- the benchmark ------------------------------------------------------------------------------------------- + def start_benchmark(self, seconds: float) -> None: + """A fixed-time run: the clock starts with the first frame shown.""" + self.benchmark = {"seconds": float(seconds), "start": None, "done": False} + + def bench_left(self, now: float | None = None) -> float | None: + """Seconds of the benchmark left (all of it before the first frame), None when there isn't one.""" + b = self.benchmark + if b is None: + return None + if b["start"] is None: + return b["seconds"] + now = time.perf_counter() if now is None else now + return max(0.0, b["seconds"] - (now - b["start"])) + + def bench_over(self, now: float | None = None) -> bool: + """Whether a benchmark was asked for and its time is up (it says so once, and stays over).""" + b = self.benchmark + if b is None: + return False + if not b["done"] and b["start"] is not None and self.bench_left(now) <= 0.0: + b["done"] = True + return b["done"] + # -- events -------------------------------------------------------------------------------------------------- def present(self, t: float, generated: bool) -> None: """A frame went on screen at time t (perf_counter).""" @@ -276,6 +301,8 @@ class Collector: self.generated += generated if self._first is None: self._first = t + if self.benchmark is not None and self.benchmark["start"] is None: + self.benchmark["start"] = t self.gen.add(t, 1.0 if generated else 0.0) rec = self._recent rec.append(t) @@ -527,7 +554,8 @@ class Cell: unit: str = "" level: str = "" hint: str = "" - detail: str = "" # a longer text for a row in Detailed (e.g. "avg 5.1 ms, worst 9.2 ms") + detail: str = "" # a second number for a row in Detailed (a stage's worst, the delay's 95th percentile) + detail_name: str = "" # what it is: "worst", "p95" # item key -> (label in the menu, help), in menu order @@ -603,25 +631,25 @@ def cells(snap: dict, item: str, colours: bool = True, inline: bool = True, note out.append(Cell("game", "game", _f(v, 0), "", lv("tight" if note else ""), "88")) elif item == "share": v = snap["share"] - out.append(Cell("share", "generated", _f(v, 0), "%", "", "888")) + out.append(Cell("share", "generated", _f(v, 0), "%", "", "88")) elif item == "frametime": v = snap["ft_avg"] - out.append(Cell("frametime", "frametime", _f(v), "ms", lv(level_of(v, 1.35 * tgt, 2.2 * tgt)), "888.8")) + out.append(Cell("frametime", "frametime", _f(v), "ms", lv(level_of(v, 1.35 * tgt, 2.2 * tgt)), "88.8")) elif item == "lows": for k, name in (("low1", "1% low"), ("low01", "0.1% low")): v = snap[k] out.append(Cell(k, name, _f(v, 0), "fps", lv(level_of(v, hz / 1.35, hz / 2.2, True)), "888")) elif item == "worst": v = snap["ft_worst"] - out.append(Cell("worst", "worst", _f(v), "ms", lv(level_of(v, 2.2 * tgt, 4.0 * tgt)), "888.8")) + out.append(Cell("worst", "worst", _f(v), "ms", lv(level_of(v, 2.2 * tgt, 4.0 * tgt)), "88.8")) elif item == "jitter": v = snap["jitter"] - out.append(Cell("jitter", "jitter", _f(v), "ms", lv(level_of(v, 0.25 * tgt, 0.6 * tgt)), "88.8")) + out.append(Cell("jitter", "jitter", _f(v), "ms", lv(level_of(v, 0.25 * tgt, 0.6 * tgt)), "8.8")) elif item == "drops": n = max(1, snap["frames_window"]) for k, name in (("dropped", "dropped"), ("repeated", "repeated"), ("late", "late")): v = snap[k] - out.append(Cell(k, name, f"{v:d}", "", lv("" if v == 0 else "bad" if v / n >= 0.01 else "tight"), "8888")) + out.append(Cell(k, name, f"{v:d}", "", lv("" if v == 0 else "bad" if v / n >= 0.01 else "tight"), "88")) elif item == "stages": for name in STAGES: s = snap["stages"].get(name) @@ -629,12 +657,12 @@ def cells(snap: dict, item: str, colours: bool = True, inline: bool = True, note continue lvl = level_of(s["avg"], 0.5 * tgt, 0.9 * tgt) if name != "present" else "" out.append(Cell("stage_" + name, STAGE_NAMES[name] if not inline else _short(name), _f(s["avg"]), "ms", - lv(lvl), "88.8", f"{_f(s['avg'], 2)} ms avg, {_f(s['worst'], 1)} ms worst")) + lv(lvl), "88.8", _f(s["worst"]), "worst")) elif item == "delay": v = snap["delay"] if v is not None: - out.append(Cell("delay", "delay", _f(v, 0), "ms", lv(level_of(v, 45.0, 80.0)), "888", - f"{_f(v, 0)} ms median, {_f(snap['delay_p95'], 0)} ms p95")) + out.append(Cell("delay", "delay", _f(v, 0), "ms", lv(level_of(v, 45.0, 80.0)), "88", + _f(snap["delay_p95"], 0), "p95")) elif item in ("gpu", "vram", "temp", "power"): g = snap["gpu"] if g: @@ -645,7 +673,7 @@ def cells(snap: dict, item: str, colours: bool = True, inline: bool = True, note out.append(Cell("vram", "VRAM", f"{used:.1f}/{total:.0f}", "GB", lv(level_of(used / total if total else None, 0.8, 0.92)), "88.8/88")) elif item == "temp": - out.append(Cell("temp", "GPU temp", _f(g["temp"], 0), "C", lv(level_of(g["temp"], 74.0, 84.0)), "888")) + out.append(Cell("temp", "GPU temp", _f(g["temp"], 0), "C", lv(level_of(g["temp"], 74.0, 84.0)), "88")) else: out.append(Cell("power", "power", _f(g["power"], 0), "W", "", "888")) elif item == "cpu": @@ -660,11 +688,16 @@ def cells(snap: dict, item: str, colours: bool = True, inline: bool = True, note else: out += [Cell("config", n, v) for n, v in config_lines(snap["config"])] elif item == "cost": - out.append(Cell("cost", "overlay", f"{snap['cost_us']:.0f}", "us/frame", "", "8888", - f"{snap['cost_us']:.0f} us a frame, {snap['snap_ms']:.2f} ms a refresh")) + out.append(Cell("cost", "overlay cost" if not inline else "cost", f"{snap['cost_us']:.1f}", "us/frame", "", "88.8")) return out +def bench_cell(left_s: float) -> Cell: + """The benchmark's countdown, always first.""" + left = max(0, int(math.ceil(left_s))) + return Cell("bench", "benchmark", f"{left // 60}:{left % 60:02d}", "left", "tight", "8:88") + + def _short(stage: str) -> str: return {"capture": "cap", "interp": "AI", "upscale": "up", "look": "look", "present": "pres"}[stage] diff --git a/engine/run.py b/engine/run.py index b1e23c4..2d89bdf 100644 --- a/engine/run.py +++ b/engine/run.py @@ -52,6 +52,7 @@ if __name__ == "__main__" and "--list-sources" in sys.argv: # answered before t import argparse import gc +import json import threading import time from pathlib import Path @@ -362,7 +363,22 @@ def main() -> int: ap.add_argument("--results", metavar="TXT", help="when test mode (a simulated 30 fps game) or --score was used, write a plain-language report " "of performance and quality here: every 10 s while playing, and at the end") + ap.add_argument("--benchmark", metavar="SECONDS", type=float, default=None, + help="run for this long (counted from the first frame shown), with a countdown in the overlay, then " + "write the session summary (JSON and a text table, in Summit's data folder, or beside --results) " + "and show a result card for a few seconds. A video file is played in real time and repeated if " + "it is shorter.") + ap.add_argument("--result-card", metavar="SECONDS", type=float, default=8.0, + help="how long --benchmark's result card stays on screen (default 8; 0 for none)") + ap.add_argument("--frametime-log", metavar="CSV", nargs="?", const="auto", default=None, + help="write a line for every frame shown to this file, with MangoHud's columns (no file name: a " + "file beside the session summary). The overlay's Log every frame setting does the same") + ap.add_argument("--stats-dir", metavar="DIR", default=None, + help="where session summaries and frame logs go (default: the sessions folder in Summit's data " + "folder, ~/.local/share/smoovplay/sessions on Linux)") a = ap.parse_args() + if a.benchmark is not None and a.benchmark <= 0: + ap.error("--benchmark SECONDS: more than 0") if a.output_res is not None and a.output_res != "screen" and parse_res(a.output_res) is None: ap.error(f"--output-res {a.output_res}: a size like 2560x1440 (320x240 to 7680x4320), or 'screen'") if a.hz is not None and not valid_hz(a.hz): @@ -390,6 +406,8 @@ def main() -> int: a.chiaki_decoder = "d3d11va" kind = a.source or ("chiaki" if a.chiaki else "capture" if a.capture is not None else "file" if a.video else None) + if a.benchmark and kind == "file": + a.realtime = True # a benchmark plays a file the way a game would arrive, not as fast as it can be read picked = kind # as asked for: an app's compressed frames on the tap become "chiaki" below, without chiaki-ng # Test mode ("Simulate a 30 fps game") works with any 60 Hz source; a video file simulates a PS5 by itself # unless --raw plays it as-is. @@ -463,6 +481,10 @@ def main() -> int: ("watermark", None if a.watermark is None else a.watermark == "on")): if value is not None: settings.override(key, value) + if a.benchmark: + settings.override("overlay", True) # the countdown is on it + if a.frametime_log: + settings.override("frametime_log", True) if a.look: if a.look.lower() == "off": settings.override("look_on", False) @@ -662,6 +684,57 @@ def main() -> int: # so the window closes, clips finish saving and the summary is printed. import signal signal.signal(signal.SIGTERM, lambda *_: setattr(window, "cmd", "quit")) + # The stats overlay's numbers and the session summary (framegen/stats.py): one collector for the whole run. + from framegen import stats as stat_lib + stats_dir = Path(a.stats_dir) if a.stats_dir else stat_lib.sessions_dir() + session_base = f"summit-{'benchmark' if a.benchmark else 'session'}-{stat_lib.stamp()}" + coll = stat_lib.Collector(window_s=settings.stats_window, + sampler=stat_lib.SystemSampler().start() if (sink.sinks or a.benchmark) else None) + coll.set_config(source=f"{src.w}x{src.h}") + if a.benchmark: + coll.start_benchmark(a.benchmark) + if isinstance(window, GLWindowSink): + window.collector = coll + seen = settings.values() + + def track_setting(key: str) -> None: + """A setting changed while playing: kept with the numbers from before and after it (the session summary).""" + old, seen[key] = seen.get(key), settings.values()[key] + spec = BY_KEY[key] + coll.setting_changed(key, spec.label, spec.name(old), spec.name(seen[key])) + + settings.watch(track_setting) + + def frame_log(key: str = "frametime_log") -> None: + if key != "frametime_log": + return + if settings.frametime_log and coll.csv is None: + name = a.frametime_log if a.frametime_log not in (None, "auto") else str(stats_dir / f"{session_base}.csv") + try: + coll.csv = stat_lib.CsvLog(name, stat_lib.system_info()) + print(f"[stats] logging every frame to {name}") + except OSError as e: + print(f"[stats] couldn't write {name}: {e}") + elif not settings.frametime_log and coll.csv is not None: + coll.csv.close() + coll.csv = None + + settings.watch(frame_log) + frame_log() + settings.watch(lambda key: coll.set_window(settings.stats_window) if key == "stats_window" else None) + summary_state = {"final": False} + + def save_summary(reason: str) -> str: + """The session so far as summit-session-