"""One frame of Summit's live comparison (framegen/compare.py), written as a PNG, without the video window: for screenshots and for checking the strips by eye. python devtools/compare_shot.py VIDEO --compare aa:off,fxaa,smaa,cas --frame 120 --out aa.png python devtools/compare_shot.py --pattern --compare scaler:off,bilinear,fsr --source-size 960x540 --size 1920x1080 python devtools/compare_shot.py VIDEO --compare framegen:off,on --frame 300 --out fg.png --sequence 4 The input is a video file (any FFmpeg/OpenCV can read) or --pattern, a generated test picture with fine diagonal lines, aliased text, a zone plate and something moving, so anti-aliasing and upscaling differences show. Each comparison is drawn by the same code as in the video window where it can be: - Anti-aliasing: framegen/aa.py, on the GPU (torch CUDA) when there is one, else on the CPU (numpy; --cpu forces it). Times are measured here, over --repeat runs of each variant on the whole frame. - Upscaler: framegen/fsr.py's FSR 1 shaders in a hidden OpenGL window (GLFW; needs a display, llvmpipe will do), bilinear as the window's GL blit. RTX VSR runs only in the live window (it needs the window's CUDA-GL path), so here it is shown as unavailable, saying so. On llvmpipe (software OpenGL) GPU times mean nothing, so timings are left off unless --timings. - Look: framegen/looks_gl.py in the hidden window (or looks.render, the numpy reference, without OpenGL). - Frame generation: RIFE (framegen/interpolator.py) makes the frame halfway between frames N and N+1; the Off strip holds frame N, as the live view does. A still can't show smoothness: --sequence K writes K output frames in a row (Off repeats, On moves), two to a row. Frame rates on these labels are the file's rate (and twice it), not measured. --layout grid is Same area: without --compare-area it shows the picker (each cell as it is, outlined and numbered); --compare-area 2 (a cell) or --compare-area X,Y,W,H (fractions of the picture: a free box, zoomed by whole pixels to fill a cell) shows that area in every cell, with the inset map. --freeze marks the still as frozen (as the live window does); --flip a|b shows one of two strips over the whole picture; --labels-at bottom. --zoom X,Y,W,H[,K] also writes -zoom.png: that part of the picture (picture pixels), K times bigger (nearest neighbour, so pixels stay pixels). """ from __future__ import annotations import argparse import sys import time from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from framegen import compare as C # noqa: E402 from framegen import ui_draw as U # noqa: E402 # ---- input ------------------------------------------------------------------------------------------------------ def pattern(w: int, h: int, t: float = 0.0) -> np.ndarray: """A test picture (BGR) that every strip gets a share of: aliased near-horizontal and steep lines across the whole width, a fence of thin posts and wires, aliased text, a row of zone plates, and a bar that moves with t (frames).""" import cv2 from PIL import Image, ImageDraw y, x = np.mgrid[0:h, 0:w].astype(np.float32) bg = np.dstack([60 + 80 * x / w, 70 + 60 * y / h, 110 + 40 * (1 - x / w)]).astype(np.uint8) img = Image.fromarray(bg[..., ::-1].copy()) d = ImageDraw.Draw(img) d.fontmode = "1" # no anti-aliasing in the text itself: what the AA is for s = h / 540 for k, rise in enumerate((0.02, 0.05, 0.09, 0.14)): # long, nearly flat 1-pixel lines: stair steps y0 = h * (0.05 + 0.06 * k) d.line((0, y0, w, y0 + rise * w * 0.3), fill=(250, 250, 240), width=1) for i in range(int(w / (40 * s))): # a fence: thin dark posts, leaning, and wires xx = i * 40 * s + 10 * s d.line((xx, h * 0.33, xx + 9 * s, h * 0.58), fill=(25, 25, 30), width=max(1, int(2 * s))) for j in range(5): yy = h * (0.36 + j * 0.045) d.line((0, yy, w, yy + h * 0.04), fill=(30, 30, 35), width=1) f = U.font(int(24 * s), "bold") words = "SUMMIT 0123 Wy// " * 12 d.text((int(8 * s), int(h * 0.61)), words, font=f, fill=(255, 240, 200)) out = np.asarray(img)[..., ::-1].copy() r = int(h * 0.12) # zone plates: rings that get finer outwards (aliasing and upscaling show as moire) yy, xx = np.mgrid[-r:r, -r:r].astype(np.float32) zone = (127.5 + 127.5 * np.cos((xx ** 2 + yy ** 2) * (np.pi / (2.0 * r)))).astype(np.uint8) inside = xx ** 2 + yy ** 2 < r * r cy = int(h * 0.84) for cx in range(int(w / 8), w, int(w / 4)): if cx - r >= 0 and cx + r <= w: sl = out[cy - r:cy + r, cx - r:cx + r] sl[inside] = zone[inside][:, None] for q in range(4): # slanted bars moving right, one in each quarter: frame generation draws them in between bx = int((0.03 + 0.25 * q + 0.03 * t) * w) % w pts = np.array([[bx, int(h * 0.70)], [bx + int(30 * s), int(h * 0.70)], [bx + int(70 * s), int(h * 0.98)], [bx + int(40 * s), int(h * 0.98)]], np.int32) cv2.fillPoly(out, [pts], (40, 200, 250)) # (aliased: cv2's default line type) return out def read_frames(path: str | None, n: int, count: int, w: int, h: int) -> list[np.ndarray]: """Frames n .. n+count-1 of the video (or of the pattern), BGR.""" if path is None: return [pattern(w, h, n + k) for k in range(count)] import cv2 cap = cv2.VideoCapture(path) if not cap.isOpened(): raise SystemExit(f"can't open {path}") cap.set(cv2.CAP_PROP_POS_FRAMES, n) frames = [] for _ in range(count): ok, f = cap.read() if not ok: raise SystemExit(f"{path} has no frame {n + len(frames)}") frames.append(f) return frames def file_fps(path: str | None) -> float: if path is None: return 30.0 import cv2 cap = cv2.VideoCapture(path) return float(cap.get(cv2.CAP_PROP_FPS) or 30.0) # ---- OpenGL (upscaler and look) --------------------------------------------------------------------------------- class Gl: """A hidden OpenGL window drawing the window's own upscalers and looks into an offscreen picture.""" def __init__(self) -> None: import glfw from OpenGL import GL if not glfw.init(): raise RuntimeError("no display for OpenGL") glfw.window_hint(glfw.VISIBLE, glfw.FALSE) self.win = glfw.create_window(64, 64, "Summit compare shot", None, None) if not self.win: raise RuntimeError("no OpenGL context") glfw.make_context_current(self.win) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) self.glfw, self.GL = glfw, GL self.renderer = GL.glGetString(GL.GL_RENDERER).decode(errors="replace") from framegen.fsr import FsrScaler, GpuTimer self.fsr = FsrScaler(GL) self.timer = GpuTimer(GL, ring=64) self.src = None def _tex(self, w: int, h: int, data=None) -> int: GL = self.GL t = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, t) for p in (GL.GL_TEXTURE_MIN_FILTER, GL.GL_TEXTURE_MAG_FILTER): GL.glTexParameteri(GL.GL_TEXTURE_2D, p, GL.GL_LINEAR) for p in (GL.GL_TEXTURE_WRAP_S, GL.GL_TEXTURE_WRAP_T): GL.glTexParameteri(GL.GL_TEXTURE_2D, p, GL.GL_CLAMP_TO_EDGE) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, None if data is None else np.ascontiguousarray(data)) return t def _fbo(self, tex: int) -> int: GL = self.GL 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) return fbo def load(self, frame: np.ndarray) -> None: h, w = frame.shape[:2] self.sw, self.sh = w, h self.src = self._tex(w, h, frame) # row 0 of the image in texture row 0, as the window uploads it self.src_fbo = self._fbo(self.src) def draw(self, variant: str, w: int, h: int, sharpness: float, look=None, renderer=None) -> tuple[np.ndarray, float]: """One upscaler variant (plus the look) at w x h, upright, read back as BGR; and its GL time in ms.""" GL = self.GL out = self._tex(w, h) fbo = self._fbo(out) GL.glViewport(0, 0, w, h) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glFinish() q = self.timer.begin() mode = "fsr" if variant in C.FSR_LEVELS or variant == "fsr" else variant if mode == "fsr": self.fsr.sharpness = C.FSR_LEVELS.get(variant, sharpness) self.fsr.draw(self.src, self.sw, self.sh, fbo, 0, 0, w, h) else: # Off: nearest neighbour, as the window's Compare draws it (the game's pixels as they are) GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.src_fbo) GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo) GL.glBlitFramebuffer(0, 0, self.sw, self.sh, 0, h, w, 0, GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST if mode == "off" else GL.GL_LINEAR) if look is not None: # the look over the upscaled picture, as the window draws it mid = self._tex(w, h) mid_fbo = self._fbo(mid) GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo) GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, mid_fbo) GL.glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST) renderer.draw(look, mid, True, fbo, 0, 0, w, h, True, 0) GL.glDeleteFramebuffers(1, [mid_fbo]) GL.glDeleteTextures([mid]) self.timer.end(q, variant) GL.glFinish() GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo) data = GL.glReadPixels(0, 0, w, h, GL.GL_BGR, GL.GL_UNSIGNED_BYTE) img = np.frombuffer(data, np.uint8).reshape(h, w, 3)[::-1].copy() # GL row 0 is the bottom GL.glDeleteFramebuffers(1, [fbo]) GL.glDeleteTextures([out]) self.timer._collect() ms = self.timer.ms.pop(variant, []) return img, (ms[-1] if ms else float("nan")) def close(self) -> None: self.glfw.destroy_window(self.win) self.glfw.terminate() # ---- the comparison --------------------------------------------------------------------------------------------- def frames_on(device: str): """numpy -> what aa.py should get: a CUDA tensor on the GPU, the array itself on the CPU.""" if device == "cuda": import torch return lambda f: torch.from_numpy(np.ascontiguousarray(f)).cuda() return lambda f: f def host(img) -> np.ndarray: return img.cpu().numpy() if hasattr(img, "cpu") else img def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("video", nargs="?", help="a video file (else --pattern)") ap.add_argument("--pattern", action="store_true", help="a generated test picture instead of a video") ap.add_argument("--compare", required=True, metavar="DIM:V1,V2,...", help="as run.py --compare") ap.add_argument("--frame", type=int, default=0, help="which frame of the video (0 = the first)") ap.add_argument("--out", default="compare.png") ap.add_argument("--source-size", default=None, metavar="WxH", help="resize the input first (the game's size)") ap.add_argument("--size", default=None, metavar="WxH", help="output picture size (upscaler: what it scales to)") ap.add_argument("--layout", default="columns", choices=C.LAYOUTS) ap.add_argument("--split", type=float, default=0.5, help="where the divider is, with 2 strips (0..1)") ap.add_argument("--compare-area", default=None, metavar="CELL|X,Y,W,H", help="Same area, picked: a cell number or x,y,w,h as fractions (implies --layout grid)") ap.add_argument("--freeze", action="store_true", help="mark it frozen, as the live window does") ap.add_argument("--flip", default="off", choices=("off", "a", "b"), help="2 strips: the whole picture with one") ap.add_argument("--labels-at", default="top", choices=("top", "bottom")) ap.add_argument("--no-labels", action="store_true") ap.add_argument("--timings", action=argparse.BooleanOptionalAction, default=None, help="cost under each name (default: on, but off on software OpenGL)") ap.add_argument("--repeat", type=int, default=20, help="runs of each variant for its timing") ap.add_argument("--cpu", action="store_true", help="anti-aliasing and frame generation on the CPU") ap.add_argument("--fsr-sharpness", type=float, default=0.5) ap.add_argument("--look", default=None, help="look id for look:off,on (default: the settings' default)") ap.add_argument("--model", default="4.22.lite", help="RIFE model for framegen") ap.add_argument("--sequence", type=int, default=0, metavar="K", help="framegen: also write K output frames side by side (-sequence.png)") ap.add_argument("--zoom", default=None, metavar="X,Y,W,H[,K]") ap.add_argument("--title", default="", help="a caption at the top") a = ap.parse_args() if a.video is None and not a.pattern: ap.error("give a video file or --pattern") dim, picks = C.parse(a.compare) def size(s, default): if not s: return default w, h = s.lower().split("x") return int(w), int(h) src_size = size(a.source_size, (1280, 720) if a.pattern else None) need = 2 if dim == "framegen" else 1 frames = read_frames(None if a.pattern else a.video, a.frame, need + max(0, a.sequence - 1), *(src_size or (1280, 720))) if src_size and frames[0].shape[1::-1] != src_size: import cv2 frames = [cv2.resize(f, src_size, interpolation=cv2.INTER_AREA) for f in frames] sh, sw = frames[0].shape[:2] out_w, out_h = size(a.size, (sw * 2, sh * 2) if dim == "scaler" else (sw, sh)) import torch # noqa: F401 - the engine always has it; CUDA if this machine has a GPU device = "cuda" if (not a.cpu and torch.cuda.is_available()) else "cpu" on = frames_on(device) timings = C.Timings(a.repeat) caps = C.Caps(scalers=("off", "bilinear", "fsr"), scaler_why={"vsr": "RTX VSR runs in the live window only (not in this tool)"}) gl = None renderer_note = f"anti-aliasing on {'the GPU (CUDA)' if device == 'cuda' else 'the CPU (numpy)'}" if dim in ("scaler", "look"): try: gl = Gl() renderer_note = f"OpenGL: {gl.renderer}" except Exception as e: # noqa: BLE001 - said, and the strips say so too print(f"[compare_shot] no OpenGL here ({e}): upscaler and look strips are unavailable") caps.window = False software_gl = gl is not None and "llvmpipe" in gl.renderer.lower() show_timings = a.timings if a.timings is not None else not software_gl look_plan = look_r = None if dim == "look": from framegen import looks look_id = a.look or looks.DEFAULT_LOOK look = looks.Library().get(look_id) or looks.BUILTIN[looks.DEFAULT_LOOK] caps.look = look["name"] if gl is not None: from framegen.looks_gl import LookRenderer lib = looks.Library() look_r = LookRenderer(gl.GL, lib.lut) look_plan = look_r.plan(look, 1) caps.multiplier = 2 caps.model = a.model values = dict(C.settings_for(a.compare), compare_layout=a.layout, compare_labels=not a.no_labels, compare_timings=show_timings, compare_freeze=a.freeze, compare_flip=a.flip, compare_labels_at=a.labels_at) free = (0.5, 0.5) if a.compare_area: try: area, free = C.area_settings(a.compare_area, len(picks)) except ValueError as e: ap.error(str(e)) values.update(area) p = C.plan(values, caps, a.split, free) rates: dict = {} t0 = time.perf_counter() images: list = [] # each strip's variant on the whole picture (None: unavailable), for --zoom if dim == "aa": from framegen import aa frame = on(frames[0]) for s in p.strips: # compiled first (on the GPU), as it is a few seconds into a session if not s.why and s.variant != "off": fused = aa.settle(s.variant, frame) print(f"[compare_shot] {s.name}: {'compiled (fused kernels)' if fused else 'op by op'}") for _ in range(5): # warm-up, not counted C.aa_strips(frame, p, C.Timings(), gpu=device == "cuda") out = None for _ in range(max(1, a.repeat)): out = C.aa_strips(frame, p, timings, gpu=device == "cuda") picture = host(out) images = [None if s.why else host(aa.apply(frame, s.variant, device == "cuda")) for s in p.strips] elif dim == "scaler": if gl is not None: gl.load(frames[0]) for s in p.strips: if s.why: images.append(None) continue img = None for r in range(max(1, a.repeat) + 3): img, ms = gl.draw(s.variant, out_w, out_h, a.fsr_sharpness) if r >= 3 and s.variant != "off" and ms == ms: # (the first 3: warm-up) timings.add(C.timing_key("scaler", s.variant), ms) images.append(img) picture = C.compose(images, C.draws(p, out_w, out_h), np.zeros((out_h, out_w, 3), np.uint8)) elif dim == "look": if gl is not None: gl.load(frames[0]) for s in p.strips: if s.why: images.append(None) continue img = None for r in range(max(1, a.repeat) + 3): img, ms = gl.draw("bilinear" if (out_w, out_h) != (sw, sh) else "off", out_w, out_h, 0.5, look_plan if s.variant == "on" else None, look_r) if r >= 3 and s.variant == "on" and ms == ms: timings.add(C.timing_key("look", "on"), ms) images.append(img) picture = C.compose(images, C.draws(p, out_w, out_h), np.zeros((out_h, out_w, 3), np.uint8)) else: # framegen: the in-between frame of N and N+1 from framegen.interpolator import RifeInterpolator import torch as T it = RifeInterpolator(sw, sh, a.model, 1.0, fp16=device == "cuda", cuda_graph=False, device=device) mids = [] for k in range(len(frames) - 1): for slot, f in ((0, frames[k]), (1, frames[k + 1])): it.load(T.from_numpy(np.ascontiguousarray(f)).to(device)) it.prepare(slot) for r in range(max(1, a.repeat + 3 if k == 0 else 1)): if device == "cuda": T.cuda.synchronize() t1 = time.perf_counter() mid = it.interpolate(1, 0.5) if device == "cuda": T.cuda.synchronize() if k == 0 and r >= 3: # (the first 3: warm-up) timings.add(C.timing_key("framegen", "ai"), (time.perf_counter() - t1) * 1000) mids.append(host(mid).copy()) fps = file_fps(None if a.pattern else a.video) rates = {"game": fps, "shown": fps * 2} fg = C.FrameGenStrips() seq = [] # output frames in order: real N, generated N+0.5, real N+1, ... for k in range(len(frames) - 1): fg.real(frames[k]) seq.append(fg.present(frames[k], p, 2, sw, sh).copy()) seq.append(fg.present(mids[k], p, 2, sw, sh).copy()) picture = seq[1] # the in-between moment: Off holds frame N, On shows the generated frame images = [None if s.why else frames[0] if s.variant == "off" else mids[0] for s in p.strips] if a.sequence: texts = C.labels(p, timings, rates, caps) import cv2 cells = [] for i, f in enumerate(seq[:a.sequence]): # each frame shown, captioned, at half size, two to a row f = C.blend(f, C.overlay_items(p, texts, sw, sh, max(0.5, sh / 1080))) f = cv2.resize(f, (sw // 2, sh // 2), interpolation=cv2.INTER_AREA) cap = f"Output frame {i + 1}: " + ("the game's own frame" if i % 2 == 0 else "generated (Off still holds the last real one)") fs = U.font(max(11, sh // 40), "semibold") c = U.Canvas(U.text_w(cap, fs) + 20, int(fs.size * 1.8), U.BG, 6, border=U.BORDER) c.text(10, c.h // 2, cap, fs, U.TEXT) cells.append(C.blend(f, [(10, f.shape[0] - c.h - 10, c.rgba(0.9))])) if len(cells) % 2: cells.append(np.zeros_like(cells[0])) gap_v = np.full((sh // 2, 6, 3), 235, np.uint8) rows = [np.concatenate([cells[i], gap_v, cells[i + 1]], axis=1) for i in range(0, len(cells), 2)] gap_h = np.full((6, rows[0].shape[1], 3), 235, np.uint8) strip = np.concatenate(sum(([r, gap_h] for r in rows), [])[:-1], axis=0) seq_path = Path(a.out).with_name(Path(a.out).stem + "-sequence.png") write_png(seq_path, strip) print(f"[compare_shot] {seq_path}: {a.sequence} output frames in order, two to a row") out_w, out_h = sw, sh texts = C.labels(p, timings, rates, caps) ui = max(0.5, out_h / 1080) final = C.blend(picture, C.overlay_items(p, texts, out_w, out_h, ui, C.Live.HINT)) if a.title: c = U.Canvas(U.text_w(a.title, U.font(int(18 * ui), "semibold")) + int(28 * ui), int(34 * ui), U.BG, int(8 * ui), border=U.BORDER) c.text(c.w // 2, c.h // 2, a.title, U.font(int(18 * ui), "semibold"), U.TEXT, anchor="mm") final = C.blend(final, [((out_w - c.w) // 2, out_h - c.h - int(14 * ui), c.rgba(0.85))]) write_png(Path(a.out), final) print(f"[compare_shot] {a.out}: {DIMS[dim]} {out_w}x{out_h} from {sw}x{sh}, {renderer_note}, " f"{(time.perf_counter() - t0):.1f} s") for (title, sub), s in zip(texts, p.strips): print(f" {title:>14}: {sub or '-'}") if a.zoom: # the same part of each variant's picture, side by side, enlarged z = [int(v) for v in a.zoom.split(",")] x, y, w, h = z[:4] k = z[4] if len(z) > 4 else 4 cells = [] for s, im in zip(p.strips, images): crop = np.zeros((h, w, 3), np.uint8) if im is None else im[y:y + h, x:x + w] crop = np.repeat(np.repeat(crop, k, axis=0), k, axis=1) cp = C.Plan(p.dim, (s,), labels=True) name = s.name if not s.why else f"{s.name}: unavailable" cells.append(C.blend(crop, C.overlay_items(cp, [(name, "")], crop.shape[1], crop.shape[0], max(0.6, crop.shape[0] / 1080)))) cells.append(np.full((h * k, 6, 3), 235, np.uint8)) zpath = Path(a.out).with_name(Path(a.out).stem + "-zoom.png") write_png(zpath, np.concatenate(cells[:-1], axis=1)) print(f"[compare_shot] {zpath}: {w}x{h} at ({x}, {y}) of each, {k}x") if gl is not None: gl.close() return 0 DIMS = C.DIM_NAMES def write_png(path: Path, bgr: np.ndarray) -> None: from PIL import Image path.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(np.ascontiguousarray(bgr[..., ::-1])).save(path) if __name__ == "__main__": sys.exit(main())