185 lines
7.2 KiB
Python
185 lines
7.2 KiB
Python
"""What differs between Windows and Linux, in one place: folders, the clock the frame tap times frames with, and the
|
|
shared memory (and its wake-up) the frame tap lives in.
|
|
|
|
Windows behaves exactly as before this module existed (same folders, QueryPerformanceCounter, named file mappings
|
|
and events). Linux follows the XDG folder conventions, times with CLOCK_MONOTONIC (the clock time.perf_counter and
|
|
time.monotonic read there) and keeps the frame tap in POSIX shared memory (/dev/shm) with a futex to wake the reader.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import mmap
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
WINDOWS = sys.platform == "win32"
|
|
LINUX = sys.platform.startswith("linux")
|
|
|
|
|
|
# ---- folders ---------------------------------------------------------------------------------------------------
|
|
def _xdg(var: str, default: str) -> Path:
|
|
v = os.environ.get(var, "")
|
|
return Path(v) if os.path.isabs(v) else Path.home() / default # XDG: relative values are to be ignored
|
|
|
|
|
|
def config_dir() -> Path:
|
|
"""Settings, looks and their LUTs. Windows: %APPDATA%\\framegen (as before). Linux: $XDG_CONFIG_HOME/smoovplay."""
|
|
if WINDOWS:
|
|
return Path(os.environ.get("APPDATA", Path.home())) / "framegen"
|
|
if LINUX:
|
|
return _xdg("XDG_CONFIG_HOME", ".config") / "smoovplay"
|
|
return Path(os.environ.get("APPDATA", Path.home())) / "framegen"
|
|
|
|
|
|
def data_dir() -> Path:
|
|
"""Things the user keeps (session summaries, benchmark results). Windows: the same folder as the settings. Linux:
|
|
$XDG_DATA_HOME/smoovplay (~/.local/share/smoovplay)."""
|
|
if LINUX:
|
|
return _xdg("XDG_DATA_HOME", ".local/share") / "smoovplay"
|
|
return config_dir()
|
|
|
|
|
|
def cache_dir() -> Path:
|
|
"""Things that can be made again (instant replay's working files). Windows: the same folder as the settings, as
|
|
before. Linux: $XDG_CACHE_HOME/smoovplay."""
|
|
if LINUX:
|
|
return _xdg("XDG_CACHE_HOME", ".cache") / "smoovplay"
|
|
return config_dir()
|
|
|
|
|
|
def _xdg_user_dir(key: str) -> Path | None:
|
|
"""A folder from ~/.config/user-dirs.dirs (what xdg-user-dir reads), e.g. key "VIDEOS"; None if it isn't set."""
|
|
try:
|
|
text = (_xdg("XDG_CONFIG_HOME", ".config") / "user-dirs.dirs").read_text(encoding="utf-8")
|
|
except OSError:
|
|
return None
|
|
m = re.search(rf'^\s*XDG_{key}_DIR\s*=\s*"([^"]*)"', text, re.M)
|
|
if not m:
|
|
return None
|
|
path = m.group(1).replace("$HOME", str(Path.home()))
|
|
return Path(path) if os.path.isabs(path) and Path(path) != Path.home() else None
|
|
|
|
|
|
def videos_dir() -> Path:
|
|
"""The user's Videos folder: Windows' known folder, Linux's XDG_VIDEOS_DIR, else ~/Videos."""
|
|
if WINDOWS:
|
|
try:
|
|
import uuid
|
|
guid = (ctypes.c_ubyte * 16).from_buffer_copy(uuid.UUID("18989B1D-99B5-455B-841C-AB7C74E4DDFC").bytes_le)
|
|
ptr = ctypes.c_wchar_p()
|
|
if ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0, None, ctypes.byref(ptr)) == 0:
|
|
path = Path(ptr.value)
|
|
ctypes.windll.ole32.CoTaskMemFree(ptr)
|
|
return path
|
|
except Exception: # noqa: BLE001 - fall back to ~/Videos
|
|
pass
|
|
elif LINUX:
|
|
found = _xdg_user_dir("VIDEOS")
|
|
if found is not None:
|
|
return found
|
|
return Path.home() / "Videos"
|
|
|
|
|
|
# ---- the frame tap's clock ---------------------------------------------------------------------------------------
|
|
if WINDOWS:
|
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
|
|
def qpc() -> int:
|
|
"""Now, in qpc_freq() ticks: QueryPerformanceCounter, the clock time.perf_counter reads on Windows."""
|
|
v = ctypes.c_int64()
|
|
_k32.QueryPerformanceCounter(ctypes.byref(v))
|
|
return v.value
|
|
|
|
def qpc_freq() -> int:
|
|
v = ctypes.c_int64()
|
|
_k32.QueryPerformanceFrequency(ctypes.byref(v))
|
|
return v.value
|
|
else:
|
|
def qpc() -> int:
|
|
"""Now, in qpc_freq() ticks: CLOCK_MONOTONIC in nanoseconds, the clock time.perf_counter reads on Linux and
|
|
what frametap.c writes there."""
|
|
return time.monotonic_ns()
|
|
|
|
def qpc_freq() -> int:
|
|
return 1_000_000_000
|
|
|
|
|
|
# ---- the frame tap's shared memory -------------------------------------------------------------------------------
|
|
def shm_name(name: str) -> str:
|
|
"""A Windows shared-memory name as a POSIX one, the way frametap.c turns it (both must agree): "Local\\" or
|
|
"Global\\" dropped, other slashes made dashes. "Local\\chiaki-frametap" is /dev/shm/chiaki-frametap."""
|
|
for prefix in ("Local\\", "Global\\"):
|
|
if name.startswith(prefix):
|
|
name = name[len(prefix):]
|
|
break
|
|
name = name.replace("\\", "-").replace("/", "-")
|
|
if not name or name in (".", "..") or len(name) > 200:
|
|
raise ValueError(f"not a usable shared-memory name: {name!r}")
|
|
return name
|
|
|
|
|
|
SHM_DIR = Path("/dev/shm")
|
|
|
|
|
|
def shared_memory(name: str, size: int) -> mmap.mmap:
|
|
"""A shared mapping of at least `size` bytes that another process opening the same name sees. Either side may
|
|
create it first. Windows: a named file mapping (as before). Linux: /dev/shm/<shm_name(name)>, readable by this
|
|
user only."""
|
|
if WINDOWS:
|
|
return mmap.mmap(-1, size, tagname=name)
|
|
fd = os.open(SHM_DIR / shm_name(name), os.O_RDWR | os.O_CREAT, 0o600)
|
|
try:
|
|
if os.fstat(fd).st_size < size:
|
|
os.ftruncate(fd, size)
|
|
return mmap.mmap(fd, size, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE)
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def remove_shared_memory(name: str) -> None:
|
|
"""Linux: deletes the shared memory's file (Windows frees a mapping by itself once nobody has it open)."""
|
|
if not WINDOWS:
|
|
try:
|
|
(SHM_DIR / shm_name(name)).unlink()
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
|
|
# ---- the futex the Linux frame tap wakes its reader with ---------------------------------------------------------
|
|
_FUTEX_WAIT, _FUTEX_WAKE = 0, 1 # shared (not FUTEX_PRIVATE_FLAG): writer and reader are different processes
|
|
_SYS_FUTEX = {"x86_64": 202, "aarch64": 98}.get(os.uname().machine if hasattr(os, "uname") else "", None)
|
|
_libc = None
|
|
|
|
|
|
class _Timespec(ctypes.Structure):
|
|
_fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
|
|
|
|
|
|
def _syscall():
|
|
global _libc
|
|
if _libc is None:
|
|
_libc = ctypes.CDLL(None, use_errno=True)
|
|
_libc.syscall.restype = ctypes.c_long
|
|
return _libc.syscall
|
|
|
|
|
|
def futex_wait(addr: int, expected: int, timeout_s: float) -> None:
|
|
"""Sleeps until futex_wake on the u32 at addr, while it still holds `expected`, or timeout_s. Returns at once if it
|
|
no longer holds `expected`. Falls back to a short sleep where there's no futex."""
|
|
if _SYS_FUTEX is None:
|
|
time.sleep(min(timeout_s, 0.001))
|
|
return
|
|
ts = _Timespec(int(timeout_s), int((timeout_s % 1) * 1e9))
|
|
_syscall()(ctypes.c_long(_SYS_FUTEX), ctypes.c_void_p(addr), ctypes.c_int(_FUTEX_WAIT),
|
|
ctypes.c_uint32(expected & 0xFFFFFFFF), ctypes.byref(ts), None, ctypes.c_int(0))
|
|
|
|
|
|
def futex_wake(addr: int) -> None:
|
|
"""Wakes every futex_wait on the u32 at addr."""
|
|
if _SYS_FUTEX is not None:
|
|
_syscall()(ctypes.c_long(_SYS_FUTEX), ctypes.c_void_p(addr), ctypes.c_int(_FUTEX_WAKE),
|
|
ctypes.c_int(0x7FFFFFFF), None, None, ctypes.c_int(0))
|