Files
2026-11-26 08:37:57 +00:00

2602 lines
140 KiB
Python

"""Frame sources (PS5 simulator, plain file, capture card) and sinks (window, file)."""
from __future__ import annotations
import os
import queue
import random
import subprocess
import sys
import threading
import collections
import time
from collections import OrderedDict
from dataclasses import dataclass, field
from typing import NamedTuple
import cv2
import numpy as np
from .fill import Panorama, layout, panorama_t, visible, wider
TICK = 1.0 / 60.0
@dataclass
class Tick:
frame: np.ndarray # HxWx3 uint8 BGR (or a CUDA tensor from a GPU decoder), never mutated after yield
t_arrival: float # perf_counter() when the frame reached this PC (Remote Play: when chiaki-ng got it, before
# decoding); latency is measured from here
index: int # tick number
# Ground truth, only known for simulated input (and test mode):
content: int | None = None # source-frame index shown on this tick
truth_new: bool | None = None
# What the source knows about the frame (framegen.sources.SourceInfo says which a source fills in):
new_hint: bool | None = None # new content (True) or a repeat (False), by the source's own account; None: the
# pipeline compares pictures
damaged: bool = False # known to be corrupt (frames lost before it); held like a scene cut, not blended
t_ready: float | None = None # when the pipeline could first have it (after decoding); None: t_arrival
t_source: float | None = None # the source's own time for the frame, in seconds (a file's position; later, a
# capture card's timestamp), for timing frames by the source's clock rather than by arrival
extra: dict = field(default_factory=dict) # anything else, for logs (e.g. Remote Play's per-frame facts)
class Waiting(NamedTuple):
"""What a live source yields instead of blocking when no frame has come for a moment (the stream stalled,
chiaki-ng is reconnecting, the card lost its signal). The pipeline then keeps the window answering: its keys, the
launcher's commands and Windows' "not responding" check, which closed SmoovPlay mid-session when a stream
stalled with the loop stuck waiting for a frame."""
since: float # seconds since the last frame
what: str # where frames come from, for the message on screen ("the PS5")
why: str = "" # what the source knows about it, as a hint for the player ("" if nothing)
WAIT_POLL_S = 0.1 # how long a source waits for a frame before saying so
def queue_ticks(q: queue.Queue, what: str, why=None):
"""A live source's ticks, as its reader thread puts them in `q` (None ends them), numbered from 0, with a
Waiting in between whenever none has come for WAIT_POLL_S. why: () -> the source's hint for the Waiting."""
i, last = 0, time.perf_counter()
while True:
try:
tick = q.get(timeout=WAIT_POLL_S)
except queue.Empty:
yield Waiting(time.perf_counter() - last, what, why() if why is not None else "")
continue
if tick is None:
return
tick.index = i
yield tick
i += 1
last = time.perf_counter()
class Sound(NamedTuple):
"""A chunk of the game's sound, for instant replay (framegen/replay.py): what a source's read_sound() returns."""
t: float # perf_counter() when its first sample reached this PC
pcm: bytes # interleaved signed 16-bit samples
rate: int
channels: int
# ----------------------------------------------------------------------------- sources
class _Decoder(threading.Thread):
"""Decodes a video file on a background thread (cv2 releases the GIL while decoding)."""
def __init__(self, path: str, maxsize: int = 16) -> None:
super().__init__(daemon=True)
self.cap = cv2.VideoCapture(path)
if not self.cap.isOpened():
raise FileNotFoundError(path)
self.fps = self.cap.get(cv2.CAP_PROP_FPS) or 60.0
self.w = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.h = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.q: queue.Queue = queue.Queue(maxsize)
self.start()
def run(self) -> None:
while True:
ok, f = self.cap.read()
self.q.put(f if ok else None)
if not ok:
return
def __iter__(self):
while (f := self.q.get()) is not None:
yield f
class Ps5SimSource:
"""Turns a native 60 fps recording into what a PS5 sends for a 30 fps game.
Source frames 0,2,4,... become the game's real frames; each is scanned out for two
60 Hz ticks (three with probability `hitch`, to mimic a dropped game frame). The
odd source frames are never shown, so they serve as ground truth for the
interpolated midpoints (`gt(i)`).
A ~30 fps file (e.g. real PS5 footage) is used frame-for-frame instead: every frame
is a game frame, there is no ground truth, and scoring is skipped.
"""
def __init__(self, path: str, realtime: bool = False, hitch: float = 0.0, noise: float = 0.0,
max_ticks: int | None = None, seed: int = 0, game60: bool = False) -> None:
from .sources import source_info
self.dec = _Decoder(path)
self.w, self.h = self.dec.w, self.dec.h
self.info = source_info("sim", live=realtime)
self.realtime, self.hitch, self.max_ticks = realtime, hitch, max_ticks
self.step = 2 if self.dec.fps > 45 else 1 # 60 fps source: drop odd frames; 30 fps: use all
self.game60 = game60 # --sim60: a 60 fps file played as a 60 fps game, a new frame every tick
if game60:
self.step = 1
print(f"[sim] {self.dec.fps:.2f} fps source played as a 60 fps game (no ground truth)")
elif self.step == 1:
print(f"[sim] {self.dec.fps:.2f} fps source: using every frame as a game frame (no ground truth)")
self.rng = random.Random(seed)
self.history: OrderedDict[int, np.ndarray] = OrderedDict()
self._noise = None
if noise > 0: # precomputed noise planes so adding noise stays cheap in realtime
r = np.random.default_rng(seed)
n = [np.clip(r.normal(0, noise, (self.h, self.w, 3)), -255, 255) for _ in range(6)]
self._noise = [(np.clip(x, 0, 255).astype(np.uint8), np.clip(-x, 0, 255).astype(np.uint8)) for x in n]
def gt(self, i: int) -> np.ndarray | None:
return self.history.get(i)
def __iter__(self):
t0 = time.perf_counter()
tick = 0
for i, f in enumerate(self.dec):
self.history[i] = f
while len(self.history) > 8:
self.history.popitem(last=False)
if i % self.step:
continue # odd frames of a 60 fps source: the game "never rendered" these
repeats = 1 if self.game60 else 3 if self.rng.random() < self.hitch else 2
for r in range(repeats):
if self.max_ticks is not None and tick >= self.max_ticks:
return
out = f
if self._noise is not None:
pos, neg = self._noise[self.rng.randrange(len(self._noise))]
out = cv2.subtract(cv2.add(f, pos), neg)
if self.realtime:
# A capture card delivers on the HDMI clock whether or not we keep up, so
# latency is measured from the scheduled arrival (includes any backlog).
t_arr = t0 + tick * TICK
if (wait := t_arr - time.perf_counter()) > 0:
time.sleep(wait)
else:
t_arr = time.perf_counter()
yield Tick(out, t_arr, tick, content=i if self.step == 2 else None,
truth_new=(r == 0) if self.step == 2 else None, t_source=i / self.dec.fps)
tick += 1
def close(self) -> None:
pass
class FileSource:
"""Plays a file's frames as-is, e.g. a raw recording from the capture card. test: a framegen.sources.TestMode,
to play a 60 fps recording as a 30 fps game."""
def __init__(self, path: str, realtime: bool = False, max_ticks: int | None = None, test=None) -> None:
from .sources import source_info
self.dec = _Decoder(path)
self.w, self.h = self.dec.w, self.dec.h
self.realtime, self.max_ticks, self.test = realtime, max_ticks, test
self.info = source_info("file", live=realtime, hz=self.dec.fps)
def __iter__(self):
t0 = time.perf_counter()
for i, f in enumerate(self.dec):
if self.max_ticks is not None and i >= self.max_ticks:
return
if self.realtime and (wait := t0 + i * TICK - time.perf_counter()) > 0:
time.sleep(wait)
tick = Tick(f, time.perf_counter(), i, t_source=i / self.dec.fps)
if self.test is None or (tick := self.test(tick)) is not None:
yield tick
def close(self) -> None:
pass
class CaptureSource:
"""Live capture card via OpenCV (DirectShow). Experimental: not tested with a real card yet, and not offered in the
launcher until it is.
Frames are read on a thread and queued (not "latest only"), because dropping a
frame would break duplicate detection. If processing can't keep up the queue
overflows and the oldest frame is dropped, which is reported as `dropped`.
device: the card's DirectShow index, or a video file that stands in for one (played at its own frame rate on
the same thread-and-queue path), to test the capture path and test mode without a card. A file waits for the
pipeline to start reading, so all of it is played; a card is live, and what comes before is dropped.
test: a framegen.sources.TestMode, applied before the queue.
"""
def __init__(self, device: int | str, width: int = 1920, height: int = 1080, fps: int = 60,
fourcc: str = "MJPG", backend: int = cv2.CAP_DSHOW, test=None) -> None:
from .sources import source_info
self.stand_in = isinstance(device, str)
if self.stand_in:
self.cap = cv2.VideoCapture(device)
if not self.cap.isOpened():
raise FileNotFoundError(device)
else:
self.cap = cv2.VideoCapture(device, backend)
if not self.cap.isOpened():
raise RuntimeError(f"could not open capture device {device}")
self.cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*fourcc))
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
self.cap.set(cv2.CAP_PROP_FPS, fps)
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
self.w = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.h = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps = self.cap.get(cv2.CAP_PROP_FPS) or 60.0
print(f"[capture] {self.w}x{self.h} @ {self.fps:.2f} fps"
+ (f", a file standing in for a capture card: {device}" if self.stand_in else f" requested {fourcc}"))
self.info = source_info("capture", hz=self.fps,
name="Capture card" + (" (a file standing in)" if self.stand_in else ""))
self.test = test
self.q: queue.Queue = queue.Queue(maxsize=3)
self.dropped = 0
self._stop = False
self._go = threading.Event()
threading.Thread(target=self._reader, daemon=True).start()
def _reader(self) -> None:
if self.stand_in:
self._go.wait()
t0, n = time.perf_counter(), 0
while not self._stop:
ok, f = self.cap.read()
if not ok:
self.q.put(None)
return
if self.stand_in and (wait := t0 + n / self.fps - time.perf_counter()) > 0:
time.sleep(wait) # a card delivers on the HDMI clock
tick = Tick(f, time.perf_counter(), 0, t_source=n / self.fps if self.stand_in else None)
n += 1
if self.test is not None and (tick := self.test(tick)) is None:
continue
try:
self.q.put_nowait(tick)
except queue.Full:
self.q.get_nowait()
self.dropped += 1
self.q.put_nowait(tick)
def __iter__(self):
self.dropped = 0 # frames dropped while RIFE was loading don't count
self._go.set()
yield from queue_ticks(self.q, "the capture card")
def close(self) -> None:
self._stop = True
self._go.set()
self.cap.release()
print(f"[capture] dropped frames: {self.dropped}")
# ----------------------------------------------------------------------------- sinks
def _is_cuda(frame) -> bool:
return getattr(frame, "is_cuda", False)
def _host(frame) -> np.ndarray:
"""A frame as a numpy array (CUDA tensors are copied to the CPU)."""
return frame.cpu().numpy() if _is_cuda(frame) else frame
# Low delay (DXGI) is for windowed play. Fullscreen already skips the compositor's copy with the standard presentation,
# and Low delay in fullscreen could freeze (Present blocked for seconds, or for good), so by default ("none") a session
# that starts fullscreen uses the standard presentation, and a Low delay window stays a window until the next Play.
# Under test (scripts/dxgi_smoke.py): "monitor", GLFW's fullscreen (an always-on-top window exactly over the monitor);
# "borderless", a plain borderless window over it, as games' borderless mode. See framegen/dxgi_present.py.
# The standard presentation's fullscreen is that borderless window too, unless this is "monitor": GLFW's stays on top
# of everything, so Alt+Tab to another program left the video over it.
FULLSCREEN_STYLE = os.environ.get("FRAMEGEN_FULLSCREEN_STYLE", "none")
# Wayland doesn't let a program place its own window, so the borderless-window fullscreen above can't cover a monitor
# there: fullscreen asks the compositor for real fullscreen on the chosen monitor instead (GLFW's own).
WAYLAND = sys.platform.startswith("linux") and os.environ.get("XDG_SESSION_TYPE") == "wayland"
# Which monitor fullscreen goes to: SMOOVPLAY_MONITOR, part of its name as GLFW gives it ("DP-4", or the model's name),
# else the primary one. Set by run.py --monitor.
MONITOR = os.environ.get("SMOOVPLAY_MONITOR", "")
# The window's title (SMOOVPLAY_TITLE): lets a window rule tell launchers apart (the projector one vs. the desktop one).
WINDOW_TITLE = os.environ.get("SMOOVPLAY_TITLE", "SmoovPlay")
# Window capture's overlay on Linux is an X11 override-redirect window (framegen/window_x11.py): on X11, and on a
# Wayland session through XWayland (DISPLAY set). KWin keeps such a window above everything, a fullscreen game
# included, never gives it the keyboard, and lets the pointer through (checked on Plasma 6.8 Wayland). Wayland itself
# has no way for a program to place its window, keep it on top or refuse the focus.
X11 = sys.platform.startswith("linux") and (not WAYLAND or bool(os.environ.get("DISPLAY")))
# SMOOVPLAY_SUPERSAMPLE=2: RTX VSR runs even when the window is no bigger than the picture (it renders at 2x and the GPU
# shrinks that back), so it cleans up a capture card's compression blocks on a 1080p screen too.
try:
SUPERSAMPLE = max(1.0, min(2.0, float(os.environ.get("SMOOVPLAY_SUPERSAMPLE", "1"))))
except ValueError:
SUPERSAMPLE = 1.0
def pick_monitor(glfw, want: str = ""):
"""The monitor whose name contains `want` (MONITOR if not given), else the primary one."""
want = (want or MONITOR).lower()
if want:
for m in glfw.get_monitors() or []:
name = glfw.get_monitor_name(m)
name = name.decode() if isinstance(name, bytes) else str(name or "")
if want in name.lower():
return m
print(f"[display] no monitor named like {want!r}: fullscreen goes to the main one")
return glfw.get_primary_monitor()
# With Windows' HDR on, OpenGL's own fullscreen (and an OpenGL window over the whole monitor too) switches the display
# to SDR while the window is in front, and back to HDR when another window is: the picture's colours change with each
# Alt+Tab or click, and the display's SDR mode can look different again (warmer, say). A DXGI swap chain keeps
# Windows' HDR on in fullscreen, and Windows shows the SDR picture in it as it shows any SDR window. So when the main
# display has Windows' HDR on, the window presents through DXGI (8-bit) and fullscreen is a borderless window over the
# monitor, as with HDR output. FRAMEGEN_KEEP_HDR=0 turns this off (OpenGL's own presentation, as before).
KEEP_HDR = os.environ.get("FRAMEGEN_KEEP_HDR", "1") != "0"
KEEP_HDR_REASON = ("With Windows' HDR on, the window always uses the low-delay presentation: the standard one switches "
"the display to SDR in fullscreen, which changes the colours.")
def windows_hdr_on() -> bool:
"""Whether the main display, where fullscreen goes, has Windows' HDR on (False if it can't be told)."""
if sys.platform != "win32":
return False
try:
from .dxgi_present import display_hdr
d = display_hdr()
return bool(d and d["hdr"])
except Exception: # noqa: BLE001 - unknown: OpenGL's own presentation, as before
return False
def _say_if_slow(what: str, t0: float, limit_ms: float = 250.0) -> None:
"""A line in the log when a window call took far longer than a frame (a stall worth reporting)."""
ms = (time.perf_counter() - t0) * 1000
if ms > limit_ms:
print(f"[display] {what} took {ms:.0f} ms")
def _draw_text(frame: np.ndarray, text: str) -> np.ndarray:
frame = frame.copy()
for i, line in enumerate(text.split("\n")):
y = 40 + 40 * i
cv2.putText(frame, line, (20, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 5, cv2.LINE_AA)
cv2.putText(frame, line, (20, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA)
return frame
def _gl_image(GL, img: np.ndarray, hdr: bool):
"""An 8-bit BGR image as (pixels, internal format, pixel type) for a GL upload: as it is, or for an HDR10 picture
(framegen/hdr.py) as 16-bit PQ with white at SDR graphics white, so it looks as on an SDR one."""
if not hdr:
return np.ascontiguousarray(img), GL.GL_RGBA8, GL.GL_UNSIGNED_BYTE
from .hdr import sdr_to_pq16_image
return np.ascontiguousarray(sdr_to_pq16_image(img)), GL.GL_RGBA16, GL.GL_UNSIGNED_SHORT
class _Panel:
"""A BGR image in a GL texture of its own, blitted 1:1 over the frame (menu, messages). hdr: over an HDR10
picture (see _gl_image)."""
def __init__(self, GL, hdr: bool = False) -> None:
self.GL, self.w, self.h, self.hdr = GL, 0, 0, hdr
self.tex, self.fbo = GL.glGenTextures(1), GL.glGenFramebuffers(1)
self.blend = False # drawn see-through (update(opacity < 1)), by a shader, instead of copied
@staticmethod
def with_alpha(img: np.ndarray, bgs, opacity: float) -> np.ndarray:
"""img as BGRA: pixels at (or near) a background colour of `bgs` get alpha `opacity`, text and lines stay solid,
and the anti-aliased edges in between get alpha in between."""
d = np.min([np.abs(img.astype(np.int16) - np.array(b, np.int16)).max(axis=2) for b in bgs], axis=0)
cover = np.clip(d / 70.0, 0.0, 1.0)
alpha = (opacity + (1.0 - opacity) * cover) * 255.0
return np.dstack([img, alpha.astype(np.uint8)])
def update(self, img: np.ndarray, bgs=None, opacity: float = 1.0) -> None:
GL = self.GL
h, w = img.shape[:2]
blend = bool(bgs) and opacity < 0.999 and not self.hdr
if blend != self.blend: # the texture's format changes: make it again
self.blend, self.w, self.h = blend, 0, 0
if blend:
rgba = np.ascontiguousarray(self.with_alpha(img, bgs, opacity))
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
if (w, h) != (self.w, self.h):
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, rgba)
self.w, self.h = w, h
else:
GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, w, h, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, rgba)
return
img, fmt, kind = _gl_image(GL, img, self.hdr)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
if (w, h) != (self.w, self.h):
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, fmt, w, h, 0, GL.GL_BGR, kind, img)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
GL.glFramebufferTexture2D(GL.GL_READ_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.tex, 0)
self.w, self.h = w, h
else:
GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, w, h, GL.GL_BGR, kind, img)
def update_rgba(self, rgba: np.ndarray) -> None:
"""An RGBA picture with its own alpha (framegen/ui_draw.py: rounded corners, a see-through background),
blended over the frame. Over an HDR10 picture it's copied without its alpha instead (square and solid)."""
if self.hdr:
self.update(np.ascontiguousarray(rgba[..., 2::-1]))
return
GL = self.GL
h, w = rgba.shape[:2]
if not self.blend: # the texture's format changes: make it again
self.blend, self.w, self.h = True, 0, 0
rgba = np.ascontiguousarray(rgba)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
if (w, h) != (self.w, self.h):
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, rgba)
self.w, self.h = w, h
else:
GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, rgba)
_PROG: dict = {} # per GL module: the program and vertex array that draw a see-through panel
def _draw_blended(self, x: int, top: int, target: int) -> None:
GL = self.GL
if id(GL) not in self._PROG:
from OpenGL.GL import shaders
vs = """#version 450
void main() { vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }"""
fs = """#version 450
layout(binding = 0) uniform sampler2D img;
uniform ivec2 origin;
out vec4 color;
void main() {
ivec2 q = ivec2(gl_FragCoord.xy) - origin;
color = texelFetch(img, ivec2(q.x, textureSize(img, 0).y - 1 - q.y), 0);
}"""
prog = shaders.compileProgram(shaders.compileShader(vs, GL.GL_VERTEX_SHADER),
shaders.compileShader(fs, GL.GL_FRAGMENT_SHADER), validate=False)
self._PROG[id(GL)] = (prog, GL.glGetUniformLocation(prog, "origin"), GL.glGenVertexArrays(1))
prog, u_origin, vao = self._PROG[id(GL)]
old_vp = GL.glGetIntegerv(GL.GL_VIEWPORT)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
GL.glViewport(x, top - self.h, self.w, self.h)
GL.glUseProgram(prog)
GL.glUniform2i(u_origin, x, top - self.h)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
GL.glBindVertexArray(vao)
GL.glEnable(GL.GL_BLEND)
GL.glBlendFuncSeparate(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA, GL.GL_ZERO, GL.GL_ONE) # window alpha stays 1
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)
GL.glDisable(GL.GL_BLEND)
GL.glBindVertexArray(0)
GL.glUseProgram(0)
GL.glViewport(*[int(v) for v in old_vp])
def blit(self, x: int, top: int, target: int = 0) -> None:
"""top: GL y of the image's top edge (GL y grows upwards; image rows go down). target: the framebuffer it goes
into (only a see-through panel needs it: a plain one is copied into whatever is bound)."""
GL = self.GL
if self.blend:
self._draw_blended(x, top, target)
return
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
GL.glBlitFramebuffer(0, 0, self.w, self.h, x, top, x + self.w, top - self.h, GL.GL_COLOR_BUFFER_BIT,
GL.GL_NEAREST)
def close(self) -> None:
self.GL.glDeleteFramebuffers(1, [self.fbo])
self.GL.glDeleteTextures([self.tex])
class MiniText(str):
"""The stats overlay's numbers, from the pipeline: a str (the plain line, and a second one while a test runs)
for sinks that just print text, plus what GLWindowSink draws from it (framegen/hud.py):
parts, [(text, kind)] with kind "main", "dim" or "warn"; health, how well the PC keeps up ("good", "tight",
"behind", "off" with frame generation off, "" not known yet); second, the test line or ""; details, (name, value)
rows for the Detailed style, else None; graph, the Graphs style's data, else None."""
parts: tuple = ()
health: 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, 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
class GLWindowSink:
"""OpenGL window (GLFW): texture upload + draw, ~1-2 ms per 1080p frame, with an in-video settings menu.
Display settings come from `settings` (framegen.settings) and apply live; see SPECS there for what each
does. vsync off presents immediately (lowest latency, may tear); on a G-Sync/FreeSync display vsync on lets
VRR follow our frame timing instead of tearing. When the window is bigger than the frame it upscales: "fsr"
with AMD FSR 1 (~0.1 ms GPU at 1440p), "vsr" with NVIDIA RTX Video Super Resolution (needs NVIDIA's package
or the RTX Video SDK, see framegen/rtxvsr.py, and frames on the GPU), "bilinear" with a plain filtered blit. A
look (framegen/looks.py, drawn by framegen/looks_gl.py) goes on after that, at the window's size.
Keys: Insert (the overlay's key: run.py --overlay-key, from the launcher's Settings page), m, Tab or a right-click =
the overlay (framegen/menu.py: arrows, Enter and Tab in it, Esc closes it), i = interpolation on/off for this
session, s = stats overlay (off, minimal, detailed, graphs), f = fullscreen, u = next upscaler, k = look on/off,
j = next look (Shift+J: the one before), l = delay test (PS5 Remote Play), r = save the instant replay, b = save a
before & after video of it (framegen/replay.py), Ctrl+Q = quit. Esc never quits (it's a game's own key): Quit
is a row in the overlay.
restart_reasons(): labels of pending restart-only changes (the menu then offers "Restart now", which makes
write() return "restart"). choices: {key: allowed values} for options the program can't use right now;
unavailable: {key: reason} greys out a whole row. remote: a framegen.remote.Remote (the launcher's Settings
page), polled with the window's own events so its changes apply like the menu's.
hdr (settings "hdr" = HDR output, framegen/hdr.py): frames are HDR10 (float16 PQ BT.2020) and the window presents
them through a 10-bit DXGI swap chain in HDR10's colour space, whatever "present" says; fullscreen is then a
borderless window over the monitor. Looks and RTX VSR are off. If that swap chain can't be made (no HDR display,
no NVIDIA interop), self.hdr10 is False and the window is the usual SDR one: the caller then sends SDR frames.
With Windows' HDR on for the main display (KEEP_HDR), an SDR picture also goes through DXGI, an 8-bit swap chain,
whatever "present" says, and fullscreen is a borderless window over the monitor: OpenGL's own fullscreen would
switch the display to SDR while it's in front (self.keep_hdr; the "present" row says why it can't be changed).
overlay_of (window capture, framegen/window.py): () -> (the app's picture area, its monitor) in screen pixels, or
None while it's minimised. The window then sits over the app's picture (fullscreen: over its monitor), clicks
and keys go through to the app, it never takes the focus, and it's left out of the capture. The overlay's key is
then taken system-wide (Linux: framegen/globalkeys.py X11Keys, on X11 and through XWayland; Windows:
framegen/hotkeys.py), and only while the overlay is open are the keyboard and the mouse Summit's: the game has
every key but that one the rest of the time.
"""
NAMES = {"fsr": "FSR 1", "vsr": "RTX VSR", "bilinear": "bilinear", "off": "no upscaling"}
# Shown when the window opens, and again when the mouse moves over it (set in __init__, with the overlay's key).
KEYS_HINT = "Insert: Summit's overlay F: fullscreen Ctrl+Q: quit"
fill, panorama = "fit", None # Fill the screen (set from the settings in __init__)
compare = None # framegen.compare.Live (run.py): Compare's strips, labels and dividers (C, Shift+C)
_cmp = None # what Compare keeps in GL: {"scratch": (tex, fbo, w, h), "timer", "panels", "pic", "drag"}
def __init__(self, w: int, h: int, settings=None, restart_reasons=None, choices: dict | None = None,
unavailable: dict | None = None, overlay_of=None, hdr: bool = False, hdr_peak: float = 1000.0,
window_keys: dict | None = None, clean_source: bool = False, overlay_key: str | None = None) -> None:
if overlay_of is not None and X11 and WAYLAND:
# pyGLFW carries two builds of GLFW and loads its Wayland-only one in a Wayland session, which can't
# open the XWayland window the overlay needs ("glfw init failed"): load the X11 one. Read on the first
# `import glfw`, which is this one.
os.environ.setdefault("PYGLFW_LIBRARY_VARIANT", "x11")
# ...and PyOpenGL has to look functions up through GLX too: in a Wayland session it picks EGL, which
# gives an X11 window's context no newer functions (glTexStorage2D: RTX VSR crashed the engine).
# Read on PyOpenGL's first import, which is just below.
if "OpenGL" not in sys.modules:
os.environ.setdefault("PYOPENGL_PLATFORM", "glx")
import glfw
from OpenGL import GL
from .menu import Menu
from .overlaykey import glfw_key, pick
from .settings import Settings
self.settings = st = settings if settings is not None else Settings()
scaler, sharpness, vsr_quality = st.scaler, st.fsr_sharpness, st.vsr_quality
self.glfw, self.GL, self.w, self.h = glfw, GL, w, h
if overlay_of is not None and X11 and WAYLAND: # GLFW would pick Wayland: the overlay needs XWayland
glfw.init_hint(glfw.PLATFORM, glfw.PLATFORM_X11)
if not glfw.init():
raise RuntimeError("glfw init failed")
self.dx = None # a DxgiPresenter when the window presents through DXGI (_choose_presentation)
self.overlay_of = overlay_of
self.hdr10 = False # presenting HDR10 (hdr asked for, and the swap chain could be made)
self.keep_hdr = False # presenting SDR through DXGI because Windows' HDR is on (KEEP_HDR)
self.fs_style = FULLSCREEN_STYLE
self._choose_presentation(w, h, hdr, hdr_peak)
if self.dx is None:
if overlay_of is not None: # borderless, on top, click-through, and not focused when it opens
for hint, value in ((glfw.DECORATED, glfw.FALSE), (glfw.FLOATING, glfw.TRUE),
(glfw.FOCUSED, glfw.FALSE), (glfw.FOCUS_ON_SHOW, glfw.FALSE),
(glfw.MOUSE_PASSTHROUGH, glfw.TRUE)):
glfw.window_hint(hint, value)
if X11: # shown by _make_overlay, once the window manager has been told to leave it alone
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
self.win = self.glwin = glfw.create_window(min(w, 1600), min(h, 900), WINDOW_TITLE, None, None)
glfw.default_window_hints()
glfw.make_context_current(self.win)
glfw.swap_interval(1 if st.vsync else 0)
# Fullscreen stays up when another window takes the focus (a click on a second display, a notification), as
# borderless fullscreen does in games. GLFW's default minimises it, which with DXGI could also stall Present.
glfw.set_window_attrib(self.win, glfw.AUTO_ICONIFY, glfw.FALSE)
self._set_icon(glfw)
self.overlay, self.cmd, self.windowed_pos, self.remote = st.overlay, None, None, None
self.fill, self.panorama = st.fill, None # Fill the screen (framegen/fill.py); Panorama's pass once used
self._borderless = False # fullscreen as a borderless window (_set_borderless)
glfw.set_key_callback(self.win, self._on_key)
glfw.set_cursor_pos_callback(self.win, self._on_mouse)
glfw.set_mouse_button_callback(self.win, self._on_click)
glfw.set_scroll_callback(self.win, self._on_scroll)
self._hint_next = 0.0 # moving the mouse shows the keys again, at most this often
# settle(): in the first seconds chiaki-ng can show its window again (settle_hook, run.py, minimises it; later
# too, each time the video window gets the keys back, as Alt+Tab to chiaki-ng's window restores it), and all
# along a program can take the keys without the player doing anything (they're taken back).
self.settle_hook = None
self._was_front = True
self._had_front = False # the video window has had the keys since it opened (settle)
self._take_tries = 0 # settle's tries at taking the keys the window opened without
t = time.perf_counter()
self._settle_until, self._settle_next, self._any_until = t + 10.0, 0.0, t + 15.0
self._front_at: float | bool = t # when the video window last had the keys (from when it opened); False: off
self._keyed = False
self._took_from: set = set()
self.tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE) # FSR samples past edges
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)
if self.hdr10: # float16 PQ frames, as they are
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA16F, w, h, 0, GL.GL_BGR, GL.GL_HALF_FLOAT, None)
else:
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, None)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
self.fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
GL.glFramebufferTexture2D(GL.GL_READ_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.tex, 0)
# Stats text: a small strip of its own, blitted over the frame (no full-frame copy to draw on). Room for two
# lines (the second is the test-mode line); _ov_th is the height the current text uses.
self.ov_w, self.ov_h, self._ov_text, self._ov_tw, self._ov_th = 1600, 96, None, 0, 56
self.ov_tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.ov_tex)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA16 if self.hdr10 else GL.GL_RGBA8, self.ov_w, self.ov_h, 0,
GL.GL_BGR, GL.GL_UNSIGNED_SHORT if self.hdr10 else GL.GL_UNSIGNED_BYTE, None)
self.ov_fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.ov_fbo)
GL.glFramebufferTexture2D(GL.GL_READ_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, self.ov_tex, 0)
# Frames that are already on the GPU (CUDA tensors) are copied into the texture directly.
self.interop = None
renderer = GL.glGetString(GL.GL_RENDERER).decode(errors="replace")
try:
if any(k in renderer.lower() for k in ("llvmpipe", "softpipe", "swrast")):
# Software GL can't share memory with CUDA, and a failed attempt leaves CUDA in an error state.
raise RuntimeError("OpenGL is software-rendered, not on the NVIDIA GPU")
from .glcuda import CudaGLTexture
self.interop = CudaGLTexture(int(self.tex), w, h, hdr=self.hdr10)
print(f"[display] {renderer}: frames go to the screen straight from the GPU")
except Exception as e: # noqa: BLE001 - any failure just means the CPU upload path
print(f"[display] {renderer}: GPU->screen copy unavailable ({e}); uploading frames from the CPU")
self.gpu = self.interop is not None
from .fsr import FsrScaler, GpuTimer
self.fsr = self.vsr = self.vsr_out = None
try:
self.fsr = FsrScaler(GL, sharpness, hdr=self.hdr10)
except Exception as e: # noqa: BLE001 - shader trouble just means another scaler
print(f"[display] FSR 1 unavailable ({str(e)[:200]})")
# Anti-aliasing (the setting) as a GLSL pass on the game-sized texture (framegen/aa_gl.py: FXAA and CAS), in
# place of aa.py's torch filters: about 0.07 / 0.02 ms against about 1 ms at 1080p on an RTX 3090
# (devtools/aa_gl_bench.py), and it works on any graphics card. Not on software OpenGL when CUDA can do it
# (llvmpipe runs shaders on the CPU), nor with HDR10 frames. SUMMIT_AA_GL=1 / 0 forces it on / off.
self.aa_gl, self._aa_gl = None, {}
want = os.environ.get("SUMMIT_AA_GL", "")
software = any(k in renderer.lower() for k in ("llvmpipe", "softpipe", "swrast"))
if not self.hdr10 and want != "0":
from . import aa as _aa
if want == "1" or not software or not _aa._has_cuda():
try:
from .aa_gl import AaGl
self.aa_gl = AaGl(GL)
print(f"[display] anti-aliasing (FXAA, CAS) runs as an OpenGL pass on {renderer}")
except Exception as e: # noqa: BLE001 - aa.py's torch filters then
print(f"[display] anti-aliasing in OpenGL unavailable ({str(e)[:200]}); torch does it")
self.vsr_why = ("it isn't used with HDR output yet" if self.hdr10 else
"it needs frames decoded on the GPU (the default for PS5 Remote Play)")
self._vsr_args = None # (w, h, clean) while RTX VSR can run but isn't made yet (_vsr_ready)
if self.gpu and not self.hdr10: # RTX VSR works on frames that are already CUDA tensors (8-bit ones)
from .rtxvsr import unavailable_reason
why = unavailable_reason()
if why is None:
self._vsr_args = (w, h, clean_source)
self.vsr_why = why
if why is not None and scaler == "vsr":
print(f"[display] RTX VSR unavailable ({why})")
self.modes = [m for m, ok in (("fsr", self.fsr), ("vsr", self._vsr_args), ("bilinear", True), ("off", True)) if ok]
self.mode = scaler if scaler in self.modes else self.modes[0]
if self.mode == "vsr" and not self._vsr_ready():
self.mode = self.modes[0]
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.collector = None # framegen.stats.Collector (run.py sets it): the stage times go there
self.optimizer = None # framegen/optimize.py Control (run.py sets it): its countdown and result card are drawn
self._opt_panel, self._opt_state = None, None
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
from .looks_gl import LookRenderer
self.looks = LookState(st)
self.look_gl = None
if self.hdr10: # looks are made for SDR pictures
print("[display] Looks are off with HDR output")
else:
try:
self.look_gl = LookRenderer(GL, self.looks.library.lut)
except Exception as e: # noqa: BLE001 - looks are optional
print(f"[display] Looks unavailable ({str(e)[:200]})")
self._frame_no = 0
self._bake = None # instant replay with "Looks in clips": (texture, framebuffer, CudaGLReader)
self._bake_said = False
self.choices, self.unavailable = dict(choices or {}), dict(unavailable or {})
self.note_presentation()
self.overlay_key, note = pick(overlay_key) # the key that opens the overlay (framegen/overlaykey.py)
if note:
print(f"[display] {note}")
self._toggle = glfw_key(self.overlay_key, glfw)
self.KEYS_HINT = f"{self.overlay_key.name}: Summit's overlay F: fullscreen Ctrl+Q: quit"
over_game = overlay_of is not None
self.menu = Menu(st, allowed=self.allowed, disabled=self.disabled, restart_reasons=restart_reasons,
title=os.environ.get("SUMMIT_GAME", ""), toggle_key=self.overlay_key.name,
quit_label="Stop Summit" if over_game else "Quit",
quit_help=("Takes Summit's picture off the game. A game added to Summit by hand closes with "
"it; a Steam game keeps running, as it looks without Summit." if over_game else
"Closes the video window and stops playing."), window_keys=not over_game)
# Compare's Same area map in the overlay's Compare tab (self.compare is set by run.py after this)
self.menu.area_view = lambda: self.compare.area_view() if self.compare is not None else None
self.menu.area_click = lambda fx, fy: self.compare.map_click(fx, fy) if self.compare is not None else None
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.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
# for the session, so it opens where it was left)
self._menu_move: tuple | None = None # dragging it by its title: (cursor x, y, offset x, y) at the press
self._cursors: dict = {} # the mouse pointers made so far (arrow, hand, move)
self._cursor_shape = "arrow"
self._cursor = (0.0, 0.0) # the mouse, in window coordinates
self._menu_state = self._toast_state = None
self._status_at = 0.0 # when the overlay's header last got new numbers
self.xkeys, self._keyq, self._modal = None, queue.SimpleQueue(), False # over a game on Linux (_start_x11_keys)
self._toast_text, self._toast_until = self.KEYS_HINT, time.perf_counter() + 8.0
self._waited = -1 # wait(): the whole second the "no picture" note last said (-1: no wait going on)
self._unwatch = st.watch(self._apply)
self._overlay_at, self._overlay_check = None, 0.0
self.hotkeys, self._cursor_at = None, None
if overlay_of is not None:
self._make_overlay()
self._start_hotkeys(window_keys)
else:
print(f"[display] {self.overlay_key.name} opens Summit's overlay; Ctrl+Q quits (Esc doesn't)")
if st.fullscreen:
self._set_fullscreen(True)
self.take_focus()
def take_focus(self) -> None:
"""The keys (M, R, K...) go to this window from the start, without a click on it first: the program in front
when it opens is usually chiaki-ng, where the player just connected (framegen/winutil.bring_to_front). Not
for window capture's overlay, which never takes the focus."""
if self.overlay_of is not None or sys.platform != "win32":
return
from .winutil import bring_to_front
try:
if not bring_to_front(self.glfw.get_win32_window(self.win)):
print("[display] couldn't bring the video window to the front; click it once so the keys go to it")
except Exception as e: # noqa: BLE001 - only the focus: the video goes on
print(f"[display] couldn't bring the video window to the front ({str(e)[:160]})")
# Programs that take the keys by themselves during play: chiaki-ng (its stream window), the launcher (minimising
# itself) and the desktop (where the keys land when the window in front goes away). Any program in the first
# seconds, when the window has just opened.
TAKERS = ("chiaki.exe", "smoovplay.exe", "explorer.exe", "")
def settle(self) -> None:
"""Four times a second: in the first seconds, settle_hook (run.py: minimise chiaki-ng again if it showed its
window), and after them each time the video window is back in front (Alt+Tab to chiaki-ng's window restores
it, and its unsmoothed picture would stay behind, or over, this one); and all along, the keys taken back for
the video window when another program took them with no keyboard or mouse input from the player since the
video window had them (the player switching on purpose, Alt+Tab or a click, is input, and left alone; a
controller isn't, and switches nothing)."""
now = time.perf_counter()
if now < self._settle_next or self.overlay_of is not None:
return
self._settle_next = now + 0.25
early = now < self._settle_until
if early:
self._run_settle_hook()
if sys.platform != "win32" or self._front_at is False:
return
from .winutil import bring_to_front, foreground, ms_since_input
try:
ours = self.glfw.get_win32_window(self.win)
hwnd, exe = foreground()
back = hwnd == ours and not getattr(self, "_was_front", True)
self._was_front = hwnd == ours
if back and not early:
self._run_settle_hook()
if hwnd == ours:
self._front_at, self._had_front = now, True
return
if not getattr(self, "_had_front", True) and now < self._any_until and exe in self.TAKERS:
# Opened without the keys (Windows let the program in front keep them): take them, even if the mouse
# moved meanwhile (moving it isn't choosing another window). A few tries, then the usual rule.
self._take_tries = getattr(self, "_take_tries", 0) + 1
if bring_to_front(ours, nudge=True):
self._front_at, self._had_front = now, True
print(f"[display] the video window opened behind {exe or 'no window'}: took the keys")
elif self._take_tries >= 4:
self._had_front = True
print(f"[display] the video window opened behind {exe or 'no window'} and couldn't take the keys "
"(click it once)")
return
idle = ms_since_input()
if idle is None or idle / 1000.0 < now - self._front_at:
return # the player did something since: theirs to choose
if now >= self._any_until and exe not in self.TAKERS:
return
if bring_to_front(ours):
self._front_at = now
if exe not in self._took_from:
self._took_from.add(exe)
who = exe if exe in self.TAKERS[:3] else ("no window" if not exe else "another program")
print(f"[display] {who} took the keys: gave them back to the video window")
except Exception as e: # noqa: BLE001
print(f"[display] couldn't check which window is in front ({str(e)[:160]})")
self._front_at = False # (stops checking)
def take_keys(self) -> None:
"""Right after the window opens, while the program the player was in (chiaki-ng) is still in front: take the
keys from it before it's minimised (run.py), which would leave no window in front to take them from."""
if sys.platform != "win32" or self.overlay_of is not None:
return
from .winutil import bring_to_front
try:
if bring_to_front(self.glfw.get_win32_window(self.win), nudge=True):
self._front_at, self._had_front = time.perf_counter(), True
except Exception as e: # noqa: BLE001 - settle() tries again
print(f"[display] couldn't take the keys ({str(e)[:160]})")
def _run_settle_hook(self) -> None:
if self.settle_hook is None:
return
try:
self.settle_hook()
except Exception as e: # noqa: BLE001 - only tidying up: the video goes on
print(f"[display] {str(e)[:160]}")
self.settle_hook = None
def _on_mouse(self, win, x, y) -> None:
"""Moving the mouse over the video shows the keys for a moment (not over the menu or another message). Over
the overlay: it highlights what's under it, and drags whatever was pressed (the overlay by its title, a
slider, the scrollbar)."""
self._cursor = (x, y)
if self.menu.open:
if self._menu_move is not None:
cx, cy, ox, oy = self._menu_move
fx, fy = self._fb_scale()
self._menu_off = (ox + round((x - cx) * fx), oy + round((y - cy) * fy))
self._set_cursor("move")
return
p = self._menu_xy()
if p is not None:
self.menu.hover(*p)
inside = 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h
self._set_cursor(self.menu.cursor(*p) if inside else "arrow")
return
if self.compare is not None and self.compare.dragging: # Same area: the box or the scene dragged
at = self._compare_xy()
if at is not None:
self.compare.move(*at)
return
if self._cmp is not None and self._cmp.get("drag") and self.compare is not None:
at = self._compare_xy()
p = self.compare.plan()
if at is not None and p is not None:
from .compare import drag_split
self.compare.split = drag_split(p.layout, at[0], at[1], at[2], at[3])
return
now = time.perf_counter()
if now >= self._hint_next and not self.menu.open and now >= self._toast_until:
self._hint_next = now + 20.0
self.toast(self.KEYS_HINT, 3.0 if self.hotkeys is None else 6.0)
def _fb_scale(self) -> tuple[float, float]:
"""Framebuffer pixels per window coordinate (2 on a HiDPI screen)."""
glfw = self.glfw
ww, wh = glfw.get_window_size(self.win)
fw, fh = glfw.get_framebuffer_size(self.win)
return (fw / ww if ww else 1.0), (fh / wh if wh else 1.0)
def _set_cursor(self, shape: str) -> None:
"""The mouse pointer over the overlay: an arrow, a hand over things to click, the move cross on its title."""
if shape == self._cursor_shape:
return
glfw = self.glfw
self._cursor_shape = shape
std = {"hand": getattr(glfw, "POINTING_HAND_CURSOR", getattr(glfw, "HAND_CURSOR", None)),
"move": getattr(glfw, "RESIZE_ALL_CURSOR", getattr(glfw, "HAND_CURSOR", None))}.get(shape)
try:
if std is None:
glfw.set_cursor(self.win, None)
return
if shape not in self._cursors:
self._cursors[shape] = glfw.create_standard_cursor(std)
glfw.set_cursor(self.win, self._cursors[shape])
except Exception: # noqa: BLE001 - a plain arrow then
pass
def _menu_xy(self) -> tuple[float, float] | None:
"""The mouse as a pixel of the menu's image (from its top-left), or None while the menu isn't on screen."""
if self._menu_at is None or not self.menu.open:
return None
glfw = self.glfw
ww, wh = glfw.get_window_size(self.win)
fw, fh = glfw.get_framebuffer_size(self.win)
if not ww or not wh:
return None
cx, cy = self._cursor[0] * fw / ww, self._cursor[1] * fh / wh # framebuffer pixels from the top-left
mx, top = self._menu_at
return cx - mx, cy - (fh - top)
def _on_click(self, win, button, action, mods) -> None:
"""Mouse: right-click on the video opens the overlay. In it, a click picks a tab, a choice or an arrow (a
right-click on a row: the choice before), and a click outside closes it. Over a game (window capture) clicks
belong to the game: they come here only while the overlay is open (_sync_modal)."""
glfw = self.glfw
if action == glfw.RELEASE: # the end of a drag (the overlay by its title, a slider, the scrollbar)
if self._cmp is not None:
self._cmp["drag"] = False # (Compare's divider)
if self.compare is not None: # (Same area: a click without a drag goes back to picking)
at = self._compare_xy() if self.compare.dragging else None
self.compare.release(*at) if at is not None else self.compare.release()
self._menu_move = None
self.menu.release()
return
if action != glfw.PRESS or (self.overlay_of is not None and not self.menu.open):
return
right = button == glfw.MOUSE_BUTTON_RIGHT
if not self.menu.open:
if right:
self._do("menu")
elif self.compare is not None and self._cmp is not None: # Compare's divider, 2 strips: dragged
from .compare import near_divider
at, p = self._compare_xy(), self.compare.plan()
if at is not None and p is not None and near_divider(p, at[0], at[1], at[2], at[3], 12):
self._cmp["drag"] = True
elif at is not None and 0 <= at[0] < at[2] and 0 <= at[1] < at[3]:
self.compare.press(*at) # Same area: pick a cell, drag the area, click to pick again
return
p = self._menu_xy()
inside = p is not None and 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h
if not inside:
self.menu.open = False
return
if not right:
grabbed = self.menu.grab(*p)
if grabbed == "move":
self._menu_move = (*self._cursor, *self._menu_off)
self._set_cursor("move")
return
if grabbed == "drag":
return
self._menu_result(self.menu.click(*p, right=right))
def _on_scroll(self, win, dx, dy) -> None:
"""The wheel scrolls the overlay's page (or its open list); the highlight stays where it is."""
if self.menu.open and dy:
self.menu.scroll(dy)
elif dy and self.compare is not None: # Same area: the wheel zooms
self.compare.wheel(dy)
def _name(self, mode: str) -> str:
if mode == "vsr":
return f"RTX VSR q{self.vsr.quality if self.vsr is not None else self.settings.vsr_quality}"
return self.NAMES[mode]
def _vsr_ready(self) -> bool:
"""Make RTX VSR the first time it's picked, so a session that never uses it loads nothing for it (NVIDIA's
model and its graphics memory). If it can't start, it comes off the list (False)."""
if self.vsr is not None:
return True
if self._vsr_args is None:
return False
from .rtxvsr import make_vsr
w, h, clean = self._vsr_args
try:
self.vsr = make_vsr(w, h, self.settings.vsr_quality, clean=clean)
except Exception as e: # noqa: BLE001 - VSR is optional
self.vsr_why, self._vsr_args = str(e)[:200], None
if "vsr" in self.modes:
self.modes.remove("vsr")
print(f"[display] RTX VSR unavailable ({self.vsr_why})")
return False
print(f"[display] RTX VSR {self.vsr.how}"
+ (": NVIDIA's models for clean video (a capture card's raw frames)" if clean else ""))
return True
# ---- presentation ----------------------------------------------------------
def _set_icon(self, glfw) -> None:
"""Summit's icon in the title bar and on the taskbar instead of Python's (framegen/assets, rendered from
packaging/icons/summit.svg by packaging/icons/render.sh). A missing icon never stops a session."""
try:
from pathlib import Path
images = []
for n in (16, 24, 32, 48, 64):
bgra = cv2.imread(str(Path(__file__).with_name("assets") / f"icon_{n}.png"), cv2.IMREAD_UNCHANGED)
if bgra is not None and bgra.shape == (n, n, 4):
images.append((n, n, bgra[..., [2, 1, 0, 3]]))
if images:
glfw.set_window_icon(self.win, len(images), images)
except Exception as e:
print(f"[display] window icon not set: {e}")
def _choose_presentation(self, w: int, h: int, hdr: bool, hdr_peak: float) -> None:
"""How frames reach the screen: self.dx, a DXGI swap chain, or None for OpenGL's own; and how fullscreen is
done (self.fs_style). DXGI for HDR output (hdr), when the main display has Windows' HDR on (KEEP_HDR), and for
settings "present" = Low delay in a window. Window capture's overlay always draws with OpenGL."""
st = self.settings
if self.overlay_of is None:
hdr_on = KEEP_HDR and windows_hdr_on()
if hdr:
self._open_dxgi(w, h, hdr=True, peak=hdr_peak)
self.hdr10 = self.dx is not None
if self.dx is None and hdr_on: # (also when HDR output's 10-bit swap chain couldn't be made: SDR, then)
self._open_dxgi(w, h, keep_hdr=True)
self.keep_hdr = self.dx is not None
if self.dx is not None:
# Fullscreen with this swap chain is a borderless window: GLFW's fullscreen could stall it.
self.fs_style = "borderless" if FULLSCREEN_STYLE == "none" else FULLSCREEN_STYLE
return
if hdr_on:
return # (it said why; Low delay would fail the same way)
if st.present != "dxgi":
return # the standard presentation
if self.overlay_of is not None:
print("[display] window capture: standard presentation (the overlay draws with OpenGL)")
elif not st.fullscreen or FULLSCREEN_STYLE != "none":
self._open_dxgi(w, h)
else:
print("[display] fullscreen: standard presentation (Low delay is for windowed play; fullscreen already "
"skips the compositor)")
def note_presentation(self) -> None:
"""The "present" row can't be changed while Windows' HDR keeps the window on DXGI (it overrides HDR output's
reason: keep_hdr is HDR output's fallback too). run.py puts it back if it drops HDR output's rows."""
if self.keep_hdr:
self.unavailable["present"] = KEEP_HDR_REASON
def _open_dxgi(self, w: int, h: int, hdr: bool = False, peak: float = 1000.0, keep_hdr: bool = False) -> None:
"""Settings "present" = "dxgi" (Experimental): the video window gets a DXGI flip-model swap chain and no OpenGL
context of its own (GLFW NO_API); OpenGL draws on a hidden window (framegen/dxgi_present.py). In a window that
skips the compositor's copy: less delay, and G-Sync/FreeSync work. Leaves self.dx None (and no windows) if
any of it fails, so the caller opens the usual OpenGL window. hdr: a 10-bit HDR10 swap chain (HDR output).
keep_hdr: an 8-bit one because Windows' HDR is on (KEEP_HDR); only what's logged differs."""
glfw = self.glfw
from .dxgi_present import DxgiPresenter
win = glwin = None
try:
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
glwin = glfw.create_window(64, 64, "framegen (OpenGL)", None, None)
glfw.default_window_hints()
if not glwin:
raise RuntimeError("couldn't open an OpenGL context")
glfw.window_hint(glfw.CLIENT_API, glfw.NO_API)
win = glfw.create_window(min(w, 1600), min(h, 900), WINDOW_TITLE, None, None)
glfw.default_window_hints()
if not win:
raise RuntimeError("couldn't open the window")
glfw.make_context_current(glwin)
fw, fh = glfw.get_framebuffer_size(win)
self.dx = DxgiPresenter(self.GL, glfw.get_win32_window(win), fw, fh, hdr=hdr, peak_nits=peak)
self.win, self.glwin = win, glwin
from .dxgi_present import BUFFERS
test = ("copy", 2) != (self.dx.mode, BUFFERS) or FULLSCREEN_STYLE != "none"
print("[display] window presentation: DXGI flip model"
+ (", HDR10 (10-bit, PQ, BT.2020)" if hdr else "")
+ ((", tearing allowed with VSync off" + (" in fullscreen" if keep_hdr else "")) if self.dx.tearing
else "")
+ (", as Windows' HDR is on: fullscreen keeps it on (FRAMEGEN_KEEP_HDR=0: OpenGL's own)" if keep_hdr
else "") + " (Experimental)"
+ (f" [testing: {self.dx.mode}, {BUFFERS} buffers, fullscreen {FULLSCREEN_STYLE}]" if test else ""))
except Exception as e: # noqa: BLE001 - any failure: OpenGL's own presentation
glfw.default_window_hints()
glfw.make_context_current(None)
for wnd in (win, glwin):
if wnd:
glfw.destroy_window(wnd)
self.dx = None
if hdr:
print(f"[display] HDR output unavailable ({str(e)[:200]}); showing HDR in SDR")
elif keep_hdr:
print(f"[display] Windows' HDR is on, but DXGI presentation is unavailable ({str(e)[:200]}); using "
"OpenGL's own. Fullscreen then switches the display to SDR while it's in front, which can change "
"the colours; a window keeps HDR on")
else:
print(f"[display] low-delay window presentation unavailable ({str(e)[:200]}); using OpenGL's own")
def _target(self) -> int:
"""The framebuffer the picture is drawn into: the window's own, or DXGI's offscreen one."""
return self.dx.fbo if self.dx is not None else 0
def _may_tear(self) -> bool:
"""Whether VSync off may tear. Fullscreen, and a window with Low delay picked, as before. Not a window that's
on DXGI only because Windows' HDR is on (KEEP_HDR): with the standard presentation it never tore."""
return not self.keep_hdr or self._borderless or self.settings.present == "dxgi"
def _present(self) -> None:
if self.dx is not None:
if self.glfw.get_window_attrib(self.win, self.glfw.ICONIFIED):
return # minimised: nothing to show, and a flip-model Present can wait for a window nobody sees
t0 = time.perf_counter()
self.dx.present(self.settings.vsync, tear=self._may_tear())
_say_if_slow("DXGI Present", t0)
else:
self._dev_shot()
self.glfw.swap_buffers(self.win)
def _dev_shot(self) -> None:
"""For screenshots (devtools): with SUMMIT_SHOT=<prefix> set, a file <prefix>.req holding a name makes this
frame, exactly as about to be shown, go to <prefix>-<name>.png (then the .req file is removed)."""
prefix = os.environ.get("SUMMIT_SHOT")
if not prefix or not os.path.exists(prefix + ".req"):
return
try:
with open(prefix + ".req", encoding="utf-8") as f:
name = f.read().strip() or "shot"
GL = self.GL
fw, fh = self.glfw.get_framebuffer_size(self.win)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, 0)
GL.glReadBuffer(GL.GL_BACK)
GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1)
data = GL.glReadPixels(0, 0, fw, fh, GL.GL_BGR, GL.GL_UNSIGNED_BYTE)
img = np.frombuffer(data, np.uint8).reshape(fh, fw, 3)[::-1]
cv2.imwrite(f"{prefix}-{name}.png", img)
os.remove(prefix + ".req")
except Exception as e: # noqa: BLE001 - a devtool: never in the way of the picture
print(f"[display] SUMMIT_SHOT failed: {e}")
os.environ.pop("SUMMIT_SHOT", None)
# ---- settings ------------------------------------------------------------
def allowed(self, key: str, value) -> bool:
if key == "scaler":
return value in self.modes
if key.startswith("compare_"): # an area cell past the strips, Flip with more than 2, Freeze for frame gen
from .compare import allowed
if not allowed(key, value, self.settings.values()):
return False
return value in self.choices.get(key, (value,))
def disabled(self, key: str) -> str | None:
if key == "vsr_quality" and self.vsr is None and self._vsr_args is None:
return f"RTX VSR isn't available: {self.vsr_why}."
if key == "fsr_sharpness" and self.fsr is None:
return "FSR 1 couldn't start on this GPU."
return self.unavailable.get(key)
def _apply(self, key: str) -> None:
"""A setting changed (menu, hotkey or elsewhere): apply the ones the window owns."""
st, glfw = self.settings, self.glfw
if key == "scaler" and st.scaler in self.modes:
if st.scaler != "vsr" or self._vsr_ready():
self.mode = st.scaler
else:
self.toast(f"RTX VSR couldn't start: {self.vsr_why}", 5.0)
elif key == "fsr_sharpness" and self.fsr is not None:
self.fsr.sharpness = st.fsr_sharpness
elif key == "vsr_quality" and self.vsr is not None:
self.vsr.quality = st.vsr_quality
elif key == "overlay":
self.overlay = st.overlay
elif key == "fill":
self.fill = st.fill
if not self.menu.open: # a hotkey: say what it did, and that it's the same picture
from .settings import BY_KEY
self.toast(f"Fill the screen: {BY_KEY['fill'].name(st.fill)}"
+ ("" if st.fill == "fit" else "\nThe same 16:9 picture: consoles send 16:9 only"), 3.0)
return
elif key == "fullscreen":
if self.dx is not None and st.fullscreen and self.fs_style == "none":
self.toast("Fullscreen starts next time you press Play: Low delay works in a window only", 5.0)
return
self._set_fullscreen(st.fullscreen)
if (st.fullscreen and self.dx is None and self.overlay_of is None and KEEP_HDR and windows_hdr_on()):
# Windows' HDR was turned on after the window opened (with OpenGL's own presentation)
self.toast("Windows' HDR is on now: fullscreen switches the display to SDR until you press Play again",
6.0)
return
elif key == "vsync":
glfw.swap_interval(1 if st.vsync else 0)
elif key in ("look", "look_on"):
if not self.menu.open:
self.toast(f"Look: {self.looks.name() if st.look_on else 'Off'}")
return
if not self.menu.open: # a hotkey: say what it did
from .settings import BY_KEY
spec = BY_KEY[key]
self.toast(f"{spec.label}: {spec.name(getattr(st, key))}")
def _make_overlay(self) -> None:
"""Window capture: no focus ever (WS_EX_NOACTIVATE: the app keeps it, and some apps stop drawing without it),
and out of the capture, which then sees the app underneath (framegen/window.py)."""
import ctypes
if sys.platform != "win32":
self._make_overlay_x11()
return
from .window import exclude_from_capture
hwnd = self.glfw.get_win32_window(self.win)
if not exclude_from_capture(hwnd):
print("[display] couldn't leave this window out of the capture (that needs Windows 10 version 2004 or "
"newer); it would capture itself. Put the app's window on another monitor.")
u32 = ctypes.windll.user32
u32.GetWindowLongW.argtypes = [ctypes.c_void_p, ctypes.c_int]
u32.SetWindowLongW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_long]
u32.SetWindowLongW(hwnd, -20, u32.GetWindowLongW(hwnd, -20) | 0x08000000) # GWL_EXSTYLE |= WS_EX_NOACTIVATE
self._follow()
def _make_overlay_x11(self) -> None:
"""Window capture on X11 (framegen/window_x11.py): the picture goes over the game as an override-redirect
window, one the window manager doesn't manage: no frame, never focused (the game keeps the keys), and above
everything, a fullscreen game included. Clicks go through it (GLFW's mouse passthrough). The capture reads
the game's own off-screen picture, so this window isn't in it."""
import ctypes
import ctypes.util
glfw = self.glfw
self._x11 = None
try:
class Attrs(ctypes.Structure): # XSetWindowAttributes
_fields_ = [("background_pixmap", ctypes.c_ulong), ("background_pixel", ctypes.c_ulong),
("border_pixmap", ctypes.c_ulong), ("border_pixel", ctypes.c_ulong),
("bit_gravity", ctypes.c_int), ("win_gravity", ctypes.c_int),
("backing_store", ctypes.c_int), ("backing_planes", ctypes.c_ulong),
("backing_pixel", ctypes.c_ulong), ("save_under", ctypes.c_int),
("event_mask", ctypes.c_long), ("do_not_propagate_mask", ctypes.c_long),
("override_redirect", ctypes.c_int), ("colormap", ctypes.c_ulong),
("cursor", ctypes.c_ulong)]
x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
dpy = ctypes.cast(glfw.get_x11_display(), ctypes.c_void_p)
xid = int(glfw.get_x11_window(self.win))
x.XChangeWindowAttributes.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong,
ctypes.POINTER(Attrs)]
x.XRaiseWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
x.XFlush.argtypes = [ctypes.c_void_p]
x.XChangeWindowAttributes(dpy, xid, 1 << 9, ctypes.byref(Attrs(override_redirect=1))) # CWOverrideRedirect
self._x11 = (x, dpy, xid)
except Exception as e: # noqa: BLE001 - still an always-on-top window that takes no focus when it opens
print(f"[display] the picture over the game is an ordinary window here ({str(e)[:120]}): if it takes the "
"keys, click the game")
self._follow()
glfw.show_window(self.win)
self._raise_x11()
def _raise_x11(self) -> None:
"""Back above everything: a window manager raising the game (a click on it) puts it over an unmanaged window."""
if getattr(self, "_x11", None):
x, dpy, xid = self._x11
x.XRaiseWindow(dpy, xid)
x.XFlush(dpy)
def _start_hotkeys(self, picked: dict | None) -> None:
"""Window capture: the picture over the game never has the keys, so the overlay's key is taken system-wide.
Linux: _start_x11_keys. Windows: shortcuts (framegen/hotkeys.py) registered for this thread, the one that
draws (_events takes their messages). Says what it got, over the picture and in the log."""
if sys.platform != "win32":
self._start_x11_keys()
return
from .hotkeys import Hotkeys, describe
from .overlaykey import windows
picked = dict(picked or {})
if windows(self.overlay_key):
picked.setdefault("menu", windows(self.overlay_key))
try:
self.hotkeys = Hotkeys(picked)
except Exception as e: # noqa: BLE001 - no shortcuts: the launcher's Stop and Settings page still work
print(f"[display] no shortcuts ({str(e)[:120]}): Stop and Settings on SmoovPlay's Play page")
keys = describe(self.hotkeys.got) if self.hotkeys is not None else ""
if self.hotkeys is not None:
print(self.hotkeys.report(), flush=True)
for name in self.hotkeys.taken:
print(f"[display] {name} is taken by another program")
if self.hotkeys.got.get("menu"):
self.menu.toggle_key = self.hotkeys.got["menu"]
self.KEYS_HINT = ("SmoovPlay's keys here (other keys go to the app):\n" + keys if keys
else "Keys go to the app: use Stop and Settings on SmoovPlay's Play page")
self.toast(self.KEYS_HINT, 12.0)
def _start_x11_keys(self) -> None:
"""Window capture on Linux: the overlay's key (Insert, or the launcher's choice) as an X key grab, on X11 and
through XWayland (framegen/globalkeys.py X11Keys), so it works while the game has the keyboard. Nothing else
is taken from the game: its other keys, Esc included, never reach Summit. Presses arrive on the key thread
and are handed to the video loop (_events)."""
name = self.overlay_key.name
why = "" if X11 else "this session has no X11 or XWayland to take a key through"
if not why:
from .globalkeys import X11Keys
from .overlaykey import x11
keys = X11Keys({x11(self.overlay_key): lambda: self._keyq.put(("toggle", False))}, bare=True)
try:
keys.start()
why = keys.error or ("" if keys.got else f"{name} is taken by another program")
except Exception as e: # noqa: BLE001 - no key: the launcher's Stop still works
why = str(e)[:120]
if why:
keys.stop()
else:
self.xkeys = keys
if why:
print(f"[display] no key for the overlay ({why}): pick another overlay key in Summit's settings, or close "
"the game to stop")
self.KEYS_HINT = f"Summit is enhancing this game\nNo overlay here: {why}"
else:
print(f"[display] {name} opens Summit's overlay; every other key stays the game's", flush=True)
self.KEYS_HINT = f"Summit is enhancing this game\n{name} opens the overlay"
self.toast(self.KEYS_HINT, 8.0)
# an X key (its keysym name, lower case) -> what it does in the open overlay (framegen/menu.py Menu.key)
_X_NAV = {"up": "up", "down": "down", "left": "left", "right": "right", "return": "enter", "kp_enter": "enter",
"escape": "back", "backspace": "back", "tab": "next_tab", "next": "next_tab", "prior": "prev_tab"}
def _sync_modal(self) -> None:
"""Window capture on Linux: while the overlay is open the keyboard and the mouse are Summit's (the game would
otherwise act on the arrows and Enter, and clicks would go through the overlay to it); the moment it closes
they're the game's again. Called every time round the video loop: X11Keys gives the keyboard back by itself
if these calls stop coming while the overlay is open (a stall), so the game is never left without its keys."""
if self.xkeys is None:
return
on = self.menu.open
self.xkeys.set_modal(on, lambda name, shift: self._keyq.put((name, shift)))
if on != self._modal:
self._modal = on
try: # clicks: to the overlay while it's open, through to the game otherwise
self.glfw.set_window_attrib(self.win, self.glfw.MOUSE_PASSTHROUGH,
self.glfw.FALSE if on else self.glfw.TRUE)
except Exception as e: # noqa: BLE001 - the keys still work
print(f"[display] the mouse stays the game's while the overlay is open ({str(e)[:100]})")
# a Windows shortcut's key (framegen/hotkeys.py NAV) -> what it does in the open overlay
_HOTKEY_NAV = {"Up": "up", "Down": "down", "Left": "left", "Right": "right", "Enter": "enter", "Esc": "back",
"Backspace": "back", "Tab": "next_tab"}
def _events(self) -> None:
"""glfw.poll_events, after the system-wide keys' presses (window capture). Windows: the shortcuts' messages
come to the thread, not a window, and GLFW would drop them. Linux: the key thread's queue. The overlay's own
keys are taken only while it's open."""
if self.hotkeys is not None:
self.hotkeys.set_nav(self.menu.open)
for what in self.hotkeys.poll():
if not what.startswith("nav:"):
self._do(what)
elif self.menu.open:
self._menu_result(self.menu.key(self._HOTKEY_NAV[what[4:]]))
self.hotkeys.set_nav(self.menu.open)
if self.xkeys is not None:
while True:
try:
what, shift = self._keyq.get_nowait()
except queue.Empty:
break
if what == "toggle":
self._do("menu")
elif self.menu.open and what in self._X_NAV:
nav = self._X_NAV[what]
self._menu_result(self.menu.key("prev_tab" if nav == "next_tab" and shift else nav))
self._sync_modal()
self.glfw.poll_events()
def _hint_on_hover(self, r) -> None:
"""Window capture: the overlay gets no mouse events (clicks go to the app), so the pointer is looked at here
(from _follow): moving it over the picture shows the keys again, at most every 20 s."""
import ctypes
from ctypes import wintypes as wt
pt = wt.POINT()
if not ctypes.windll.user32.GetCursorPos(ctypes.byref(pt)):
return
at, moved = (pt.x, pt.y), self._cursor_at is not None and (pt.x, pt.y) != self._cursor_at
self._cursor_at = at
if moved and r.x <= pt.x < r.x + r.w and r.y <= pt.y < r.y + r.h:
self._on_mouse(self.win, 0, 0)
def _follow(self) -> None:
"""Window capture: keeps the overlay over the app's picture (fullscreen: its monitor), four times a second."""
now = time.perf_counter()
if now < self._overlay_check:
return
self._overlay_check = now + 0.25
where = self.overlay_of()
if where is None: # minimised: stay put until it's back
return
client, monitor = where
if X11 and self.settings.fullscreen: # the monitor --monitor names, else the one the game is on
monitor = self._monitor_rect(client) or monitor
r = monitor if self.settings.fullscreen else client
self._raise_x11()
if self.hotkeys is not None:
self._hint_on_hover(r)
at = (r.x, r.y, r.w, r.h)
if at != self._overlay_at:
self._overlay_at = at
self.glfw.set_window_pos(self.win, r.x, r.y)
self.glfw.set_window_size(self.win, r.w, r.h)
def _monitor_rect(self, client):
"""Window capture on X11: the monitor the picture covers in fullscreen, as a rectangle in screen pixels: the
one --monitor names (io.MONITOR), else the one holding the middle of the game's window. None if GLFW can't say."""
glfw = self.glfw
try:
rects = []
for m in glfw.get_monitors():
(x, y), mode = glfw.get_monitor_pos(m), glfw.get_video_mode(m)
rects.append((m, type(client)(x, y, mode.size.width, mode.size.height)))
if MONITOR: # (by name: GLFW hands out a new pointer object for the same monitor on every call)
want = glfw.get_monitor_name(pick_monitor(glfw))
return next(r for m, r in rects if glfw.get_monitor_name(m) == want)
cx, cy = client.x + client.w // 2, client.y + client.h // 2
return next((r for _, r in rects if r.x <= cx < r.x + r.w and r.y <= cy < r.y + r.h), None)
except Exception: # noqa: BLE001
return None
def _set_fullscreen(self, on: bool) -> None:
glfw, win = self.glfw, self.win
if self.overlay_of is not None: # over the app's monitor, as a borderless window: no fullscreen mode change
self._overlay_at, self._overlay_check = None, 0.0
self._follow()
return
if not WAYLAND and (self.fs_style == "borderless" or (self.dx is None and self.fs_style != "monitor")):
self._set_borderless(on)
return
if bool(glfw.get_window_monitor(win)) == on:
return
t0 = time.perf_counter()
if not on:
x, y, ww, wh = self.windowed_pos or (80, 80, min(self.w, 1600), min(self.h, 900))
glfw.set_window_monitor(win, None, x, y, ww, wh, 0)
else:
self.windowed_pos = (*((0, 0) if WAYLAND else glfw.get_window_pos(win)), *glfw.get_window_size(win))
mon = pick_monitor(glfw)
mode = glfw.get_video_mode(mon)
glfw.set_window_monitor(win, mon, 0, 0, mode.size.width, mode.size.height, mode.refresh_rate)
_say_if_slow("fullscreen " + ("on" if on else "off"), t0)
glfw.swap_interval(1 if self.settings.vsync else 0)
def _set_borderless(self, on: bool) -> None:
"""Fullscreen as a borderless window over the monitor, as games' borderless mode (the standard presentation's
fullscreen, and HDR output's): no GLFW fullscreen monitor, so no always-on-top window (Alt+Tab to another
program puts that one in front) and no video mode request. Windows tucks the taskbar under it while it's in
front."""
glfw, win = self.glfw, self.win
if self._borderless == on:
return
t0 = time.perf_counter()
if on:
self.windowed_pos = (*glfw.get_window_pos(win), *glfw.get_window_size(win))
mon = pick_monitor(glfw)
mx, my = glfw.get_monitor_pos(mon)
mode = glfw.get_video_mode(mon)
glfw.set_window_attrib(win, glfw.DECORATED, glfw.FALSE)
glfw.set_window_pos(win, mx, my)
glfw.set_window_size(win, mode.size.width, mode.size.height)
else:
x, y, ww, wh = self.windowed_pos or (80, 80, min(self.w, 1600), min(self.h, 900))
glfw.set_window_attrib(win, glfw.DECORATED, glfw.TRUE)
glfw.set_window_pos(win, x, y)
glfw.set_window_size(win, ww, wh)
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], compared: bool = False) -> None:
"""What the picture is made with, in words, for the stats overlay (only when it changes). compared: Compare
drew upscaler or look strips this frame, each timed on its own label, so no upscale time goes to the stats."""
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 ([] if compared else 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 display_mode(self) -> tuple[int, int, float] | None:
"""The monitor fullscreen goes to (pick_monitor): its own width, height and refresh rate. None if unknown."""
try:
mode = self.glfw.get_video_mode(pick_monitor(self.glfw))
return mode.size.width, mode.size.height, float(mode.refresh_rate)
except Exception: # noqa: BLE001
return None
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
_NAV = {"UP": "up", "DOWN": "down", "LEFT": "left", "RIGHT": "right", "ENTER": "enter", "KP_ENTER": "enter",
"BACKSPACE": "back", "ESCAPE": "back", "PAGE_DOWN": "next_tab", "PAGE_UP": "prev_tab"}
def _menu_result(self, r: str | None) -> None:
"""What a key or a click in the overlay asked for (Menu.key, Menu.click)."""
if r == "close":
self.menu.open = False
elif r in ("restart", "quit"):
self.menu.open = False
self.cmd = r
elif r in ("save_replay", "save_summary"):
self.cmd = r
elif r and r.startswith("optimize"): # the Optimize tab (framegen/optimize.py, through the pipeline)
self.menu.open = False
self.cmd = r
def _do(self, action: str) -> None:
"""What the keys do, by name: the window's own (_on_key) and the system-wide ones over a game (_events)."""
st = self.settings
if action == "menu":
self.menu.open = not self.menu.open
self._toast_until = 0.0
elif action == "quit":
self.cmd = "quit"
elif action == "fullscreen":
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, Bar, Off...
if not st.overlay:
st.set("overlay_style", "minimal")
st.set("overlay", True)
elif st.overlay_style == "minimal":
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)
def _on_key(self, win, key, scancode, action, mods) -> None:
"""The video window's own keys (it has the keyboard: Remote Play, a capture card, a file). Over a game the
keys are the game's and none come here."""
glfw, st = self.glfw, self.settings
nav = {getattr(glfw, "KEY_" + k): v for k, v in self._NAV.items()}
in_menu = self.menu.open and (key in nav or key == glfw.KEY_TAB)
if key == glfw.KEY_V and action == glfw.RELEASE and self.compare is not None and not self.menu.open:
self.compare.key("flip_up") # Flip: let go of V, strip 2 (B)
return
if action == glfw.REPEAT and not in_menu:
return
if action not in (glfw.PRESS, glfw.REPEAT):
return
self._keyed = True # the player has pressed a key here
held = mods & (glfw.MOD_CONTROL | glfw.MOD_ALT | glfw.MOD_SHIFT | glfw.MOD_SUPER)
if (key, held) == self._toggle:
if action == glfw.PRESS:
self._do("menu")
return
o = self.optimizer.state() if self.optimizer is not None and not self.menu.open else "idle"
if o != "idle" and key in (glfw.KEY_ESCAPE, glfw.KEY_BACKSPACE): # Optimize: stop, or keep my settings
self.cmd = "optimize_cancel"
return
if o == "card" and key in (glfw.KEY_ENTER, glfw.KEY_KP_ENTER): # Optimize's card: Apply
self.cmd = "optimize_apply"
return
if in_menu:
name = ("prev_tab" if mods & glfw.MOD_SHIFT else "next_tab") if key == glfw.KEY_TAB else nav[key]
self._menu_result(self.menu.key(name))
return
if self.compare is not None and not self.menu.open and not held & ~glfw.MOD_SHIFT:
name = self._compare_key(key, mods)
r = self.compare.key(name) if name else None
if isinstance(r, str):
self.toast(r, 4.0)
if r:
return
if key in (glfw.KEY_M, glfw.KEY_TAB):
self._do("menu")
elif key == glfw.KEY_ESCAPE: # never quits: say what does
self.toast(self.KEYS_HINT, 4.0)
elif key == glfw.KEY_Q:
if mods & glfw.MOD_CONTROL:
self._do("quit")
else:
self.toast("Ctrl+Q quits (or Quit in the overlay)", 3.0)
elif key == glfw.KEY_I:
self._do("smooth")
elif key == glfw.KEY_S:
self._do("stats")
elif key == glfw.KEY_U:
st.step("scaler", 1, self.allowed)
elif key == glfw.KEY_Z:
st.step("fill", 1, self.allowed)
elif key == glfw.KEY_K:
self.looks.toggle()
elif key == glfw.KEY_J:
self.looks.next(-1 if mods & glfw.MOD_SHIFT else 1)
elif key == glfw.KEY_F:
self._do("fullscreen")
elif key == glfw.KEY_L:
self.cmd = "delay_test" # the pipeline runs it (PS5 Remote Play only)
elif mods & glfw.MOD_CONTROL and glfw.KEY_1 <= key <= glfw.KEY_6:
self.cmd = "save_replay:" + str((15, 30, 60, 180, 300, 600)[key - glfw.KEY_1]) # PS5-style length picker
elif key == glfw.KEY_R:
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
elif key == glfw.KEY_C: # Compare (framegen/compare.py): on and off; Shift+C: the next thing to compare
if mods & glfw.MOD_SHIFT:
st.step("compare_dim", 1)
if not st.compare:
st.set("compare", True)
else:
st.set("compare", not st.compare)
def _compare_key(self, key: int, mods: int) -> str | None:
"""The video window's Compare keys by name (framegen/compare.py Live.key): A Same area, Space Freeze, V Flip
(held), and while Same area is on the arrows, Enter, Esc, 1-4 and + / -."""
glfw = self.glfw
named = {glfw.KEY_A: "area", glfw.KEY_SPACE: "freeze", glfw.KEY_V: "flip_down", glfw.KEY_UP: "up",
glfw.KEY_DOWN: "down", glfw.KEY_LEFT: "left", glfw.KEY_RIGHT: "right", glfw.KEY_ENTER: "enter",
glfw.KEY_KP_ENTER: "enter", glfw.KEY_ESCAPE: "back", glfw.KEY_EQUAL: "zoom_in",
glfw.KEY_KP_ADD: "zoom_in", glfw.KEY_MINUS: "zoom_out", glfw.KEY_KP_SUBTRACT: "zoom_out"}
if glfw.KEY_1 <= key <= glfw.KEY_4 and not mods & glfw.MOD_CONTROL:
return str(key - glfw.KEY_1 + 1)
return named.get(key)
# ---- drawing -------------------------------------------------------------
def _layout(self) -> tuple[int, int, float, int, int, int, int]:
fw, fh = self.glfw.get_framebuffer_size(self.win)
if self.dx is not None:
self.dx.resize(fw, fh) # cheap when the size hasn't changed
s = min(fw / self.w, fh / self.h) # letterbox, keep aspect
if self.overlay_of is not None and not X11: # window capture: the frame is the app's window squeezed to the
return fw, fh, s, fw, fh, 0, 0 # stream's size, so it's stretched back over it to fill the overlay exactly
if self.overlay_of is not None: # X11: frames keep the game's shape, so fullscreen fits them to the monitor
dw, dh = round(self.w * s), round(self.h * s)
return fw, fh, s, dw, dh, (fw - dw) // 2, (fh - dh) // 2
dw, dh, x0, y0 = layout(self.fill, fw, fh, self.w, self.h) # (Fill the screen: always the same 16:9 picture)
return fw, fh, s, dw, dh, x0, y0
def _output_size(self, dw: int, dh: int) -> tuple[int, int] | None:
"""Output resolution: the size to make the picture at (its shape kept, within the size asked for), or None
when that's the screen's own (the upscaler then draws straight to the screen)."""
from .settings import parse_res
want = parse_res(getattr(self.settings, "output_res", "screen"))
if want is None or dw <= 0 or dh <= 0:
return None
k = min(want[0] / dw, want[1] / dh)
ow, oh = max(2, round(dw * k)) & ~1, max(2, round(dh * k)) & ~1
return None if abs(ow - dw) <= 2 and abs(oh - dh) <= 2 else (ow, oh)
def _out_target(self, w: int, h: int) -> int:
"""The framebuffer the picture is drawn into at the output resolution (made again when the size changes)."""
GL = self.GL
have = getattr(self, "_out", None)
if have is not None and have[2:] == (w, h):
return have[1]
if have is not None:
GL.glDeleteFramebuffers(1, [have[1]])
GL.glDeleteTextures([have[0]])
tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo)
GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0)
self._out = (tex, fbo, w, h)
print(f"[display] output resolution {w}x{h}", flush=True)
return fbo
def _panorama_on(self, fw: int, fh: int) -> bool:
return self.fill == "panorama" and self.overlay_of is None and wider(fw, fh, self.w, self.h)
def _ui_rect(self, fw: int, fh: int, dw: int, dh: int, x0: int, y0: int) -> tuple[int, int, int, int]:
"""Where the menu, messages and stats go: the picture as seen on the screen."""
return (0, 0, fw, fh) if self._panorama_on(fw, fh) else visible(dw, dh, x0, y0, fw, fh)
def _draw_ui(self, x0: int, y0: int, dw: int, dh: int) -> None:
"""The overlay and messages, on top of everything else. Images are redrawn only when they change."""
ui = max(0.5, dh / 1080) * self.settings.ui_scale
op = self.settings.ui_opacity
if not self.menu.open:
self._menu_top = self._menu_at = self._menu_move = None
self._set_cursor("arrow")
else:
state = (self.menu.state(), round(ui, 3), op, dw)
if state != self._menu_state:
# never wider than the picture (less a margin each side): narrower, not cut off
self.menu_panel.update_rgba(self.menu.render(ui, op, dw - 2 * int(16 * ui)))
self._menu_state = state
p = self.menu_panel
# Centred top to bottom when it opens, on the side away from the stats' corner (so they stay in view
# next to it, live, while settings change), and it stays put until it closes. Inside the picture
# whatever happens.
where = (y0, dh)
if self._menu_top is None or self._menu_top[1] != where:
self._menu_top = (y0 + (dh + p.h) // 2, where, self.settings.overlay_corner.endswith("right"))
ox, oy = self._menu_off # where the player dragged it (framebuffer px, y down)
base_x = x0 + int(32 * ui) if self._menu_top[2] else max(x0, x0 + dw - p.w - int(32 * ui))
# inside the picture whatever happens: a drag past its edge stops there (and is kept as stopped, so
# dragging back moves it at once)
top = min(y0 + dh, max(self._menu_top[0] - oy, y0 + p.h))
mx = max(x0, min(base_x + ox, x0 + dw - p.w))
self._menu_off = (mx - base_x, self._menu_top[0] - top)
self._menu_at = (mx, top) # where the mouse finds it (see _menu_xy)
self.menu_panel.blit(mx, top, self._target())
if time.perf_counter() < self._toast_until: # a message: top middle, clear of the stats' corner
state = (self._toast_text, round(ui, 3), op)
if state != self._toast_state:
from .hud import toast
self.toast_panel.update_rgba(toast(self._toast_text, ui, op))
self._toast_state = state
p = self.toast_panel
p.blit(x0 + max(0, (dw - p.w) // 2), y0 + dh - int(16 * ui), self._target())
self._draw_optimizer(x0, y0, dw, dh, ui, op)
def _draw_optimizer(self, x0: int, y0: int, dw: int, dh: int, ui: float, op: float) -> None:
"""Optimize (framegen/optimize.py): its countdown and candidate at the top while it runs; its result card in
the middle once done (Enter applies, Esc keeps the player's settings; also on the overlay's Optimize tab)."""
o = self.optimizer
if o is None or self.menu.open:
return
banner, result = o.banner(), o.result()
if banner is None and result is None:
return
from . import optimize as opt
state = (banner, id(result), round(ui, 3), op)
if self._opt_panel is None:
self._opt_panel = _Panel(self.GL, self.hdr10)
if state != self._opt_state:
if banner is not None:
from .hud import toast
self._opt_panel.update_rgba(toast(banner, ui, op))
else:
self._opt_panel.update_rgba(opt.card_image(result, ui, max(op, 0.92), o.runner.saved_to))
self._opt_state = state
p = self._opt_panel
if banner is not None: # top middle, below where messages go
p.blit(x0 + max(0, (dw - p.w) // 2), y0 + dh - int(96 * ui), self._target())
else: # in the middle (its top kept in the picture)
p.blit(x0 + max(0, (dw - p.w) // 2), y0 + min(dh, (dh + p.h) // 2), self._target())
def busy(self, fn, text: str):
"""Run fn() on a worker thread while the window stays responsive, showing the last frame and `text`.
Returns fn()'s result (or raises its exception). Keys pressed meanwhile (e.g. q) take effect after."""
GL, glfw = self.GL, self.glfw
out: list = []
def work() -> None:
try:
out.append((True, fn()))
except BaseException as e: # noqa: BLE001 - handed back to the caller
out.append((False, e))
self.menu.open = False
worker = threading.Thread(target=work, daemon=True)
worker.start()
t0 = time.perf_counter()
while worker.is_alive():
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)
dots = "." * (1 + int(time.perf_counter() - t0) % 3)
self.toast(f"{text}{dots:<3}", 1.0)
self._draw_ui(*visible(dw, dh, x0, y0, fw, fh))
self._present()
self._events()
if self.remote is not None and self.remote.poll() == "quit": # live settings still apply; a
self.cmd = "quit" # restart is already under way, but a Stop is kept for when it's done
worker.join(0.05)
self._toast_until = 0.0
ok, value = out[0]
if not ok:
raise value
return value
def wait(self, w: Waiting) -> str | None:
"""No new frame for a moment (framegen/io.Waiting): the window keeps answering Windows, its keys and the
launcher, and from 2 s on says so over the last picture. Returns "quit" or "restart" when asked for; any other
key waits for the next frame (write() hands it on)."""
glfw = self.glfw
n = int(w.since)
if n >= 2 and (n != self._waited or self.menu.open) and self.overlay_of is None:
self._waited = n
self.toast(f"No picture from {w.what} for {n} s" + (f"\n{w.why}" if w.why else "")
+ f"\n{self.overlay_key.name}: Summit's overlay Ctrl+Q: quit", 1.5)
fw, fh, s, dw, dh, x0, y0 = self._layout()
GL = self.GL
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) # the last frame, plain (no upscaler or look)
GL.glBlitFramebuffer(0, 0, self.w, self.h, x0, y0 + dh, x0 + dw, y0, GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR)
self._draw_ui(*visible(dw, dh, x0, y0, fw, fh))
self._present()
self.settle()
self._events()
if self.remote is not None:
r = self.remote.poll() # the launcher's Stop sends quit
if r == "quit" or (r == "restart" and self.cmd is None):
self.cmd = r
if glfw.window_should_close(self.win):
return "quit"
if self.cmd in ("quit", "restart"):
cmd, self.cmd = self.cmd, None
return cmd
return None
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:
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:
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
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
if self.aa_gl is not None and self.compare is not None:
self.compare.gl_aa = self.aa_gl.MODES # (the pipeline leaves these to this window)
mode = self.compare.window_aa(self.compare.plan() if not self.hdr10 else None)
if mode:
self._aa_pass(mode)
fw, fh, s, dw, dh, x0, y0 = self._layout()
target = screen = self._target()
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
ux, uy, uw, uh = self._ui_rect(fw, fh, dw, dh, x0, y0)
pano = self._panorama_on(fw, fh)
if pano: # Panorama: the picture is drawn as for Fit (to the screen's height) into its texture, then bent
if self.panorama is None: # across the whole screen below
self.panorama = Panorama(GL)
target, x0, y0 = self.panorama.target(dw, dh), 0, 0
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
# Output resolution: the upscaler makes the picture at that size, in a texture of its own, which is then
# stretched (or shrunk: supersampling) onto the screen where the picture goes
out_to = None
out_size = None if pano else self._output_size(dw, dh)
if out_size is not None:
out_to = (target, x0, y0, dw, dh)
target = self._out_target(*out_size)
x0, y0, dw, dh = 0, 0, *out_size
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
mode = self.mode
cmp = self.compare.plan() if self.compare is not None and not self.hdr10 else None
cmp_gl = cmp is not None and cmp.dim in ("scaler", "look") # drawn here, strip by strip (_compare_draw)
if mode == "off" and (dw > self.w or dh > self.h) and not cmp_gl:
# Upscaling off: the picture at its own size (never enlarged), in the middle of where it would go
k = min(1.0, dw / self.w, dh / self.h)
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
if ss > 1.0:
upscale = True
label = self._name(mode) if upscale else "no upscale"
self._frame_no += 1
plan = self.look_gl.plan(self.looks.current(), self.looks.rev) if self.look_gl is not None else None
pic = (x0, y0, dw, dh) # where the picture is (Compare's labels go over it)
q = self.timer.begin() if not cmp_gl else None # (Compare times each strip with its own queries)
if cmp_gl:
self._compare_draw(cmp, target, x0, y0, dw, dh, on_gpu)
GL.glViewport(0, 0, fw, fh)
label = f"compare: {cmp.dim}"
elif plan is not None: # the upscaler draws into the look's input, and the look onto the screen
if upscale and mode == "fsr":
src, fbo = self.look_gl.input_target(dw, dh)
self.fsr.draw(self.tex, self.w, self.h, fbo, 0, 0, dw, dh)
flip_in = True # (FSR draws upright)
elif upscale and mode == "vsr" and self._vsr_safely(lambda: self._vsr_render(round(dw * ss), round(dh * ss))):
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":
self.fsr.draw(self.tex, self.w, self.h, target, x0, y0, dw, dh)
GL.glViewport(0, 0, fw, fh)
elif upscale and mode == "vsr" and self._vsr_safely(lambda: self._vsr_draw(x0, y0, dw, dh, ss)):
pass
else:
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
# Image row 0 is the top; GL row 0 is the bottom, so blit with destination Y flipped.
GL.glBlitFramebuffer(0, 0, self.w, self.h, x0, y0 + dh, x0 + dw, y0, GL.GL_COLOR_BUFFER_BIT,
GL.GL_LINEAR)
if out_to is not None:
to, tx, ty, tw, th = out_to
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, target)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, to)
GL.glBlitFramebuffer(0, 0, dw, dh, tx, ty, tx + tw, ty + th, GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR)
GL.glViewport(0, 0, fw, fh)
kx, ky = tw / dw, th / dh
pic = (tx + round(pic[0] * kx), ty + round(pic[1] * ky), round(pic[2] * kx), round(pic[3] * ky))
label += f" at {dw}x{dh} -> {tw}x{th}"
dw, dh = tw, th
if pano:
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, cmp_gl)
if cmp is not None: # Compare's dividers and labels, over the picture (never in saved clips: those are the
self._compare_overlay(cmp, (ux, uy, uw, uh) if pano else pic, screen) # pipeline's, before this)
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:]))
if self.overlay and isinstance(text, MiniText) and getattr(text, "graph", None):
self._draw_graphs(text, ux, uy, uw, uh)
elif self.overlay and isinstance(text, MiniText):
self._draw_stats(text, f"{label}, {dw}x{dh}", ux, uy, uw, 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
self._blit_text(f"{first} {label}{nl}{rest}", ux, uy + uh, s)
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:
r = self.remote.poll() # the launcher's Stop sends quit
if r == "quit" or (r == "restart" and self.cmd is None):
self.cmd = r
if glfw.window_should_close(self.win):
return "quit"
cmd, self.cmd = self.cmd, None
return cmd
def _aa_pass(self, mode: str) -> None:
"""The Anti-aliasing setting on the uploaded frame, in place: GLSL into a scratch texture, copied back. Its GPU
time is printed now and then (it doesn't reach the stats overlay's stages)."""
GL, c = self.GL, self._aa_gl
if c.get("size") != (self.w, self.h):
tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, self.w, self.h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
for p_ in (GL.GL_TEXTURE_MIN_FILTER, GL.GL_TEXTURE_MAG_FILTER):
GL.glTexParameteri(GL.GL_TEXTURE_2D, p_, GL.GL_NEAREST)
fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo)
GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0)
from .fsr import GpuTimer
c.update(size=(self.w, self.h), tex=tex, fbo=fbo, timer=c.get("timer") or GpuTimer(GL, ring=16),
ms=[], told=time.perf_counter())
vp = GL.glGetIntegerv(GL.GL_VIEWPORT)
q = c["timer"].begin()
self.aa_gl.draw(mode, self.tex, c["fbo"], self.w, self.h)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, c["fbo"])
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self.fbo)
GL.glBlitFramebuffer(0, 0, self.w, self.h, 0, 0, self.w, self.h, GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST)
c["timer"].end(q, "aa")
GL.glViewport(*[int(v) for v in vp])
c["timer"]._collect()
c["ms"].extend(c["timer"].ms.pop("aa", []))
if time.perf_counter() - c["told"] >= 30.0 and c["ms"]:
ms = c["ms"][-600:]
print(f"[display] anti-aliasing {mode} in OpenGL: {sum(ms) / len(ms):.3f} ms a frame on average, "
f"{max(ms):.3f} worst (GPU time, pass and copy, {self.w}x{self.h})", flush=True)
c["ms"], c["told"] = [], time.perf_counter()
# ---- Compare (framegen/compare.py) ------------------------------------------------------------------------------
def _compare_scratch(self, w: int, h: int) -> int:
"""A picture-sized framebuffer each upscaler or look variant is drawn into whole, before its strip is cut."""
GL, c = self.GL, self._cmp
have = c.get("scratch")
if have is not None and have[2:] == (w, h):
return have[1]
if have is not None:
GL.glDeleteFramebuffers(1, [have[1]])
GL.glDeleteTextures([have[0]])
tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
for p_ in (GL.GL_TEXTURE_MIN_FILTER, GL.GL_TEXTURE_MAG_FILTER):
GL.glTexParameteri(GL.GL_TEXTURE_2D, p_, GL.GL_NEAREST)
fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo)
GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0)
c["scratch"] = (tex, fbo, w, h)
return fbo
def _compare_variant(self, dim: str, variant: str, fbo: int, dw: int, dh: int, on_gpu: bool) -> bool:
"""One upscaler (or look) variant on the whole picture, into fbo at (0, 0, dw, dh), upright as on screen.
False if it couldn't be drawn (the strip stays black)."""
from .compare import FSR_LEVELS
GL, st = self.GL, self.settings
if dim == "look":
mode = self.mode if self.mode != "vsr" or on_gpu else ("fsr" if self.fsr is not None else "bilinear")
sharp = st.fsr_sharpness
else:
mode = "fsr" if variant in FSR_LEVELS else variant
sharp = FSR_LEVELS.get(variant, st.fsr_sharpness)
upscale = dw > self.w or dh > self.h
look_plan = None
if dim == "look" and variant == "on" and self.look_gl is not None:
from .looks import BUILTIN, DEFAULT_LOOK
look = self.looks.library.get(st.look) or BUILTIN[DEFAULT_LOOK]
look_plan = self.look_gl.plan(look, self.looks.rev)
if look_plan is not None:
if upscale and mode == "fsr" and self.fsr is not None:
src, lfbo = self.look_gl.input_target(dw, dh)
self.fsr.draw(self.tex, self.w, self.h, lfbo, 0, 0, dw, dh)
flip_in = True
elif upscale and mode == "vsr" and on_gpu and self._vsr_ready() and self._vsr_safely(
lambda: self._vsr_render(dw, dh)):
src, flip_in = self.vsr_out[0], False
else:
src, flip_in = self.tex, False
self.look_gl.draw(look_plan, src, flip_in, fbo, 0, 0, dw, dh, True, self._frame_no)
return True
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo)
if mode == "fsr":
if self.fsr is None:
return False
old, self.fsr.sharpness = self.fsr.sharpness, sharp
try:
self.fsr.draw(self.tex, self.w, self.h, fbo, 0, 0, dw, dh)
finally:
self.fsr.sharpness = old
return True
if mode == "vsr":
if not (on_gpu and self._vsr_ready()):
return False
ss = 1.0 if upscale else SUPERSAMPLE
return self._vsr_safely(lambda: self._vsr_draw(0, 0, dw, dh, ss))
# Off: the game's pixels enlarged as they are (nearest neighbour), over the whole picture like the others:
# Upscaler Off itself shows it small in the middle, which most strips would miss
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
GL.glBlitFramebuffer(0, 0, self.w, self.h, 0, dh, dw, 0, GL.GL_COLOR_BUFFER_BIT,
GL.GL_NEAREST if mode == "off" and dim == "scaler" else GL.GL_LINEAR)
return True
def _compare_draw(self, p, target: int, x0: int, y0: int, dw: int, dh: int, on_gpu: bool) -> None:
"""Upscaler and look strips: each variant drawn on the whole picture (so its GPU time, measured with a timer
query, is its real cost per frame), then its strip copied to where it goes."""
from .compare import draws, timing_key
from .fsr import GpuTimer
GL = self.GL
if self._cmp is None:
self._cmp = {"panels": [], "drag": False}
c = self._cmp
if c.get("timer") is None:
c["timer"] = GpuTimer(GL, ring=16)
timer = c["timer"]
fbo = self._compare_scratch(dw, dh)
todo = draws(p, dw, dh) # (strip, where, which part): -1 is black (a zoomed area's margin)
for _, (dx0, dy0, dx1, dy1), _ in (t for t in todo if t[0] < 0):
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
GL.glEnable(GL.GL_SCISSOR_TEST)
GL.glScissor(x0 + dx0, y0 + dh - dy1, dx1 - dx0, dy1 - dy0)
GL.glClearColor(0.0, 0.0, 0.0, 1.0)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
GL.glDisable(GL.GL_SCISSOR_TEST)
for i, s in enumerate(p.strips):
mine = [(d, src) for k, d, src in todo if k == i]
if not mine: # (Flip: the strip that isn't on screen isn't drawn, or timed)
continue
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo)
GL.glViewport(0, 0, dw, dh)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
if not s.why:
key = timing_key(p.dim, s.variant)
vsr = p.dim == "scaler" and s.variant == "vsr" or p.dim == "look" and self.mode == "vsr"
if vsr: # CUDA work: a GL query wouldn't see it, so the time from start to finish
GL.glFinish()
t0 = time.perf_counter()
self._compare_variant(p.dim, s.variant, fbo, dw, dh, on_gpu)
GL.glFinish()
self.compare.timings.add(key, (time.perf_counter() - t0) * 1000)
else:
q = timer.begin()
self._compare_variant(p.dim, s.variant, fbo, dw, dh, on_gpu)
timer.end(q, key)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo)
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
for (dx0, dy0, dx1, dy1), (sx0, sy0, sx1, sy1) in mine:
# picture rows go down, GL's up. Nearest: a Same area zoom shows the variant's own pixels; only the
# inset map (the whole picture, shrunk) is smoothed
shrink = (dx1 - dx0) < (sx1 - sx0)
GL.glBlitFramebuffer(sx0, dh - sy1, sx1, dh - sy0, x0 + dx0, y0 + dh - dy1, x0 + dx1, y0 + dh - dy0,
GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR if shrink else GL.GL_NEAREST)
timer._collect()
for key, ms in timer.ms.items():
for v in ms:
self.compare.timings.add(key, v)
ms.clear()
def _compare_overlay(self, p, pic, target: int) -> None:
"""Compare's dividers and labels over the picture at pic = (x, GL y of its bottom, w, h)."""
if self._cmp is None:
self._cmp = {"panels": [], "drag": False}
c = self._cmp
x0, y0, w, h = (int(v) for v in pic)
c["pic"] = (x0, y0, w, h)
if w <= 0 or h <= 0:
return
# how to pick an area: over a game the keys and clicks are the game's, so in the overlay's Compare tab
self.compare.hint = (self.compare.HINT if self.overlay_of is None else
f"Pick the area in Summit's overlay ({self.overlay_key.name}): Compare tab, Area")
items = self.compare.items(p, w, h, max(0.5, h / 1080))
panels = c["panels"]
while len(panels) < len(items):
panels.append([_Panel(self.GL, self.hdr10), None])
for (x, y, img), slot in zip(items, panels):
if slot[1] is not img:
slot[0].update_rgba(img)
slot[1] = img
slot[0].blit(x0 + x, y0 + h - y, target)
def _compare_xy(self) -> tuple[float, float, int, int] | None:
"""The mouse over Compare's picture: (x, y from its top-left, its width, height), or None."""
pic = (self._cmp or {}).get("pic")
if pic is None:
return None
glfw = self.glfw
ww, wh = glfw.get_window_size(self.win)
fw, fh = glfw.get_framebuffer_size(self.win)
if not ww or not wh:
return None
cx, cy = self._cursor[0] * fw / ww, fh - self._cursor[1] * fh / wh # framebuffer pixels, GL y (up)
x0, y0, w, h = pic
return cx - x0, (y0 + h) - cy, w, h
def _vsr_safely(self, draw) -> bool:
"""Runs a VSR draw. If it fails, RTX VSR is off for the rest of the session (out of the upscaler list, FSR 1
in its place, a message saying why) and this frame is drawn without it: the game goes on either way."""
try:
draw()
return True
except Exception as e: # noqa: BLE001 - an optional upscaler never ends the session
why = f"{type(e).__name__}: {str(e)[:160]}"
print(f"[display] RTX VSR failed, switching to FSR 1 for this session ({why})", flush=True)
try:
self._vsr_target_free()
except Exception: # noqa: BLE001 - tidying up after a failure
pass
self.vsr_out, self.vsr, self._vsr_args, self.vsr_why = None, None, None, f"it failed here ({why})"
self.modes = [m for m in self.modes if m != "vsr"]
self.mode = "fsr" if "fsr" in self.modes else self.modes[0]
self.toast("RTX VSR stopped working, so Summit switched to FSR 1. The log says why.", 6.0)
return False
def _vsr_draw(self, x0: int, y0: int, dw: int, dh: int, ss: float = 1.0) -> None:
"""RTX VSR from the staged RGBA frame straight into a window-sized GL texture, then a 1:1 blit."""
GL = self.GL
rw, rh = round(dw * ss), round(dh * ss)
fbo = self._vsr_render(rw, rh)[1]
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo)
GL.glBlitFramebuffer(0, 0, rw, rh, x0, y0 + dh, x0 + dw, y0, GL.GL_COLOR_BUFFER_BIT,
GL.GL_LINEAR if ss > 1.0 else GL.GL_NEAREST)
def _vsr_render(self, dw: int, dh: int) -> tuple[int, int]:
"""RTX VSR into the window-sized texture (row 0 = the image's top); returns (texture, framebuffer)."""
if self.vsr_out is None or self.vsr_out[3:5] != (dw, dh):
self._vsr_target(dw, dh)
tex, fbo, img = self.vsr_out[:3]
stream = self.vsr.stream.cuda_stream
arr = img.map(stream)
try:
self.vsr(self.interop.rgba, arr, dw, dh)
finally:
img.unmap(stream) # orders GL's read after VSR's write, no CPU wait
return tex, fbo
def _vsr_target(self, w: int, h: int) -> None:
"""(Re)make the VSR output texture at the window's image size. RGBA8, or, for NVIDIA's package's packed
10-bit output, an R32UI texture that CUDA copies the words into, read by GL through an RGB10_A2 view of the
same memory (both 32 bits a pixel, R in the low bits as NVIDIA packs it), so nothing unpacks them."""
from .glcuda import CudaGLImage
GL = self.GL
self._vsr_target_free()
store = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, store)
if self.vsr.out_format == "rgb10a2":
GL.glTexStorage2D(GL.GL_TEXTURE_2D, 1, GL.GL_R32UI, w, h)
tex = GL.glGenTextures(1)
GL.glTextureView(tex, GL.GL_TEXTURE_2D, store, GL.GL_RGB10_A2, 0, 1, 0, 1)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_A, GL.GL_ONE) # NVIDIA leaves alpha 0 at times
else:
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
tex = store
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo)
GL.glFramebufferTexture2D(GL.GL_READ_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0)
self.vsr_out = (tex, fbo, CudaGLImage(int(store)), w, h, store)
def _vsr_target_free(self) -> None:
if self.vsr_out is not None:
tex, fbo, img = self.vsr_out[:3]
if img.array.value:
self.vsr.forget(img.array)
img.close()
self.GL.glDeleteFramebuffers(1, [fbo])
self.GL.glDeleteTextures(sorted({int(tex), int(self.vsr_out[5])})) # a view and its storage, or one
self.vsr_out = None
def _blit_corner(self, panel, x0: int, y0: int, dw: int, dh: int, ui: float) -> None:
"""The stats panel in the corner the settings pick, a margin in from the picture's edges."""
m = int(12 * ui)
corner = self.settings.overlay_corner
x = x0 + dw - panel.w - m if corner.endswith("right") else x0 + m
top = y0 + m + panel.h if corner.startswith("bottom") else y0 + dh - m
panel.blit(x, top, self._target())
def _stats_ui(self, dh: int) -> float:
return max(0.5, dh / 1080) * self.settings.overlay_scale
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 bar, stats
ui = self._stats_ui(dh)
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:
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
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:
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)
if now - self._graph_drawn >= 1 / 30 or self._mini_state != key:
self.mini_panel.update_rgba(graphs(text, self._frametimes, ui, self.settings.overlay_opacity, self._gpu))
self._graph_drawn, self._mini_state = now, key
self._blit_corner(self.mini_panel, x0, y0, dw, dh, ui)
def _draw_watermark(self, x0: int, y0: int, dw: int, dh: int) -> None:
"""The Summit watermark (framegen/watermark.py, settings "watermark"): small, in a bottom corner, away from the
stats. Drawn again only when its size changes."""
from . import watermark as wm
ui = max(0.5, dh / 1080)
if self._wm_state != round(ui, 3):
self.wm_panel.update_rgba(wm.render_rgba(ui))
self._wm_state = round(ui, 3)
p = self.wm_panel
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())
def _blit_text(self, text: str, x0: int, top: int, s: float) -> None:
GL = self.GL
if text != self._ov_text:
img = np.zeros((self.ov_h, self.ov_w, 3), np.uint8)
lines = text.split("\n")[:2]
for i, line in enumerate(lines):
cv2.putText(img, line, (12, 38 + 40 * i), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA)
# The box only grows, so it doesn't jitter as the numbers change width.
tw = max(cv2.getTextSize(line, cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2)[0][0] for line in lines) + 24
self._ov_tw = min(self.ov_w, max(self._ov_tw, tw))
self._ov_th = 16 + 40 * len(lines)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.ov_tex)
img, _, kind = _gl_image(GL, img, self.hdr10)
GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self.ov_w, self.ov_h, GL.GL_BGR, kind, img)
self._ov_text = text
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.ov_fbo)
x, y = x0 + int(8 * s), top - int(8 * s)
GL.glBlitFramebuffer(0, 0, self._ov_tw, self._ov_th, x, y, x + int(self._ov_tw * s), y - int(self._ov_th * s),
GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR)
# ---- looks
def remote_commands(self) -> dict:
"""The launcher's Looks page, through framegen/remote.py: `look-show <look JSON>` shows a look it's editing,
`look-hide` goes back to the settings' look, `looks-reload` reads the user's looks again after a change."""
import json
def show(text: str) -> None:
try:
self.looks.show(json.loads(text))
except ValueError as e:
print(f"[looks] can't show that look: {e}")
def reload(_text: str) -> None:
self.looks.reload()
if self.remote is not None:
self.remote.publish() # the new list of looks
return {"look-show": show, "look-hide": lambda _text: self.looks.show(None), "looks-reload": reload}
def baked(self, frame):
"""The frame just shown, with the look drawn on at the stream's size: for instant replay with "Looks in
clips" on (framegen/replay.py). Call right after write(), on its thread. The frame itself when no look is on,
or when the frames aren't on the graphics card (then it says so, once)."""
plan = self.look_gl.plan(self.looks.current(), self.looks.rev) if self.look_gl is not None else None
if plan is None:
return frame
if not (_is_cuda(frame) and self.interop is not None):
if not self._bake_said:
self._bake_said = True
print("[looks] Looks in clips needs the frames on the graphics card; clips are saved without it")
self.toast("Clips are saved without the look (it needs the frames on the graphics card)", 5.0)
return frame
import torch
GL = self.GL
if self._bake is None:
from .glcuda import CudaGLReader
tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, self.w, self.h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbo)
GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0)
self._bake = (tex, fbo, CudaGLReader(int(tex), self.w, self.h))
tex, fbo, reader = self._bake
self.look_gl.draw(plan, self.tex, False, fbo, 0, 0, self.w, self.h, False, self._frame_no, "bake")
GL.glViewport(0, 0, *self.glfw.get_framebuffer_size(self.win))
rgba = torch.empty((self.h, self.w, 4), dtype=torch.uint8, device=frame.device)
reader.read(rgba)
return rgba[..., [2, 1, 0]] # BGR, like the frame
def hide(self) -> None:
"""Take the window off the screen now, before what's left of stopping (clips finishing saving): close()
follows."""
try:
self.glfw.hide_window(self.win)
self._events()
except Exception: # noqa: BLE001 - closing anyway
pass
def close(self) -> None:
if self.hotkeys is not None:
self.hotkeys.close()
self.hotkeys = None
if self.xkeys is not None: # (the keyboard, if the overlay was open, goes back to the game)
self.xkeys.stop()
self.xkeys = None
self.GL.glFinish()
self.timer._collect()
private = self.vsr is not None and self.vsr.private # NVIDIA's package: its timings stay off the log
timed = {k: v for k, v in self.timer.ms.items() if not (private and "RTX VSR" in k)}
if timed:
parts = [f"{k} p50 {np.median(v):.2f} / p95 {np.percentile(v, 95):.2f} ms (n={len(v)})"
for k, v in sorted(timed.items(), key=lambda kv: -len(kv[1]))]
print("[display] GPU time to draw each frame: " + "; ".join(parts))
self.timer.close()
self._unwatch()
self.menu_panel.close()
self.toast_panel.close()
self.mini_panel.close()
if self._cmp is not None:
for panel, _ in self._cmp["panels"]:
panel.close()
if self._cmp.get("timer") is not None:
self._cmp["timer"].close()
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()
v = self.vsr.gpu_ms
if v and not self.vsr.private:
print(f"[display] RTX VSR q{self.vsr.quality} GPU time per frame: p50 {np.median(v):.2f} / "
f"p95 {np.percentile(v, 95):.2f} ms (n={len(v)})")
if self.fsr is not None:
self.fsr.close()
if self._bake is not None:
self._bake[2].close()
self.GL.glDeleteFramebuffers(1, [self._bake[1]])
self.GL.glDeleteTextures([self._bake[0]])
if self.look_gl is not None:
self.look_gl.close()
self.looks.close()
if self.interop is not None:
self.interop.close()
if self.dx is not None:
self.dx.close()
self.glfw.destroy_window(self.glwin)
self.glfw.destroy_window(self.win)
self.glfw.terminate()
class WindowSink:
"""OpenCV window (fallback; its GDI paint costs 5-12 ms/frame, too slow for 60 Hz on Windows).
Keys: i = toggle interpolation, s = stats overlay, f = fullscreen, r/b = save the instant replay (plain or
before & after), q = quit (Esc doesn't: it's a game's own key)."""
NAME = "SmoovPlay"
def __init__(self, w: int, h: int) -> None:
cv2.namedWindow(self.NAME, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
cv2.resizeWindow(self.NAME, min(w, 1600), min(h, 900))
self.full = False
self.overlay = True
gpu = False
def write(self, frame, text: str | None = None) -> str | None:
frame = _host(frame)
if self.overlay and text:
frame = _draw_text(frame, text)
cv2.imshow(self.NAME, frame)
k = cv2.waitKey(1) & 0xFF
if k == ord("q"):
return "quit"
if k == ord("f"):
self.full = not self.full
cv2.setWindowProperty(self.NAME, cv2.WND_PROP_FULLSCREEN,
cv2.WINDOW_FULLSCREEN if self.full else cv2.WINDOW_NORMAL)
if k == ord("s"):
self.overlay = not self.overlay
if k == ord("i"):
return "toggle_interp"
if k in (ord("r"), ord("b")):
return "save_replay" if k == ord("r") else "save_compare"
return None
def close(self) -> None:
cv2.destroyWindow(self.NAME)
class FileSink:
"""Encodes output frames to a 60 fps file with NVENC (falls back to x264)."""
def __init__(self, path: str, w: int, h: int, fps: float = 60.0) -> None:
enc = ["-c:v", "h264_nvenc", "-preset", "p5", "-cq", "18"] if _has_nvenc() else \
["-c:v", "libx264", "-preset", "veryfast", "-crf", "16"]
self.p = subprocess.Popen(
["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}",
"-r", str(fps), "-i", "-", *enc, "-pix_fmt", "yuv420p", path],
stdin=subprocess.PIPE)
gpu = False
def write(self, frame, text: str | None = None) -> None:
self.p.stdin.write(memoryview(np.ascontiguousarray(_host(frame))))
def close(self) -> None:
self.p.stdin.close()
self.p.wait()
class MultiSink:
def __init__(self, *sinks) -> None:
self.sinks = [s for s in sinks if s is not None]
# Hand out CUDA tensors if any sink can use them directly; the others copy to the CPU themselves.
self.gpu = any(getattr(s, "gpu", False) for s in self.sinks)
def write(self, frame, text: str | None = None):
cmd = None
for s in self.sinks:
cmd = s.write(frame, text) or cmd
return cmd
def wait(self, w: Waiting) -> str | None:
cmd = None
for s in self.sinks:
if hasattr(s, "wait"):
cmd = s.wait(w) or cmd
return cmd
def toast(self, text: str, seconds: float = 2.0) -> None:
for s in self.sinks:
if hasattr(s, "toast"):
s.toast(text, seconds)
def close(self) -> None:
for s in self.sinks:
s.close()
_nvenc: bool | None = None
def _has_nvenc() -> bool:
global _nvenc
if _nvenc is None:
r = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=s=256x256:d=0.1",
"-c:v", "h264_nvenc", "-f", "null", "-"], capture_output=True)
_nvenc = r.returncode == 0
return _nvenc