Files
bonzi 0bf25d63f5 Linux capture cards: V4L2 picture + ALSA sound; GC311 plays on the RTX 5080
- framegen/capture_linux.py: devices via VIDIOC_QUERYCAP (/sys/class/video4linux),
  formats via ENUM_FMT/FRAMESIZES/FRAMEINTERVALS -> capture.Mode, ALSA cards from
  /proc/asound, busy/permission errors in plain words (names the app holding it)
- capture.CardSource: Linux opens video4linux2 + alsa as two inputs, sound on its
  own thread; needs PyAV built against system FFmpeg (--no-binary av)
- PyAV's bundled libasound: point ALSA_CONFIG_PATH at the system config
- winutil: nice -10 via rtkit MakeThreadHighPriorityWithPID instead of SCHED_RR
  (RLIMIT_RTTIME got the process SIGKILLed during startup); '--' before args
- Verified on the GC311: 1080p60 MJPEG via NVDEC, 62 fps, 0 dropped, sound in sync
2026-11-19 09:34:25 +00:00

357 lines
15 KiB
Python

"""Phase 0 of the Linux port (docs/linux-port/PLAN.md): does this PC's stack do what SmoovPlay needs?
python scripts/linux_spike.py [--json out/spike.json] [--skip-bench]
Each check prints one line, OK / WARN / FAIL with what it found, and the whole result goes to --json for
docs/linux-port/target.md. Nothing here changes the system. Checks:
system kernel, distribution, session type (Wayland/X11), desktop
driver nvidia-smi: GPU, driver, VRAM; nvidia-open (Blackwell needs the open kernel modules); nvidia_drm modeset
torch CUDA available, compute capability (12.0 on an RTX 5080), a real kernel on the card
rife RIFE 4.22 lite at 1080p, fp16, full and half motion detail (ms per in-between frame)
tensorrt tensorrt importable, its version
nvdec PyAV: HEVC 1080p decoded with hwaccel=cuda into a CUDA tensor, ms per frame
nvenc PyAV: h264_nvenc opens (instant replay)
gl a GLFW window (Wayland or X11), its GL vendor, and CUDA->GL texture interop (framegen/glcuda.py)
vfx nvidia-vfx (NVIDIA VFG / RTX VSR) importable, if installed
chiaki chiaki-ng on PATH, and whether it has the frame tap
capture V4L2 devices (/sys/class/video4linux), with v4l2-ctl's formats if it's installed; ALSA capture cards
rt real-time scheduling for the frame threads (direct or rtkit)
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
results: dict[str, dict] = {}
def report(name: str, status: str, text: str, **data) -> None:
results[name] = {"status": status, "text": text, **data}
print(f"[{status:4}] {name:9} {text}", flush=True)
def run(cmd: list[str], timeout: float = 20) -> str:
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip()
except (OSError, subprocess.SubprocessError):
return ""
def check(name: str):
def wrap(fn):
def go(*a, **k):
try:
fn(*a, **k)
except Exception as e: # noqa: BLE001 - one check failing mustn't stop the others
report(name, "FAIL", f"{type(e).__name__}: {str(e)[:300]}")
return go
return wrap
@check("system")
def system() -> None:
distro = ""
try:
for line in Path("/etc/os-release").read_text().splitlines():
if line.startswith("PRETTY_NAME="):
distro = line.split("=", 1)[1].strip('"')
except OSError:
pass
session = os.environ.get("XDG_SESSION_TYPE", "?")
desktop = os.environ.get("XDG_CURRENT_DESKTOP", "?")
plasma = run(["plasmashell", "--version"])
ok = session == "wayland"
report("system", "OK" if ok else "WARN", f"{distro}, kernel {platform.release()}, {session} session, {desktop}"
+ (f" ({plasma})" if plasma else ""), distro=distro, kernel=platform.release(), session=session,
desktop=desktop, plasma=plasma, python=sys.version.split()[0])
@check("driver")
def driver() -> None:
q = run(["nvidia-smi", "--query-gpu=name,driver_version,memory.total,compute_cap", "--format=csv,noheader"])
if not q:
report("driver", "FAIL", "nvidia-smi didn't answer (no NVIDIA driver loaded?)")
return
name, ver, mem, cap = [x.strip() for x in q.splitlines()[0].split(",")]
lic = Path("/sys/module/nvidia/version")
open_modules = "Open" in (Path("/proc/driver/nvidia/version").read_text() if
Path("/proc/driver/nvidia/version").exists() else "")
modeset = Path("/sys/module/nvidia_drm/parameters/modeset")
ms = modeset.read_text().strip() if modeset.exists() else "?"
major = int(ver.split(".")[0]) if ver.split(".")[0].isdigit() else 0
bad = []
if major < 570:
bad.append("driver < 570 (RTX 50 needs 570+)")
if not open_modules:
bad.append("not the open kernel modules (Blackwell needs nvidia-open)")
if ms != "Y":
bad.append(f"nvidia_drm.modeset={ms}")
report("driver", "OK" if not bad else "WARN", f"{name}, driver {ver}, {mem}, compute {cap}, "
f"{'open' if open_modules else 'proprietary'} modules, modeset {ms}" + (f" - {'; '.join(bad)}" if bad else ""),
gpu=name, driver=ver, vram=mem, compute_cap=cap, open_modules=open_modules, modeset=ms,
module_version=lic.read_text().strip() if lic.exists() else "")
@check("torch")
def torch_check() -> None:
import torch
if not torch.cuda.is_available():
report("torch", "FAIL", f"torch {torch.__version__}: CUDA not available")
return
cap = torch.cuda.get_device_capability(0)
x = torch.randn(4096, 4096, device="cuda", dtype=torch.float16)
for _ in range(5): # warm up: cuBLAS picks its kernel on the first calls
y = x @ x
torch.cuda.synchronize()
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
s.record()
for _ in range(50):
y = x @ x
e.record()
torch.cuda.synchronize()
tflops = 50 * 2 * 4096 ** 3 / (s.elapsed_time(e) / 1000) / 1e12
del y
archs = torch.cuda.get_arch_list()
has = f"sm_{cap[0]}{cap[1]}" in archs
report("torch", "OK" if has else "WARN", f"torch {torch.__version__} (CUDA {torch.version.cuda}), "
f"{torch.cuda.get_device_name(0)}, sm_{cap[0]}{cap[1]} {'built in' if has else 'NOT in ' + str(archs)}, "
f"fp16 matmul {tflops:.0f} TFLOPS", torch=torch.__version__, cuda=torch.version.cuda, capability=cap,
archs=archs, fp16_tflops=round(tflops, 1))
@check("rife")
def rife(skip: bool) -> None:
if skip:
report("rife", "SKIP", "--skip-bench")
return
import torch
from framegen.interpolator import RifeInterpolator
out = {}
w, h = 1920, 1080
frame = torch.randint(0, 256, (h, w, 3), dtype=torch.uint8, device="cuda")
for scale in (1.0, 0.5):
# As scripts/benchmark.py: prepare() is the per-real-frame work, interpolate() one in-between frame
it = RifeInterpolator(w, h, "4.22.lite", scale, backend="torch")
it.load(frame)
it.prepare(0)
for _ in range(10):
it.prepare(1)
it.interpolate(1)
torch.cuda.synchronize()
ts = []
for _ in range(60):
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
s.record()
it.interpolate(1)
e.record()
torch.cuda.synchronize()
ts.append(s.elapsed_time(e))
ts.sort()
out[scale] = (ts[len(ts) // 2], ts[int(len(ts) * 0.99) - 1])
del it
torch.cuda.empty_cache()
full, half = out[1.0], out[0.5]
# 120 fps needs three in-between frames per 33.3 ms real frame, with room for upload and present
fits120 = 3 * full[0] < 25
report("rife", "OK", f"RIFE 4.22 lite 1080p fp16 (PyTorch): full {full[0]:.1f} ms (p99 {full[1]:.1f}), half "
f"{half[0]:.1f} ms; 120 fps at full detail {'fits' if fits120 else 'is tight'} "
"(RTX 4070 Ti SUPER, TensorRT: about 9 ms)",
full_p50=full[0], full_p99=full[1], half_p50=half[0], half_p99=half[1])
@check("tensorrt")
def tensorrt_check() -> None:
try:
import tensorrt as trt
except ImportError:
report("tensorrt", "WARN", "tensorrt not installed (pip install tensorrt-cu12): PyTorch engine only")
return
report("tensorrt", "OK", f"TensorRT {trt.__version__}", version=trt.__version__)
@check("nvdec")
def nvdec() -> None:
import av
import torch
from av.codec.hwaccel import HWAccel
if not shutil.which("ffmpeg"):
report("nvdec", "WARN", "no ffmpeg to make a test clip")
return
clip = Path(os.environ.get("TMPDIR", "/tmp")) / "sp-spike-hevc.mkv"
if not clip.exists():
subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=1920x1080:rate=60",
"-t", "3", "-c:v", "libx265", "-preset", "ultrafast", "-x265-params", "log-level=none",
str(clip)], check=True)
from framegen.chiaki_tap import cuda_frame_to_bgr
torch.zeros(1, device="cuda")
with av.open(str(clip), hwaccel=HWAccel("cuda", options={"primary_ctx": "0", "current_ctx": "1"},
is_hw_owned=True)) as c:
n, t0, on_gpu, x = 0, time.perf_counter(), None, None
for fr in c.decode(video=0):
x = cuda_frame_to_bgr(fr)
on_gpu = fr.format.name == "cuda"
n += 1
torch.cuda.synchronize()
ms = (time.perf_counter() - t0) / max(n, 1) * 1000
report("nvdec", "OK" if on_gpu else "WARN", f"HEVC 1080p: {n} frames, {ms:.2f} ms each to a CUDA BGR tensor, "
f"{'on the GPU (NVDEC)' if on_gpu else 'fell back to software'}", ms=ms, on_gpu=on_gpu,
shape=list(x.shape) if x is not None else None)
@check("nvenc")
def nvenc() -> None:
import av
c = av.CodecContext.create("h264_nvenc", "w")
c.width, c.height, c.pix_fmt, c.time_base = 1920, 1080, "yuv420p", __import__("fractions").Fraction(1, 90)
c.open()
report("nvenc", "OK", "h264_nvenc opens (instant replay can record on the GPU)")
@check("gl")
def gl() -> None:
import glfw
from OpenGL import GL
if not glfw.init():
report("gl", "FAIL", "glfw.init failed (no display?)")
return
try:
platform_name = {getattr(glfw, k, -1): k for k in ("PLATFORM_WAYLAND", "PLATFORM_X11")}.get(
glfw.get_platform() if hasattr(glfw, "get_platform") else -2, "?")
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
win = glfw.create_window(640, 360, "SmoovPlay spike", None, None)
glfw.make_context_current(win)
vendor = GL.glGetString(GL.GL_VENDOR).decode()
renderer = GL.glGetString(GL.GL_RENDERER).decode()
version = GL.glGetString(GL.GL_VERSION).decode()
mon = glfw.get_primary_monitor()
mode = glfw.get_video_mode(mon) if mon else None
hz = mode.refresh_rate if mode else None
res = f"{mode.size.width}x{mode.size.height}" if mode else "?"
import torch
from framegen.glcuda import CudaGLTexture, cudart_path
tex = GL.glGenTextures(1)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, 1920, 1080, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
up = CudaGLTexture(tex, 1920, 1080)
frame = torch.full((1080, 1920, 3), 77, dtype=torch.uint8, device="cuda")
for _ in range(5):
up.upload(frame)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(100):
up.upload(frame)
torch.cuda.synchronize()
ms = (time.perf_counter() - t0) * 10
px = (GL.GLubyte * 4)()
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)
GL.glReadPixels(0, 0, 1, 1, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, px)
right = list(px)[:3] == [77, 77, 77]
report("gl", "OK" if right and "NVIDIA" in vendor else "WARN",
f"GLFW on {platform_name}, {renderer} ({version}), display {res} @ {hz} Hz; CUDA->GL copy "
f"{ms:.3f} ms per 1080p frame, read back {'right' if right else 'WRONG: ' + str(list(px))}",
platform=platform_name, vendor=vendor, renderer=renderer, version=version, refresh=hz, resolution=res,
interop_ms=ms, interop_right=right, cudart=cudart_path())
glfw.destroy_window(win)
finally:
glfw.terminate()
@check("vfx")
def vfx() -> None:
try:
import nvvfx # noqa: F401
except ImportError:
report("vfx", "SKIP", "nvidia-vfx not installed (optional: NVIDIA VFG / RTX VSR, needs NVIDIA's licence)")
return
report("vfx", "OK", "nvidia-vfx imports")
@check("chiaki")
def chiaki() -> None:
exe = shutil.which("chiaki") or shutil.which("chiaki-ng")
if not exe:
report("chiaki", "WARN", "chiaki-ng isn't installed (chiaki_tap/PKGBUILD builds the one with the tap)")
return
with open(exe, "rb") as f:
tap = b"CHIAKI_FRAMETAP" in f.read()
report("chiaki", "OK" if tap else "WARN", f"{exe}: {'has the frame tap' if tap else 'plain chiaki-ng (no tap)'}",
path=exe, tap=tap)
@check("capture")
def capture() -> None:
devs = []
for d in sorted(Path("/sys/class/video4linux").glob("video*")):
name = (d / "name").read_text().strip() if (d / "name").exists() else "?"
devs.append({"dev": f"/dev/{d.name}", "name": name})
v4l2 = shutil.which("v4l2-ctl")
for d in devs:
if v4l2:
out = run([v4l2, "-d", d["dev"], "--list-formats-ext"])
d["formats"] = out
cards = run(["arecord", "-l"])
gc311 = [d for d in devs if "GC311" in d["name"] or "Live Gamer" in d["name"] or "AVerMedia" in d["name"]]
text = ", ".join(f"{d['dev']} {d['name']}" for d in devs) or "no V4L2 devices"
report("capture", "OK" if gc311 else "WARN", text + ("" if v4l2 else " (install v4l-utils for formats)"),
devices=devs, alsa=cards)
@check("rt")
def rt() -> None:
import threading
from framegen import winutil
res = {}
def go():
res["ok"] = winutil.boost_thread()
res["nice"] = os.getpriority(os.PRIO_PROCESS, threading.get_native_id())
t = threading.Thread(target=go)
t.start()
t.join()
up = res.get("nice", 0) < 0
report("rt", "OK" if res.get("ok") and up else "WARN",
f"frame threads get a raised CPU priority (nice {res.get('nice')})" if up else
"no raised CPU priority (install rtkit; it only grants it to programs started in the desktop session)",
ok=res.get("ok"), nice=res.get("nice"))
def main() -> int:
ap = argparse.ArgumentParser(description="Phase 0 of the Linux port: check this PC's stack")
ap.add_argument("--json", help="write every result here")
ap.add_argument("--skip-bench", action="store_true", help="skip the RIFE timing (needs the weights download)")
a = ap.parse_args()
system()
driver()
torch_check()
rife(a.skip_bench)
tensorrt_check()
nvdec()
nvenc()
gl()
vfx()
chiaki()
capture()
rt()
if a.json:
Path(a.json).parent.mkdir(parents=True, exist_ok=True)
Path(a.json).write_text(json.dumps(results, indent=2, default=str))
print(f"wrote {a.json}")
return 1 if any(r["status"] == "FAIL" for r in results.values()) else 0
if __name__ == "__main__":
sys.exit(main())