Linux: chiaki-ng minimises itself on request, Arch PKGBUILD, Phase 0 spike script

- frame tap: window_request word (offset 100, feature bit 32): SmoovPlay asks
  chiaki-ng to minimise/restore its own windows (Wayland forbids doing it from
  outside); run.py uses it on Linux. Covered by chiaki_tap/selftest.py
- chiaki_tap/PKGBUILD (chiaki-ng-smoovplay, v1.10.1) + build_linux.sh; built in
  an archlinux:latest container (needs system curl: the bundled one fails with
  Arch's OpenSSL)
- scripts/linux_spike.py: Phase 0 checks in one command
- docs/linux-port: progress log, QUICKSTART
This commit is contained in:
bonzi committed 2026-11-19 08:39:37 +00:00
1 parent b206fb2c31
commit 7eba48426f
13 files changed
+610 -7

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
# chiaki-ng with SmoovPlay's frame tap (chiaki_tap/), for Arch Linux.
#
# cd chiaki_tap && makepkg -si
#
# Builds chiaki-ng v1.10.1 (the version apply_patch.py's edits are written against) with the tap compiled in. With
# CHIAKI_FRAMETAP unset it behaves exactly like chiaki-ng; SmoovPlay starts it with CHIAKI_FRAMETAP=1. It replaces
# the chiaki-ng package (provides/conflicts), so the controller mapping and registered consoles carry over.
#
# chiaki-ng is AGPL-3.0; the tap files are MIT (SmoovPlay). The result is a build of chiaki-ng, under its licence.
pkgname=chiaki-ng-smoovplay
_tag=v1.10.1
pkgver=1.10.1
pkgrel=1
pkgdesc="chiaki-ng (PS5 Remote Play) with SmoovPlay's frame tap, for SmoovPlay's frame generation"
arch=('x86_64')
url="https://github.com/smoovplay/smoovplay"
license=('AGPL-3.0-only' 'MIT')
depends=('qt6-base' 'qt6-declarative' 'qt6-svg' 'qt6-wayland' 'qt6-webengine' 'qt6-positioning' 'ffmpeg'
'sdl2-compat' 'opus' 'openssl' 'json-c' 'miniupnpc' 'libevent' 'hidapi' 'libplacebo' 'speexdsp' 'fftw'
'lcms2' 'libdovi' 'shaderc' 'spirv-cross' 'protobuf' 'systemd-libs' 'libevdev' 'curl')
makedepends=('cmake' 'ninja' 'git' 'python' 'python-protobuf' 'python-setuptools' 'qt6-shadertools'
'vulkan-headers' 'fast_float')
provides=('chiaki-ng')
conflicts=('chiaki-ng' 'chiaki-ng-bin' 'chiaki-ng-git')
source=("chiaki-ng::git+https://github.com/streetpea/chiaki-ng.git#tag=${_tag}"
'apply_patch.py' 'frametap.c' 'frametap.h' 'frametap_session.cpp' 'frametap_session.h')
sha256sums=('SKIP' 'SKIP' 'SKIP' 'SKIP' 'SKIP' 'SKIP') # the tap files come from this folder; the tag pins chiaki-ng
prepare() {
cd chiaki-ng
git submodule update --init --recursive --depth 1
python "${srcdir}/apply_patch.py" .
}
build() {
cmake -S chiaki-ng -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr \
-DCHIAKI_ENABLE_CLI=OFF -DCHIAKI_ENABLE_TESTS=OFF -DCHIAKI_USE_SYSTEM_CURL=ON # the bundled curl fails on OpenSSL 3.6+
cmake --build build --target chiaki
}
package() {
DESTDIR="${pkgdir}" cmake --install build --component Unspecified 2>/dev/null || DESTDIR="${pkgdir}" cmake --install build
install -Dm644 chiaki-ng/COPYING "${pkgdir}/usr/share/licenses/${pkgname}/COPYING"
}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
# Build chiaki-ng with the frame tap on Linux, without packaging it (on Arch, prefer `makepkg -si` with the PKGBUILD
# in this folder):
#
# bash chiaki_tap/build_linux.sh <chiaki-ng source, at v1.10.1> <build folder>
#
# Needs chiaki-ng's build dependencies (see the PKGBUILD's depends and makedepends for Arch's names). The result is
# <build folder>/gui/chiaki; start it with the tap on:
#
# CHIAKI_FRAMETAP=1 <build folder>/gui/chiaki
set -euo pipefail
SRC="${1:?usage: build_linux.sh <chiaki-ng source> <build folder>}"
OUT="${2:?usage: build_linux.sh <chiaki-ng source> <build folder>}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "=== submodules"
git -C "$SRC" submodule update --init --recursive --depth 1
echo "=== frame tap patch"
python3 "$HERE/apply_patch.py" "$SRC"
echo "=== configure + build chiaki-ng"
cmake -S "$SRC" -B "$OUT" -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCHIAKI_ENABLE_CLI=OFF -DCHIAKI_ENABLE_TESTS=OFF -DCHIAKI_USE_SYSTEM_CURL=ON # the bundled curl fails on OpenSSL 3.6+
cmake --build "$OUT" --target chiaki
echo
echo "done: CHIAKI_FRAMETAP=1 $OUT/gui/chiaki"
+10 -1
View File
@@ -219,8 +219,9 @@ bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t ma
*H64(48) = freq;
*H32(40) = 0;
*H32(64) = FRAMETAP_FEATURE_PRESS | FRAMETAP_FEATURE_AUDIO_DELAY | (g_abase ? FRAMETAP_FEATURE_AUDIO_TAP : 0u)
| FEATURE_PLATFORM;
| FRAMETAP_FEATURE_WINDOW | FEATURE_PLATFORM;
*H32(68) = 0;
*H32(FRAMETAP_WINDOW_OFFSET) = 0;
audio_header(freq);
// The reader treats a new session as a new stream: it resets its decoder and waits for a keyframe.
XCHG64(H64(32), 0);
@@ -278,6 +279,13 @@ uint32_t frametap_take_press_request(uint32_t *hold_ms)
return buttons;
}
uint32_t frametap_take_window_request(void)
{
if(!g_base)
return 0;
return (uint32_t)XCHG32(H32(FRAMETAP_WINDOW_OFFSET), 0);
}
void frametap_press_sent(void)
{
if(!g_base)
@@ -368,6 +376,7 @@ void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool re
(void)buf; (void)size; (void)frames_lost; (void)recovered;
}
bool frametap_take_idr_request(void) { return false; }
uint32_t frametap_take_window_request(void) { return 0; }
uint32_t frametap_take_press_request(uint32_t *hold_ms) { (void)hold_ms; return 0; }
uint32_t frametap_audio_delay_ms(void) { return 0; }
void frametap_audio_format(uint32_t rate, uint32_t channels) { (void)rate; (void)channels; }
+9
View File
@@ -23,6 +23,8 @@
// 88 u32 audio_delay_ms (reader: hold chiaki-ng's sound back this long, to meet SmoovPlay's picture; ignored
// once the reader's heartbeat is over 2 s old, so sound comes back on time if SmoovPlay stops)
// 96 u32 wake (Linux writer: bumped after each frame and at the end, then FUTEX_WAKE on it; feature bit 4)
// 100 u32 window_request (reader: 1 minimise chiaki-ng's windows, 2 show them again; the writer clears it and
// does it, feature bit 5). On Wayland one program can't minimise another's window, so chiaki-ng does its own.
// features bit 1: it honours audio_delay_ms; bit 2: it writes the sound ring below; bit 4: it wakes the reader
// through `wake` (Linux; bit 3, variable frame timing, is for other writers: docs/frame-tap.md).
// slot i at 4096 + i * slot_size:
@@ -59,7 +61,11 @@ extern "C" {
#define FRAMETAP_FEATURE_AUDIO_DELAY 2u
#define FRAMETAP_FEATURE_AUDIO_TAP 4u
#define FRAMETAP_FEATURE_WAKE 16u
#define FRAMETAP_FEATURE_WINDOW 32u
#define FRAMETAP_WAKE_OFFSET 96u
#define FRAMETAP_WINDOW_OFFSET 100u
#define FRAMETAP_WINDOW_MINIMIZE 1u
#define FRAMETAP_WINDOW_RESTORE 2u
#define FRAMETAP_AUDIO_SUFFIX "-audio"
#define FRAMETAP_AUDIO_MAGIC 0x41544643u /* 'CFTA' */
#define FRAMETAP_AUDIO_HEADER 64u
@@ -86,6 +92,9 @@ uint32_t frametap_take_press_request(uint32_t *hold_ms);
// Call right after a press went to the PS5: the reader times the PS5's response from here.
void frametap_press_sent(void);
// What the reader asked chiaki-ng's windows to do, once per request: FRAMETAP_WINDOW_MINIMIZE, _RESTORE or 0.
uint32_t frametap_take_window_request(void);
// How long to hold the sound back (0-500 ms), as the reader asked; 0 if it hasn't, or has stopped.
uint32_t frametap_audio_delay_ms(void);
+20
View File
@@ -6,8 +6,10 @@
#include <frametap.h>
#include <streamsession.h>
#include <QGuiApplication>
#include <QMetaObject>
#include <QTimer>
#include <QWindow>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
@@ -49,6 +51,8 @@ bool FrameTapSession::VideoSample(uint8_t *buf, size_t buf_size, int32_t frames_
uint32_t hold_ms = 0;
if(uint32_t buttons = frametap_take_press_request(&hold_ms))
QMetaObject::invokeMethod(session, [session, buttons, hold_ms]() { Press(session, buttons, hold_ms); }, Qt::QueuedConnection);
if(uint32_t what = frametap_take_window_request())
QMetaObject::invokeMethod(session, [what]() { Windows(what); }, Qt::QueuedConnection);
return chiaki_ffmpeg_decoder_video_sample_cb(buf, buf_size, frames_lost, frame_recovered, session->ffmpeg_decoder);
}
@@ -64,6 +68,22 @@ void FrameTapSession::Press(StreamSession *session, uint32_t buttons, uint32_t h
});
}
// SmoovPlay's video window is in front: chiaki-ng's own (which would draw the unsmoothed stream, taking GPU time)
// goes down, and comes back when SmoovPlay is done. On Windows SmoovPlay can do this itself; on Wayland a program can
// only minimise its own windows, so SmoovPlay asks here. chiaki-ng keeps streaming and reading the controller.
void FrameTapSession::Windows(uint32_t what)
{
for(QWindow *w : QGuiApplication::topLevelWindows())
{
if(!w->isVisible() && what == FRAMETAP_WINDOW_MINIMIZE)
continue;
if(what == FRAMETAP_WINDOW_MINIMIZE)
w->showMinimized();
else if(what == FRAMETAP_WINDOW_RESTORE && w->windowState() & Qt::WindowMinimized)
w->showNormal();
}
}
// Sound held back by SmoovPlay's picture delay (frametap_audio_delay_ms): a first-in first-out buffer of exactly
// that much sound. Each frame in sends one frame's worth out, so the device is fed as steadily as before; while the
// delay grows that's silence, and when it shrinks the oldest sound is skipped.
+1
View File
@@ -32,4 +32,5 @@ class FrameTapSession
private:
static bool VideoSample(uint8_t *buf, size_t buf_size, int32_t frames_lost, bool frame_recovered, void *user);
static void Press(StreamSession *session, uint32_t buttons, uint32_t hold_ms);
static void Windows(uint32_t what);
};
+6 -1
View File
@@ -69,10 +69,15 @@ int main(void)
}
Sleep(30); // "sending"
frametap_press_sent();
// Then SmoovPlay asks chiaki-ng to minimise its windows (Linux; on Windows it can do that itself).
uint32_t window = 0;
for(t = 0; t < 500 && !(window = frametap_take_window_request()); t++)
Sleep(10);
uint32_t delay = 0;
for(t = 0; t < 500 && !(delay = frametap_audio_delay_ms()); t++)
Sleep(10);
printf("idr request seen; press %u for %u ms sent; audio delay %u ms\n", buttons, hold_ms, delay);
printf("idr request seen; press %u for %u ms sent; window request %u; audio delay %u ms\n", buttons, hold_ms, window,
delay);
fflush(stdout);
// Once the reader stops its heartbeat, the delay lapses on its own.
for(t = 0; t < 400 && frametap_audio_delay_ms(); t++)
+6 -3
View File
@@ -20,7 +20,8 @@ from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
from framegen.chiaki_tap import (AUDIO_SUFFIX, BUTTON_OPTIONS, FEATURE_AUDIO_DELAY, FEATURE_AUDIO_TAP, # noqa: E402
FEATURE_PRESS, FEATURE_WAKE, AudioTap, FrameTap)
FEATURE_PRESS, FEATURE_WAKE, FEATURE_WINDOW, WINDOW_MINIMIZE,
AudioTap, FrameTap)
NAME = r"Local\chiaki-frametap-selftest"
@@ -67,12 +68,14 @@ def main() -> int:
assert 0 < time.perf_counter() - chunks[0].t < 10, "sound arrival time off"
# The delay test's press: asked for, sent by the writer, timed in our clock
wake = 0 if sys.platform == "win32" else FEATURE_WAKE # Linux: the writer wakes us through the header's futex
assert tap.features() == FEATURE_PRESS | FEATURE_AUDIO_DELAY | FEATURE_AUDIO_TAP | wake, tap.features()
assert tap.features() == FEATURE_PRESS | FEATURE_AUDIO_DELAY | FEATURE_AUDIO_TAP | FEATURE_WINDOW | wake, \
tap.features()
t_ask = time.perf_counter()
token = tap.press(BUTTON_OPTIONS, 120)
while (sent := tap.press_sent(token, h.qpc_freq)) is None and time.perf_counter() - t_ask < 5:
time.sleep(0.005)
assert sent is not None and t_ask < sent < time.perf_counter(), "press not sent, or its time is off"
tap.window_request(WINDOW_MINIMIZE)
# The sound delay holds while our heartbeat is fresh, then lapses
tap.set_audio_delay(42)
for _ in range(20):
@@ -80,7 +83,7 @@ def main() -> int:
time.sleep(0.05)
out, err = proc.communicate(timeout=15)
assert proc.returncode == 0, (proc.returncode, out, err)
assert f"press {BUTTON_OPTIONS} for 120 ms sent; audio delay 42 ms" in out, out
assert f"press {BUTTON_OPTIONS} for 120 ms sent; window request {WINDOW_MINIMIZE}; audio delay 42 ms" in out, out
assert "audio delay lapsed: yes" in out, out
assert not tap.header().live, "end-of-stream not marked"
assert not sound.live(), "sound ring's end not marked"
+33 -1
View File
@@ -3,7 +3,9 @@
**Target:** Arch Linux, NVIDIA GeForce RTX 5080 (Blackwell, `sm_120`, 16 GB), Wayland first (X11 supported).
**Repo:** `git.molberg.cloud/alex/smoovplay` (fork). `upstream` branch = pristine mirror of
`github.com/smoovplay/smoovplay` `main`; `main` = the port. Forked at upstream **v0.3.8** (`33a80b6`).
**Status:** plan only, no port code yet. Written 2026-11-19 by Bonzi; decisions from Zeb added the same day (§8).
**Status (2026-11-19):** Phase 1 done on Linux without a GPU; the parts of Phase 3 that don't need the box are done.
Waiting for SSH to the desktop for Phase 0. See §9 for what's built and verified.
Written 2026-11-19 by Bonzi; decisions from Zeb added the same day (§8).
---
@@ -333,3 +335,33 @@ Phases 4, 5, 6 and 8 are independent of each other once 3 lands, so they can run
keep the code upstreamable (Principle 5), credit upstream everywhere, no rebranding.
Still open: HDR monitor model and max refresh (Phase 6 only).
## 9. Progress log
**2026-11-19: before access to the desktop** (on Bonzi's Linux host: CPU only, no display; branch `linux/phase-1`, merged to `main`)
Done and verified:
- `framegen/oslayer.py`, the Windows/Linux seam: XDG folders (`~/.config/smoovplay`, `~/.cache/smoovplay`,
`XDG_VIDEOS_DIR`), the frame tap's clock (`CLOCK_MONOTONIC` ns, `qpc_freq` 1e9), POSIX shared memory (`/dev/shm`,
mode 0600) and a futex wake-up. Windows paths and APIs are unchanged.
- **Frame tap on Linux, both sides.** `chiaki_tap/frametap.c` (inside chiaki-ng), `framegen/chiaki_tap.py`,
`framegen/tap.py` and `docs/frame-tap-writer.c`. The layout is unchanged apart from two new header words: `wake`
(96, feature bit 16) and `window_request` (100, feature bit 32). `chiaki_tap/selftest.py` passes on Linux: the C
writer and the Python reader agree byte for byte, including the delay test's press, sound delay, sound ring and
window request. The Windows build still compiles (mingw cross-compile of `frametap.c`, `selftest.c` and the docs writer).
- **chiaki-ng minimises itself when asked** (`FrameTapSession::Windows`), since Wayland doesn't let SmoovPlay
minimise it. `run.py` uses this outside Windows.
- **chiaki-ng v1.10.1 + tap builds on Arch** (archlinux:latest container, current packages): `apply_patch.py`
applies cleanly, and the binary contains the tap. Needs `-DCHIAKI_USE_SYSTEM_CURL=ON`, because the bundled curl
doesn't build against Arch's OpenSSL. `chiaki_tap/PKGBUILD` (`chiaki-ng-smoovplay`) + `build_linux.sh`.
- **Security fix:** LUT names and look ids lose folders on every OS (`..\..\x.cube` got through on Linux).
- Windows-only modules import on Linux; `boost_thread` → SCHED_RR 10 (direct or via rtkit); `glcuda` finds
`libcudart.so`.
- `pytest tests` on Linux: **403 passed, 0 failed, 14 skipped** (baseline: 328 passed, 6 failed). New tests:
`tests/test_oslayer.py`; the frame tap tests and the fake-PS5 end-to-end test now run on Linux.
- `scripts/linux_spike.py`: the Phase 0 checks in one command (driver/open modules, sm_120, RIFE timing, TensorRT,
NVDEC, NVENC, GLFW on Wayland + CUDA↔GL interop with read-back, nvidia-vfx, chiaki-ng tap, V4L2/ALSA for the
GC311, real-time scheduling). Tested here; the GPU checks fail cleanly without a GPU.
Not verifiable without the desktop: everything on the GPU and display (Phase 0, 2), a real PS5 session (Phase 3
gate), the GC311 (Phase 5).
+56
View File
@@ -0,0 +1,56 @@
# SmoovPlay on Linux: developer quickstart (Arch + NVIDIA)
Work in progress (see [PLAN.md](PLAN.md)). This is the setup for Phase 0 on the target desktop, not an end-user install.
## 1. System packages
```bash
sudo pacman -S --needed nvidia-open nvidia-utils ffmpeg git base-devel python uv v4l-utils alsa-utils rtkit
```
`nvidia-open` is required for RTX 50 (Blackwell). Reboot after a driver change.
## 2. Python environment (3.12, pinned like upstream)
```bash
git clone https://git.molberg.cloud/alex/smoovplay.git && cd smoovplay
uv venv -p 3.12 .venv && source .venv/bin/activate
uv pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cu128
uv pip install numpy opencv-python glfw PyOpenGL av sounddevice pytest
uv pip install tensorrt-cu12 onnx onnxscript # optional: the TensorRT engine
```
## 3. Phase 0 check
```bash
python scripts/linux_spike.py --json out/spike.json
```
Run it in the Plasma Wayland session (it opens a hidden GL window). Every line should say OK. RIFE downloads its
weights into `models/` the first time.
## 4. Tests
```bash
pytest tests -q
python chiaki_tap/selftest.py # chiaki-ng's C frame tap vs the Python reader
```
## 5. chiaki-ng with the frame tap
```bash
cd chiaki_tap && makepkg -si # chiaki-ng-smoovplay, replaces chiaki-ng
CHIAKI_FRAMETAP=1 chiaki # SmoovPlay's launcher will do this for you later
```
## 6. Try it without a PS5
Any 60 fps gameplay recording works; `testdata/` isn't in the repo, so put one there first.
```bash
python scripts/frametap_fake.py testdata/clip_1080p60.mp4 --chiaki-like & # a fake PS5 through the tap
python run.py --chiaki --display # SmoovPlay, 90/120 fps
```
Settings live in `~/.config/smoovplay/settings.json`, looks in `~/.config/smoovplay/looks/`, and instant replay
clips go to `~/Videos/SmoovPlay` (or wherever `XDG_VIDEOS_DIR` points).
+21
View File
@@ -64,6 +64,8 @@ FEATURE_PRESS, FEATURE_AUDIO_DELAY, FEATURE_AUDIO_TAP = 1, 2, 4 # header `featu
FEATURE_VARIABLE = 8 # frames come when the picture changes, not once a refresh: the reader puts them on a beat
FEATURE_WAKE = 16 # Linux: the writer bumps the u32 at WAKE_OFFSET and futex-wakes it after each frame and at the end
WAKE_OFFSET = 96
FEATURE_WINDOW = 32 # the writer minimises / shows its own windows when asked (WINDOW_OFFSET): what Wayland allows
WINDOW_OFFSET, WINDOW_MINIMIZE, WINDOW_RESTORE = 100, 1, 2
FLAG_TRUNCATED, FLAG_REPEAT, FLAG_NEW = 1, 2, 4 # slot `flags`: REPEAT/NEW are the writer's own word on the frame
@@ -188,6 +190,17 @@ class FrameTap:
def set_audio_delay(self, ms: int) -> None:
struct.pack_into("<I", self.mm, 88, max(0, min(500, int(ms))))
def window_request(self, what: int) -> None:
"""Ask the writer to minimise (WINDOW_MINIMIZE) or show again (WINDOW_RESTORE) its own windows."""
struct.pack_into("<I", self.mm, WINDOW_OFFSET, what)
def take_window_request(self) -> int:
"""Writer side (tests, the fake PS5): the request, once."""
(what,) = struct.unpack_from("<I", self.mm, WINDOW_OFFSET)
if what:
struct.pack_into("<I", self.mm, WINDOW_OFFSET, 0)
return what
def wait(self, timeout_s: float) -> None:
"""Until the writer signals (a frame, or the stream's end) or timeout_s. A signal since the last wait counts, as
with Windows' auto-reset event, so one that came between the caller's check and this call isn't missed."""
@@ -795,6 +808,14 @@ class ChiakiSource:
def can_press(self) -> bool:
return bool(self.tap.features() & FEATURE_PRESS)
def can_hide_windows(self) -> bool:
"""Whether the chiaki-ng streaming minimises its own windows when asked (Linux, where we can't)."""
return bool(self.tap.features() & FEATURE_WINDOW)
def hide_windows(self, hide: bool) -> None:
"""Ask chiaki-ng to minimise its windows (True) or show them again (False)."""
self.tap.window_request(WINDOW_MINIMIZE if hide else WINDOW_RESTORE)
def can_delay_audio(self) -> bool:
return bool(self.tap.features() & FEATURE_AUDIO_DELAY)
+21 -1
View File
@@ -616,10 +616,24 @@ def main() -> int:
handlers=window.remote_commands())
hidden: list[int] = []
# Outside Windows a program can't minimise another's windows (Wayland forbids it), so chiaki-ng is asked through
# the frame tap to minimise its own (FrameTapSession::Windows); hidden then holds a marker, not window handles.
own_windows = sys.platform != "win32"
def minimize_chiaki(key: str = "minimize_chiaki") -> None:
if key != "minimize_chiaki" or not (picked == "chiaki" and window is not None):
return
if own_windows:
if not hasattr(src, "can_hide_windows") or not src.can_hide_windows():
return
if settings.minimize_chiaki and not hidden:
src.hide_windows(True)
hidden[:] = [0]
print("[run] asked chiaki-ng to minimise its window; restored on exit")
elif not settings.minimize_chiaki and hidden:
src.hide_windows(False)
hidden.clear()
return
from framegen.winutil import SW_SHOWMINNOACTIVE, SW_SHOWNOACTIVATE, show, windows_of
if settings.minimize_chiaki and not hidden:
hidden[:] = windows_of("chiaki.exe")
@@ -636,6 +650,10 @@ def main() -> int:
restores it, after it was minimised. Minimise it again."""
if not (picked == "chiaki" and settings.minimize_chiaki):
return
if own_windows:
if hidden and hasattr(src, "hide_windows"):
src.hide_windows(True) # chiaki-ng skips windows already down
return
from framegen.winutil import SW_SHOWMINNOACTIVE, minimised, show, windows_of
back = [h for h in windows_of("chiaki.exe") if not minimised(h)]
if back:
@@ -797,7 +815,9 @@ def main() -> int:
s.hide()
if kind == "chiaki" and hasattr(src, "set_audio_delay"):
src.set_audio_delay(0) # chiaki-ng's sound back on time (it would also lapse once we stop)
if hidden:
if hidden and own_windows:
src.hide_windows(False)
elif hidden:
from framegen.winutil import SW_RESTORE, show
show(hidden, SW_RESTORE)
if replay is not None:
+353
View File
@@ -0,0 +1,353 @@
"""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)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(20):
x @ x
torch.cuda.synchronize()
tflops = 20 * 2 * 4096 ** 3 / (time.perf_counter() - t0) / 1e12
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()
try:
res["policy"] = os.sched_getscheduler(0)
except OSError:
res["policy"] = None
t = threading.Thread(target=go)
t.start()
t.join()
rr = res.get("policy") == getattr(os, "SCHED_RR", 2)
report("rt", "OK" if res.get("ok") and rr else "WARN",
"frame threads get real-time priority" if rr else "no real-time priority (install rtkit, or add yourself "
"to the realtime group)", ok=res.get("ok"), policy=res.get("policy"))
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())