204 lines
8.8 KiB
Python
204 lines
8.8 KiB
Python
"""The stats wired into the pipeline (framegen/pipeline.py) and the settings: a fake interpolator and sink on the CPU, so
|
|
no GPU or window is needed. The numbers are from made-up frames: they test the wiring, not any speed."""
|
|
import pathlib
|
|
import sys
|
|
import time
|
|
|
|
import numpy as np
|
|
import pytest
|
|
import torch
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
from framegen import stats as S
|
|
from framegen.io import MiniText, Tick
|
|
from framegen.pipeline import Pipeline
|
|
from framegen.settings import BY_KEY, SPECS, Settings
|
|
from framegen.sources import make_detector, source_info
|
|
|
|
H, W = 36, 64
|
|
|
|
|
|
class FakeInterp:
|
|
"""Stands in for RifeInterpolator: frames in, a made-up in-between frame out, taking `work_ms`."""
|
|
h, w, device, private = H, W, "cpu", False
|
|
frame_dtype = torch.uint8
|
|
|
|
def __init__(self, work_ms: float = 1.0) -> None:
|
|
self.in_u8 = torch.zeros((H, W, 3), dtype=torch.uint8)
|
|
self.out_u8 = torch.zeros((H, W, 3), dtype=torch.uint8)
|
|
self.work = work_ms / 1000.0
|
|
|
|
def load(self, frame) -> None:
|
|
self.in_u8.copy_(frame if torch.is_tensor(frame) else torch.from_numpy(frame))
|
|
|
|
def prepare(self, slot: int) -> None:
|
|
pass
|
|
|
|
def interpolate(self, slot: int, t: float = 0.5):
|
|
time.sleep(self.work)
|
|
return self.out_u8.clone()
|
|
|
|
|
|
class FakeSource:
|
|
"""A 30 fps game on a 60 Hz stream: a new picture every other tick."""
|
|
info = source_info("file", live=False, hz=60)
|
|
|
|
def __init__(self, ticks: int, pause_s: float = 0.0) -> None:
|
|
self.n, self.pause, self.taken = ticks, pause_s, 0
|
|
|
|
def __iter__(self):
|
|
for i in range(self.n):
|
|
self.taken += 1
|
|
frame = np.full((H, W, 3), (i // 2 * 40) % 250, np.uint8)
|
|
if self.pause:
|
|
time.sleep(self.pause)
|
|
yield Tick(frame, time.perf_counter(), i)
|
|
|
|
|
|
class FakeSink:
|
|
gpu = False
|
|
|
|
def __init__(self, cmds=()) -> None:
|
|
self.texts, self.toasts, self.cmds = [], [], list(cmds)
|
|
|
|
def write(self, frame, text=None):
|
|
self.texts.append(text)
|
|
return self.cmds.pop(0) if self.cmds else None
|
|
|
|
def toast(self, text: str, seconds: float = 2.0) -> None:
|
|
self.toasts.append(text)
|
|
|
|
|
|
def run(ticks=120, hz=60, style="minimal", cmds=(), coll=None, pause=0.0, **over):
|
|
st = Settings()
|
|
st.override("hz", hz)
|
|
st.override("overlay_style", style)
|
|
for k, v in over.items():
|
|
st.override(k, v)
|
|
coll = coll or S.Collector()
|
|
sink = FakeSink(cmds)
|
|
pipe = Pipeline(FakeInterp(), make_detector(FakeSource.info))
|
|
src = FakeSource(ticks, pause)
|
|
stats = pipe.run(src, sink, settings=st, label="FAKE", collector=coll)
|
|
return coll, sink, stats, src
|
|
|
|
|
|
def test_a_run_feeds_the_collector_frames_stages_and_the_game_rate():
|
|
coll, sink, stats, _ = run(ticks=120)
|
|
assert coll.frames == 120 and coll.generated > 0 and coll.frames - coll.generated > 0 # real and generated frames
|
|
assert len(coll.stage_all["capture"]) == 120 and len(coll.stage_all["interp"]) > 10
|
|
assert all(0 <= v < 5000 for v in coll.stage_all["interp"]) and np.mean(coll.stage_all["interp"]) >= 1.0 # the fake's 1 ms
|
|
assert coll.real_input > 0 and coll.ticks_input == 120
|
|
s = coll.summary()
|
|
assert s["frames"]["presented"] == 120 and s["stages"]["interp"]["n"] == len(coll.stage_all["interp"])
|
|
assert s["delay"] is not None and s["delay"]["n"] > 0 # from the pipeline's Stats, attached
|
|
assert s["stats_cost"]["per_frame_us"] < 500
|
|
|
|
|
|
def test_a_pipeline_without_a_collector_still_runs():
|
|
st = Settings()
|
|
sink = FakeSink()
|
|
stats = Pipeline(FakeInterp(), make_detector(FakeSource.info)).run(FakeSource(30), sink, settings=st, label="X")
|
|
assert len(sink.texts) == 30 and stats.exit == "end"
|
|
|
|
|
|
@pytest.mark.parametrize("style", ["minimal", "bar", "detailed", "graphs"])
|
|
def test_every_style_hands_the_window_its_numbers(style):
|
|
_, sink, _, _ = run(ticks=60, style=style)
|
|
t = next(x for x in reversed(sink.texts) if isinstance(x, MiniText) and (x.cells or x.graph))
|
|
assert t.parts and t.parts[0][0].endswith("fps")
|
|
if style == "graphs":
|
|
assert t.cells is None and "low1" in t.graph
|
|
else:
|
|
assert [c.key for c in t.cells][0] == "fps"
|
|
assert (len(t.rows) > 5) == (style == "detailed")
|
|
|
|
|
|
def test_the_item_settings_choose_what_the_line_shows():
|
|
_, sink, _, _ = run(ticks=60, stat_lows="on", stat_game="off", stat_delay="off")
|
|
t = next(x for x in reversed(sink.texts) if isinstance(x, MiniText) and x.cells)
|
|
keys = [c.key for c in t.cells]
|
|
assert keys == ["fps", "low1", "low01"]
|
|
_, sink, _, _ = run(ticks=60, overlay_colours=False)
|
|
t = next(x for x in reversed(sink.texts) if isinstance(x, MiniText) and x.cells)
|
|
assert all(c.level == "" for c in t.cells)
|
|
|
|
|
|
def test_generated_frames_left_out_when_behind_are_counted_as_dropped():
|
|
coll = S.Collector()
|
|
# 120 fps from a 30 fps game: three extra frames a real one. A source that arrives late each tick makes the
|
|
# pipeline skip them ("behind"), which the collector counts as dropped.
|
|
_, _, stats, _ = run(ticks=40, hz=120, coll=coll)
|
|
assert coll.dropped_total + coll.generated > 0 and coll.frames >= 40
|
|
assert coll.dropped_total == stats.quarter_skipped
|
|
|
|
|
|
def test_a_benchmark_stops_the_run_at_its_time_and_shows_a_countdown():
|
|
coll = S.Collector()
|
|
coll.start_benchmark(0.4)
|
|
_, sink, stats, src = run(ticks=100000, coll=coll, pause=0.004) # would take minutes
|
|
assert stats.exit == "end" and src.taken < 1000 and coll.bench_over()
|
|
assert 0.3 < coll.summary()["duration_s"] < 1.5
|
|
benches = [c for x in sink.texts if isinstance(x, MiniText) and x.cells for c in x.cells if c.key == "bench"]
|
|
assert benches and benches[0].value.startswith("0:0") and benches[0].unit == "left"
|
|
assert coll.summary()["benchmark"] == {"seconds": 0.4}
|
|
|
|
|
|
def test_the_summary_key_writes_through_the_hook_and_says_so():
|
|
coll = S.Collector()
|
|
seen = []
|
|
coll.save_hook = lambda why: seen.append(why) or "Summary saved to ~/x"
|
|
_, sink, _, _ = run(ticks=20, cmds=[None, None, "save_summary"], coll=coll)
|
|
assert seen == ["asked for"] and sink.toasts == ["Summary saved to ~/x"]
|
|
coll2 = S.Collector()
|
|
_, sink, _, _ = run(ticks=10, cmds=["save_summary"], coll=coll2) # no hook: it says so, nothing breaks
|
|
assert "isn't available" in sink.toasts[0]
|
|
|
|
|
|
# ---- the settings ---------------------------------------------------------------------------------------------------------
|
|
def test_every_overlay_setting_has_help_and_a_place():
|
|
overlay = [s for s in SPECS if s.group == "Overlay"]
|
|
assert len(overlay) > 25
|
|
for s in overlay:
|
|
assert s.help.strip(), f"{s.key} has no help text"
|
|
assert s.sub, f"{s.key} has no heading"
|
|
assert {s.sub for s in overlay} == {"Stats", "Items", "Graphs", "Session", "This menu", "Branding"}
|
|
assert {"stat_" + k for k in S.ITEMS} <= {s.key for s in overlay}
|
|
|
|
|
|
def test_old_saved_settings_still_load_and_new_ones_default_sensibly(tmp_path):
|
|
f = tmp_path / "settings.json"
|
|
f.write_text('{"overlay_style": "graphs", "overlay_corner": "top-right", "graph_gpu": false, "hz": 90}')
|
|
st = Settings.load(f)
|
|
assert st.overlay_style == "graphs" and st.overlay_corner == "top-right" and st.graph_gpu is False and st.hz == 90
|
|
assert st.stat_fps == "auto" and st.bar_position == "top" and st.overlay_colours is True
|
|
assert st.stats_window == 30 and st.session_summary is True and st.frametime_log is False
|
|
st.set("overlay_style", "bar")
|
|
assert Settings.load(f).overlay_style == "bar"
|
|
assert BY_KEY["overlay_style"].accepts("minimal") and BY_KEY["overlay_style"].accepts("detailed")
|
|
with pytest.raises(ValueError):
|
|
st.set("stat_fps", "sometimes")
|
|
|
|
|
|
def test_the_overlay_menu_groups_the_items_and_hides_what_the_style_does_not_use():
|
|
from framegen.menu import Menu
|
|
m = Menu(Settings())
|
|
m.open = True
|
|
rows = m.tab_rows("Overlay")
|
|
headers = [r.label for r in rows if r.kind == "header"]
|
|
assert headers[:3] == ["Stats", "Items", "Session"] # (Graphs' rows only show with the Graphs style)
|
|
assert any(r.key == "stat_lows" for r in rows) and not any(r.key == "bar_position" for r in rows)
|
|
m.settings.override("overlay_style", "bar")
|
|
assert any(r.key == "bar_position" for r in m.tab_rows("Overlay"))
|
|
m.settings.override("overlay_style", "graphs")
|
|
keys = [r.key for r in m.tab_rows("Overlay")]
|
|
assert "graph_gpu" in keys and "stat_lows" not in keys
|
|
# Home: the one performance row has Bar, and the summary action is there above Quit
|
|
home = m.tab_rows(None)
|
|
assert [r.key for r in home][-2:] == ["summary", "quit"]
|
|
perf = next(r for r in home if r.kind == "perf")
|
|
m.set_value(perf, "bar")
|
|
assert m.settings.overlay_style == "bar" and m.settings.overlay is True
|
|
m.index = [r.key for r in m.rows()].index("summary")
|
|
assert m.key("enter") == "save_summary"
|