Compare commits

..
Author SHA1 Message Date
spoopyghosty0 1989acd3a3 Google Daydream / Cardboard builds: detect and warn (GitHub #335)
Analysis extra.google_vr (ANALYSIS_VERSION 20): manifest DAYDREAM/CARDBOARD
categories, enableVrMode=com.google.vr.vrcore, libgvr.so / Cardboard SDK libs,
GVR Java classes, Unity vr-device-list (not libgvraudio.so, which Quest games
ship too). A build without Oculus support gets a warning (recipe notes, CLI,
game page); never unsupported from the manifest. Triage gvr-not-supported for
Unity's 'Google VR Error', the bridge's missing CardboardViewNativeImpl and
VrCore binds. PLAYBOOK row, tests.
2026-10-16 10:22:35 -04:00
spoopyghosty0 04faa0be65 Catalog: The Climb (works)
Closes #341
2026-10-16 09:39:49 -04:00
spoopyghosty0 1399d7c5a3 Catalog: Attack on Titan VR: Unbreakable works with its asset files (was Freedom, issues)
Closes #337
2026-10-16 09:36:24 -04:00
spoopyghosty0 fa5c5b32ce Catalog: Sclerosis (works)
Closes #339
2026-10-16 09:33:54 -04:00
spoopyghosty0 0228516a2a Catalog: 7 community recipes (Breathedge VR, Cities: VR, Lawn Mowing Simulator VR, Exploding Kittens VR, Lost Recipes, Neko Atsume Purrfect, Real VR Fishing)
Closes #347
Closes #345
Closes #344
Closes #343
Closes #340
Closes #338
Closes #333
2026-10-16 09:31:12 -04:00
spoopyghosty0 960da4469b Announcements: a one-time pop-up in the app
Source of truth: announcements/current.md on main (front matter: id, title,
date, optional image/button/expires; Markdown body), read from raw GitHub every
6 h like the catalog, so a push reaches users without a release. Ships
switched off (active: false).

Shown only to people who used FramePort before the announcement's date, never
on a first start; any close (X, click outside, Escape) dismisses that id for
good, and a new announcement = a new id. Centred over the content area, right
of the sidebar. announcements/README.md explains the file;
ui_smoke.py --announcement renders it.
2026-10-16 09:23:46 -04:00
spoopyghosty0 e9720f83d2 Catalog: Crisis Zone VR (works)
Closes #331
2026-10-16 00:14:17 -04:00
spoopyghosty0 729f77a9e3 Docs: update screenshots and videos 2026-10-16 00:08:46 -04:00
spoopyghosty0 4824b30e94 Catalog: Vermillion works (confirmed in the headset, #200) 2026-10-15 23:54:32 -04:00
spoopyghosty0 39e1762e53 Game menu: Update with a newer version… for Linux apps and PC VR games (#161)
Follow-up to "Update with a newer APK…": Linux apps take their new AppImage/archive or folder (a file or a folder
picker, like the app was added), PC VR games their new game folder. pipeline.replace_linux_app / replace_rift_game
re-run the add path (add_linux_app(replace=) / add_rift_game(replace=)): the entry keeps its package (so the Steam
shortcut), name, artwork, tags, switches and the user's recipe; a folder keeps the program chosen before if it's still
there, else FramePort picks again (and asks, for ambiguous PC VR games). A name that looks like another app's is
allowed with a heads-up.

The entry gets a new source_id, recorded in the deployment's recipe at install (no agent change):
components.source_replaced shows the Frame copy (and a PC install, pc_outdated) as outdated until then. Such an
install also re-sends same-size files changed after the last install (installer.changed_since), since uploads
otherwise skip files the Frame has with the same size. The old PC VR folder is left out of later scans
(replaced_dirs). CLI: frameport new-version <game> <path> (APKs too). Docs: INSTALL.md.
2026-10-15 20:10:50 -04:00
spoopyghosty0 3d260dccb1 OpenSSH uploads log in like the Frame connection; SSH key files in Settings (#242)
A Frame that only authorizes the user's own key refused OpenSSH, which
offered FramePort's keys alone (IdentitiesOnly), so every upload fell back
to Paramiko. The connection now records which login worked (Frame.auth):
after a login with this PC's own keys/agent OpenSSH also offers private
copies of ~/.ssh/id_* (OpenSSH skips its defaults once -i is given) and the
agent; a refused strict login is retried that way once. FramePort doesn't
add its key to the Frame for this.

New: Settings > Installing > SSH keys (library ssh.extra_keys, CLI
frameport frame ssh-keys): extra private key files for the connection and
OpenSSH, checked with Paramiko (passphrase keys: use the agent). OpenSSH
runs with -v and a refused login's error lists the keys offered and its
warnings. whoami's SID is read from bytes (non-ASCII user names).
Checked with Windows ssh.exe/sftp.exe against the Frame.
2026-10-15 19:58:58 -04:00
spoopyghosty0 26a34ddadb OpenSSH uploads: don't escape glob characters inside sftp's quotes (#324)
sftp escapes * ? [ inside double quotes itself, so FramePort's extra
backslash became part of the path: a folder named "... [ENG] ..." failed
every OpenSSH upload (on Linux too) and fell back to Paramiko. On Windows
the local path now goes with forward slashes: Win32-OpenSSH turned every
backslash, escapes included, into '/' ("C://Users", "/[ENG]").
Checked with Windows sftp.exe and Linux sftp against the Frame (put and
reput, sha256 match).
2026-10-15 19:58:57 -04:00
spoopyghosty0 939845d379 Catalog: Clockwork is The Last Clockwinder (Meta's store name; reported in #110) 2026-10-15 19:51:45 -04:00
spoopyghosty0 35eb12df08 CLAUDE.md: every triage sweeps for unanswered comments (closed issues, PRs, discussion replies) 2026-10-15 19:41:32 -04:00
spoopyghosty0 570a98b91a Triage: meta-entitlement for Quest games; catalog: Deadly Delivery unsupported (#322)
Deadly Delivery 1.0.30 renders (72 fps), then its lobby's Meta entitlement check
fails four times and it quits. The oculus-entitlement signature is PC VR only,
so the Quest log had no finding. New Quest signature meta-entitlement (error:
offline games may log it and play on; an online game's exit fails the test).
FramePort doesn't get around entitlement checks. docs/GAMES.md regenerated
(it was also behind on other catalog entries).
2026-10-15 19:34:51 -04:00
spoopyghosty0 f2f92cce70 Catalog: NEX Player typing verified in the headset (keyboard opened by hand) 2026-10-15 19:07:48 -04:00
spoopyghosty0 dd74c17212 Heuristics eval: docs for the dated score, CLAUDE.md notes, ratchet floors from the final run 2026-10-15 19:07:47 -04:00
spoopyghosty0 5647e266bd Catalog: Unity text-input fix for 17 recipes verified before it existed (from detection, not headset-verified) 2026-10-15 19:07:46 -04:00
spoopyghosty0 a5a86e591d eval_heuristics: adapter/device picks a catalog recipe inherits aren't errors in the dated score 2026-10-15 19:07:45 -04:00
spoopyghosty0 7cd78cfa26 eval_heuristics: date-aware score (patches newer than the entry's verified date are catalog gaps, not errors); fit report dates by verified date 2026-10-15 19:07:44 -04:00
spoopyghosty0 e04edf3600 unity_oculus_check: keep suggesting it with the Oculus XR Plugin (holdout game com.coatsink.alone needs it) 2026-10-15 19:07:43 -04:00
spoopyghosty0 c98aad5056 Use built-in Oculus evidence for adapter pose timing suggestions 2026-10-15 19:07:41 -04:00
spoopyghosty0 ae228ea4ea Refine Unity heuristics for IL2CPP support, XR routing and thread keys 2026-10-15 19:07:40 -04:00
spoopyghosty0 0599e55831 eval_heuristics: catalog truth goes through the 32-bit bridge / 2D-app transforms like suggest(); floors from the full snapshot 2026-10-15 19:07:39 -04:00
spoopyghosty0 2e83970ad5 Add catalog-only heuristics scoring and new patch fit reports 2026-10-15 19:07:38 -04:00
spoopyghosty0 33a778c195 scripts: heuristics_snapshot.py saves dump analyses as JSON for heuristics evals 2026-10-15 19:07:37 -04:00
134 changed files with 3744 additions and 9954 deletions

No files matched your search

+2
View File
@@ -19,6 +19,8 @@ CLAUDE.local.md
# outputs of `frameport report` / `parity` / ruff
REPORT.md
.ruff_cache/
.eval-home/
.eval-results/
.claude/worktrees/
# project page (site/)
+39 -58
View File
@@ -223,6 +223,13 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
store matches and links then only update `auto_title`; a locked name gets no twin suffix); `sync_title` → Frame
agent v77 `rename` (deployment.json title, same shortcut appid: upsert matches by Exe) + art + one Steam restart, PC
`PcReviveTarget.rename`; an unreachable Frame → `steam_name_stale` (game page "Update name on Frame", next install).
- Newer versions (GitHub #161): game menu "Update with a newer APK…" (`pipeline.replace_apk`, outdated via
`build.source_version`) and, for Linux apps / PC VR games, "Update with a newer version…" (`replace_linux_app` /
`replace_rift_game` via `add_linux_app(replace=)` / `add_rift_game(replace=)`, CLI `frameport new-version`): the
entry keeps package, name, art, tags, switches, user recipe (a confirmed exe if the new folder has it); a new
`source_id` goes into the deployment's `recipe` dict at install (no agent change) → `C.source_replaced` = outdated
(Frame + `pc_outdated`); such an install re-sends same-size files changed after the last install (mtime/ctime,
`installer.changed_since`); the old Rift folder is in `replaced_dirs` (rescans skip it). Untested on the device.
- `Recipe.as_is` = install unchanged (pre-patched libraries): `pipeline.prepare_as_is`; auto for APKs that already
contain FrameBridge (`frame_patched`). For Rift it changes nothing (the dump is never modified; the Frame copy
still gets launch fixes like the crash-reporter rename — `-nocrashreports` alone doesn't stop UE 4.23) — it does
@@ -267,6 +274,15 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
`working-config.yml` issue → maintainer label `catalog-accepted` (a plain issue needs `working-config` added by
hand) → `catalog-from-issue.yml` workflow (`scripts/catalog_from_issue.py` validates) opens a catalog PR. App log:
`core/applog.py` (`<data>/logs/app.log`, finished GUI jobs in `<data>/logs/jobs/`).
- Announcements (2026-10-15, announcements/README.md; app only, the owner dropped the site pop-up): source of
truth `announcements/current.md` on `main` (front matter id/title/date + optional image/image_alt/button+url/
expires/active, Markdown body; ships `active: false`). `announcements.py` (no Flet; raw GitHub via
`cache.cached_text`, 6 h) + `ui/announcer.py` (pop-up 20 s after start / every 6 h when no dialog is open and not
on welcome; `C.dialog` with the portal edge, image downloaded + Pillow-checked into `<data>/announcements/`, shown
by asset URL). Shown only if the user was around before `date` (setting `announce.since`, set once at the GUI's
first start: 0 when `USED_BEFORE` settings exist, else now), once: any close (X, outside click, Escape, button)
stores the id (`announce.dismissed`, last 50). New announcement = new id; same id = typo fix.
`FRAMEPORT_NO_ANNOUNCEMENTS`; `ui_smoke.py --announcement` renders it.
- Self-update (docs/ARCHITECTURE.md "Self-update", docs/INSTALL.md "Updating"): `_version.py` = the only version
(`frameport.__version__`; pyproject reads it via hatch `dynamic`; app log, diagnostics, User-Agent, Settings use
it — never `importlib.metadata`, bundles have no dist-info). `updates.py` (no Flet): `check()` = GitHub
@@ -548,61 +564,6 @@ maps a symlink to the already-loaded module) gets past it to **-3021 = ovrError_
an Oculus-signed runtime. Next step (not done): make the runtime check pass without Detours, e.g. an injected helper
that patches the game's import table (IAT) for LoadLibrary*/WinVerifyTrust, or a prefix-level override. This is
runtime interop (what Revive does), not the Platform SDK licence check (which FramePort never touches).
**Rift via x86_64 Wine under FEX (research, 2026-10-08, headless on the dev Frame, SteamOS 0.4.5; no product code):**
why Revive failed is confirmed upstream: x64 Detours returns ERROR_NOT_SUPPORTED on ARM64EC targets (microsoft/Detours
PR #388; only an ARM64EC build of Detours can hook them). A fully x86_64 Wine avoids it: GE-Proton11-7 **x86_64** runs
under the FEX tool (`fex-compat-tool run -- <x86 binary>`; RootFS /usr/share/guestos/fex-mesa, no FreeType there)
— prefix boot 35 s, kernelbase.dll is x86-64. Proton's script needs help without the x86_64 SLR (app 4183110, not
installed): its Python runs natively (the RootFS has none), so `files/bin/wine{,server}` and the two direct
`wine-preloader` argv calls must go through a FEX wrapper that also unsets `FEX_APP_CONFIG(_LOCATION)` (Proton sets
them on aarch64 for its own ARM64EC FEX → "RootFS path set to ''"); GE's game drive needs STEAM_COMPAT_INSTALL_PATH
unset. SteamVR now ships `bin/linux64/vrclient.so` + `bin/vrclient.so` (i386) + `vrclient_x64.dll` (Oct 6 build; not
there on 09-30): Proton's x86_64 vrclient bridge reaches the arm64 vrserver. **Rick and Morty ran as the scene app**
("OpenVR initialized!", controller tracking, 9176 presents / 6 dropped, CPU 11.6 / GPU 17.9 ms, target 72).
**ReviveInjector: "Succesfully injected!"**, LibRevive64.dll loaded next to OVRPlugin.dll in Lies Beneath, which then
died on 0xc06d007e = delay-loaded `libovrplatform64_1.dll` (Platform SDK) before connecting to SteamVR — so Revive's
signature hook and Revive→SteamVR are still unproven. Every Rift game in the library except Rick and Morty uses the
Platform SDK → the Meta (Link) app in the prefix, logged in with the user's own account, is the real blocker; the
only public attempt (github.com/michauMiau/oculus-wine-linux, 2026-10) never got OculusSetup.exe (32-bit .NET)
past its HTTPS config fetch. Scratch files on the Frame: `~/frameport-rifttest/` (scripts t1-t4.sh).
Meta runtime in the same Wine (2026-10-09): Platform SDK games reach OVRServer's IPC on the Frame. The apparent
intermittent handshake hang was **OVRLibrarian.exe** (.NET, Wine Mono): under FEX it finishes its work but never exits,
its AppTracker entry stays, and the runtime then tracks no later client (Meta app, game), so the game waits forever
for the reply event the runtime only sets after identifying it (found with wineserver `+server` traces PC vs Frame).
Ending OVRLibrarian before the game → game tracked, "Missing entitlement" exactly as on the PC (needs a login).
Logged in (2026-10-09, owner's own account, browser sign-in; the `oculus://` answer had to be forwarded into the Wine
app's `\\.\pipe\oculus`), the runtime also needed a WinRT `Windows.Devices.WiFi.WiFiAdapter` stand-in (Air Link code
fail-fasts without it), Wine's DeviceWatcher add/remove_Updated/Removed implemented, and the C: volume name
(`\\?\Volume{...0043}`) linked in dosdevices. Copying the logged-in `sessions/` + CoreData to the Frame prefix kept the
login. **Oculus First Contact then ran in VR on the Frame** (Revive in OpenVR mode; `/openxr` failed in wineopenxr):
scene app at 72 Hz target, but 92 % of frames "timed out" (game CPU-bound under FEX) → stutter/flicker/lag.
Performance (2026-10-10, headless with patched Revive visibility + SteamVR `pauseCompositorOnStandby=false`, numbers from
`IVRCompositor::GetFrameTimings`): the frame loop waited on sync round trips through the FEX-run x86_64 wineserver.
`native/fexwine/`: a **native aarch64 wineserver** built from GE's exact source (protocol 938) + **ntsync** (works once
OVRLibrarian is ended) took hitches 17 → 0-4 per 20 s. The rest were Unreal's large-block allocator committing,
filling (one `rep stos`) and freeing 514 MB every 1-8 s: ~130k 4 KB page faults each under FEX. `fp_mem.so`
(`FP_BIGCACHE_MB=256`, guest preload via `FEX_ENV=LD_PRELOAD=…`: fex-compat-tool deletes LD_PRELOAD) keeps that block
→ 0 hitches, steady 36 fps + motion smoothing, ~5.5 % timed out. 72 fps would need ~30 % less GPU (game ~55 % busy
at 36 fps); THP (fragmentation), MSAA off, Turnip gmem don't help. Also needed: Unreal's
`Slate.DeferWindowsMessageProcessing` = 0 (exe patch; the default deadlocks Wine's IME window ~1/3 of starts).
Headset (owner, 2026-10-10): with motion smoothing off for the game (SteamVR per-app `motionSmoothingOverride=2`:
smoothing cost ~15 % GPU) "much much better", 95 % of frames new at 72 Hz; MSAA off (DXVK `d3d11.disableMsaa`, -25 %
GPU) helped but the owner misses smooth edges → the game's MSAA CVar is `r.MobileMSAA` (Oculus' clustered-forward
branch; no r.MSAACount in the exe), 2x untested. Headless tests need the headset worn once per boot (else "IMU
fallback" and the game waits at startup forever).
**Experimental mode on branch `rift-on-frame` (the owner's single linkable branch for this work):** CLI only,
`FRAMEPORT_EXPERIMENTAL_FEX=1 frameport fex setup | import-login <signed-in PC prefix> [--app <meta name>] | install
[<meta name>] [--msaa N] [--force-unverified] | status` (hidden group). Generic per game: exe + arguments from Meta's
manifest (`Software/Manifests/<app>.json` launchFile/launchParameters), the Unreal IME-deadlock fix found in the binaries
(`find_ime_patch`: the CVar's UTF-16 name → its `lea` xref → `lea r8` member/global → `mov [reg+disp],1` / int 1;
also modular ApplicationCore/Slate DLLs), `static_checks` (engine, imported graphics DLLs: monolithic Unreal imports
every RHI, so it can't tell which runs). `agent/fexrift.py` `GAMES` = verified games + per-game opt-ins only (fp_mem's
unzeroed big-block cache, `msaa_ini`); others need `--force-unverified`. PC `src/frameport/fexrift.py` uploads `agent/fexrift.py` + `artifacts/fexrift`
(sources native/fexwine) + Revive 3.2.0 with 6 byte patches (refused for other builds); the Frame helper downloads
GE-Proton11-7 x86_64 (SHA-512), x86 GnuTLS (Arch archive), installs Meta's runtime (Meta's signature checks kept) and
writes the game's launcher. Agent v79 `fex_prepare/status/setup/import_login/install`, kind `frame_fex` (uninstall
keeps the shared prefix; launch tests refused). Everything under `~/.local/share/frameport/fexrift` (purge removes it,
login tokens included). Not yet run end to end on the device; the login still comes from a PC prefix signed in by hand.
Uninstall (Quest, saves kept) used to leave `deployment.json` → still "installed"; fixed (agent v16).
**Discovery/network:** Developer-Mode SteamOS devices announce `_steamos-devkit._tcp` (TXT `login=steamos`) — use it;
@@ -959,6 +920,13 @@ hide_space_warp / vk_hide_fdm / no Valve layers; FNAF HW (#135) "freeze" = first
on Zink (threads busy in zink/disk cache), not a hang; VR4 (#199) reporter's patch.203 OBB truncated. Upload benchmark
(`scripts/upload_bench.py`, #242): home Wi-Fi caps every method at ~11 MB/s; paramiko uses ~3x OpenSSH's CPU; Windows
OpenSSH refuses FramePort's key file (ACL "bad permissions") until its permissions are tightened.
**OpenSSH uploads (2026-10-15, #324/#242):** sftp escapes `* ? [` inside double quotes itself (and undoes it for
put's destination), so `native_upload.quote` escapes only `\\`/`"`; Win32 sftp turns every local backslash into `/`
(escapes too) → local paths go as `C:/…`. Logins: `Frame.auth` = the attempt that worked (app_key / user_key = a key
file from Settings → Installing → SSH keys, library `ssh.extra_keys`, CLI `frame ssh-keys` / agent / password).
OpenSSH strict (FramePort + Settings keys, IdentitiesOnly) unless auth was "agent"; a refused strict login retries
relaxed (+ private copies of ~/.ssh/id_{rsa,dsa,ecdsa,ed25519}: OpenSSH skips its defaults once any -i is given, + the
agent); `-v` key lines go into the error. FramePort doesn't add its key to the Frame for this. Windows-tested.
**Meta user id (GitHub #182, 2026-10-11):** OVRPort's platform loader (runtimes 3.4.3-23204ea and -aa54c3f) answers
`ovr_GetLoggedInUserID` (and two other callers) without a Meta account with a made-up id from a helper (`stp; mov x29,
sp; bl random; …; mov/movk x9 = 0x53444835ec580000 (6e18); add x0, x8, x9; ldp; ret`), kept only in memory → a new id
@@ -1110,6 +1078,13 @@ GitHub identity + credentials are maintainer-local (`CLAUDE.local.md`): check `g
GitHub write. **The owner approves before posting, labelling or closing anything.** Reply style: "I"/neutral, never
we/our/us; never mention agent version numbers or internal tool versions; show the owner every draft in full with a
short recap of the thread so far; read **all** comments on a thread first (a later one often has the zip or the answer).
- **Every triage also sweeps for unanswered comments**, not just new threads: open AND recently closed issues, PRs
(incl. merged/closed ones) and discussions (top-level comments and their replies) whose latest comment isn't the
maintainer's, plus earlier user comments a later maintainer reply skipped. Users often ask follow-ups after a fix or
after closing (#294: two questions after the reporter closed it; #249: a Q&A discussion with no reply for days;
#161/#110: requests posted after the close). Quick check: `gh issue list --state all --search "updated:>=<date>"
--json number,comments --jq '.[] | select(.comments[-1].author.login != "spoopyghosty0")'`; discussions via GraphQL
(`discussions(orderBy:UPDATED_AT)` with `comments{replies}`).
- **Issue templates & labels** (`.github/ISSUE_TEMPLATE/`): `[Game report]` → `game-compatibility` (a game that
doesn't work right); `[Working recipe]` (`working-config.yml`) → `working-config` (a headset-verified config to add);
`[App]` → `bug` (FramePort itself). Mislabel/relabel to match.
@@ -1155,9 +1130,15 @@ MR-only (PASSTHROUGH required + BOUNDARYLESS_APP) → force_passthrough, + USE_S
hand tracking required → controller_fix=0; OVRPlugin + ≥20 GiB → disable_space_warp; Unreal ≤4.21 or Unreal Meta XR
Audio → nodebug; Oculus-OS class referenced by the Unreal audio build or ≥2 Meta libs → oculusos; legacy-VrApi Unity
GLES with MSAA → unity_no_msaa; CryEngine → user.cfg r_variable_rate_shading=0; direct VrApi → bridge (+GL shim for
GLAD/GLES); Unreal → alternate no-ForceQuit build. Score changes with
`python scripts/eval_heuristics.py "<dumps>"` (catalog off vs verified recipes; currently 33/34 exact — Phantom's
"use the no-ForceQuit build" is only detectable at runtime via triage). Add a rule → re-run the eval + `pytest -m games`.
GLAD/GLES); Unreal → alternate no-ForceQuit build. Scoring (docs/HEURISTICS_EVAL.md, 2026-10-15): analyse the dumps
once (`scripts/heuristics_snapshot.py <out.json> "<VR CyberDeck Portable>" "<PATCHED>"`, ~30 min, keep out of git),
then `scripts/eval_heuristics.py --snapshot <out.json> --split dev|holdout|all [--fit-report]` (catalog-only truth,
per-patch precision/recall, a fixed 20% holdout to catch rules fitted to one game). Read the **dated** score: an
"extra" on an entry verified before the patch existed is a catalog gap, and adapter/device picks are inherited by
catalog recipes anyway. 2026-10-15: strict 5/65 exact, F1 73.8%; dated 39/65, F1 88.6%; remaining misses are
one-game runtime fixes. Don't key a rule on one game's code fingerprint (an Unreal splash/depth "detect" matching
only Star Wars Tales + FNAF HW was rejected: it would also have bumped ANALYSIS_VERSION for every user). Add a rule →
re-run dev + holdout + `pytest -m games`.
## Frame operations
- Find/connect: `frameport frame discover` / `frame info` (the remembered Frame is in `<user data>/frames.json`).
-1327
View File
File diff suppressed because it is too large. Load diff
-221
View File
@@ -1,221 +0,0 @@
"""Data-driven FEX game compatibility. No entitlement/runtime-signature changes; stdlib only on the Frame."""
import hashlib
import os
import re
import shlex
import struct
STATUSES = {"verified", "likely", "untested", "blocked"}
GRAPHICS = {"d3d11", "d3d9", "d3d12", "opengl", "vulkan"}
def exe_facts(path):
"""Read just the PE headers. A 32-bit client still needs GE's WoW64 and a working 32-bit VR/graphics bridge."""
try:
with open(path, "rb") as f:
head = f.read(64)
if head[:2] != b"MZ" or len(head) < 64:
return {}
f.seek(struct.unpack_from("<I", head, 0x3c)[0])
pe = f.read(26)
if len(pe) < 26 or pe[:4] != b"PE\0\0":
return {}
machine = struct.unpack_from("<H", pe, 4)[0]
return {"exe_32bit": machine == 0x14c, "exe_machine": hex(machine)}
except (OSError, struct.error):
return {}
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def match_profile(games, app, path):
"""Exact canonical name OR SHA-256 OR (exe basename AND byte size). No fuzzy title matches: different store
builds can need different routes. Multiple matches are refused rather than silently picking one."""
hits, digest = [], None
for key, profile in games.items():
match = profile.get("match", {"canonical_names": [key]})
hit = app in match.get("canonical_names", [])
if not hit and path and os.path.isfile(path):
hit = any(os.path.basename(path).lower() == e["name"].lower() and os.path.getsize(path) == e["size"]
for e in match.get("executables", []))
if not hit and match.get("sha256"):
digest = digest or sha256(path)
hit = digest in match["sha256"]
if hit:
hits.append((key, profile))
if len(hits) > 1:
raise ValueError("ambiguous FEX compatibility profiles: " + ", ".join(k for k, _ in hits))
return hits[0] if hits else (None, None)
def graphics_lines(route):
if route not in GRAPHICS:
raise ValueError(f"unknown FEX graphics route: {route}")
# Proton owns DLL selection/copying: DXVK for D3D9/11, vkd3d-proton for D3D12. Do not override DLLs or copy
# anything into the game. Clearing inherited flags also keeps a prior game's wined3d choice from leaking in.
lines = ["unset PROTON_USE_WINED3D PROTON_NO_D3D12 PROTON_NO_D3D11"]
if route == "opengl":
lines.append("export PROTON_USE_WINED3D=1")
lines.append(f"echo 'FramePort FEX: graphics={route}'")
return lines
# Which VR runtimes a build can use, from its files (after RiftLift's detection.py, MIT). Over-reporting LibOVR or
# the Platform SDK is safe (the game keeps Meta's runtime + Revive); only a build with neither leaves that route.
LIBOVR_FILES = {"libovrrt64_1.dll", "libovrrt32_1.dll", "ovrplugin.dll", "oculusxrplugin.dll"}
PLATFORM_FILES = {"libovrplatform64_1.dll", "libovrplatform32_1.dll", "pnsovr.dll"}
LIBOVR_MARKERS = (b"libovrrt", "libovrrt".encode("utf-16-le")) # LibOVR shim's runtime name (static or
PLATFORM_MARKERS = (b"libovrplatform", "libovrplatform".encode("utf-16-le")) # format string), Platform SDK imports
# arguments that already pick a VR mode/runtime: Unreal (-vr, -hmd=, ...) and Unity (-vrmode <name>)
VR_SELECTORS = ("-vr", "-nohmd", "-emulatestereo", "-openvr", "-steamvr", "-openxr", "-oculus", "-vrmode")
def _contains(path, needles):
"""Case-insensitive search of a file in 16 MiB chunks (the exe can be ~100 MB)."""
keep = max(map(len, needles)) - 1
tail = b""
try:
with open(path, "rb") as f:
while chunk := f.read(16 << 20):
block = (tail + chunk).lower()
if any(n in block for n in needles):
return True
tail = block[-keep:]
except OSError:
pass
return False
def oculus_facts(game_dir, exe):
"""{libovr, platform_sdk, openvr, unity}: file names in the game's folder tree + markers in the exe."""
names = set()
for _root, dirs, files in os.walk(game_dir or os.path.dirname(exe)):
dirs[:] = [d for d in dirs if not d.startswith(".")]
names.update(n.lower() for n in files)
folder = os.path.dirname(exe)
unity = os.path.isfile(os.path.join(folder, "UnityPlayer.dll")) or \
os.path.isdir(os.path.splitext(exe)[0] + "_Data")
return {
# modular Unreal ships the plugins as DLLs (*-OculusHMD-*, *-OnlineSubsystemOculus-*)
"libovr": bool(names & LIBOVR_FILES) or any("oculushmd" in n for n in names) or
_contains(exe, LIBOVR_MARKERS),
"platform_sdk": bool(names & PLATFORM_FILES) or any("onlinesubsystemoculus" in n for n in names) or
_contains(exe, PLATFORM_MARKERS),
"openvr": "openvr_api.dll" in names,
"unity": unity,
}
def vr_route(facts):
""""revive" (Meta's runtime + Revive, the proven route) or "openvr" (straight to SteamVR, nothing of Meta's):
only builds without the Platform SDK that carry OpenVR and either no LibOVR or Unity's per-launch VR choice."""
if facts["platform_sdk"] or not facts["openvr"]:
return "revive"
return "openvr" if not facts["libovr"] or facts["unity"] else "revive"
def vr_args(engine, route, args):
"""Arguments that make the engine use the route's runtime (after RiftLift's oculus_launch_arguments), unless
the arguments already choose one: Unity dual builds take -vrmode OpenVR, Unreal on Revive gets -vr."""
low = [a.lower() for a in args]
if any(a in VR_SELECTORS or a.startswith("-hmd=") for a in low):
return []
if engine == "unity" and route == "openvr":
return ["-vrmode", "OpenVR"]
if engine == "unreal" and route == "revive":
return ["-vr"]
return []
def register(core):
original_find = core.find_ime_target
def find_ime_target(bins):
# Before ApplicationCore was split out, FWindowsApplication (including its deferral CVar) lived in Core.
# Robo Recall's modular UE4 build has the SAME CVar and constructor instruction there. Search that module
# with the existing anchored finder; never infer a member offset from bAllowedToDeferMessageProcessing.
extra = []
for folder in sorted({os.path.dirname(b) for b in bins}):
extra += [os.path.join(folder, n) for n in sorted(os.listdir(folder))
if re.search(r"(?:^|-)core(?:-win(?:32|64)-shipping)?\.dll$", n, re.I)]
return original_find(list(dict.fromkeys(list(bins) + extra)))
def game_info(app, info):
path = os.path.join(info.get("game_dir") or os.path.join(core.META_DIR, "Software", "Software", app),
info.get("exe", ""))
key, profile = match_profile(core.GAMES, app, path)
if profile is None:
return
status = profile.get("status", "verified") # backward compatible with First Contact's original data
if status not in STATUSES:
raise ValueError(f"invalid FEX profile status: {status}")
if "args" in profile:
info.pop("args_argv", None) # profile args are shell fragments like the legacy entries
info.update({k: v for k, v in profile.items() if k != "match"})
info.update(profile=key, status=status)
def install_info(app, info, result):
"""Route and VR arguments from the build's files. A profile's explicit revive/meta_runtime/args win, and a
verified profile keeps exactly the launch it was verified with."""
facts = oculus_facts(result.get("game_dir"), result["exe"])
engine = "unity" if facts["unity"] else result["checks"].get("engine")
explicit = "revive" in info or "meta_runtime" in info
route = ("revive" if info.get("revive", True) else "openvr") if explicit or result["verified"] \
else vr_route(facts)
info.setdefault("revive", route == "revive")
# without Revive, Meta's runtime only matters to the Platform SDK
info.setdefault("meta_runtime", info["revive"] or facts["platform_sdk"])
added = []
if not result["verified"] and "args" not in (core.GAMES.get(info.get("profile")) or {}) and \
info.get("vr_args") != "off":
added = vr_args(engine, route, info.get("args", []))
info["args"] = list(info.get("args", [])) + added
return {"vr": dict(facts, route=route, meta_runtime=info["meta_runtime"], added_args=added)}
def launcher_env(app, info):
lines = graphics_lines(info.get("graphics", "d3d11"))
if info.get("fp_mem") == "enabled":
if info.get("status") != "verified":
raise ValueError("fp_mem requires a verified per-game opt-in")
lines.append("export FP_MEM=1")
lines.append("export FP_BIGCACHE_MB=" + str(int(info.get("bigcache_mb", 256))))
# candidate is informational: never enable the unzeroed cache merely because the engine uses Binned2.
for k, v in info.get("env", {}).items():
if not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", k) or not isinstance(v, str):
raise ValueError("invalid FEX profile environment")
# with the perf extension loaded, perf_prepare writes the game's one dxvk.conf (profile lines + its settings)
if info.get("dxvk") and "perf_prepare" not in core.COMMANDS:
lines += ["printf '%s\\n' " + " ".join(shlex.quote(line) for line in info["dxvk"]) + ' > "$A/dxvk.conf"',
'export DXVK_CONFIG_FILE="$A/dxvk.conf"']
return lines
def checks(app, info, result):
facts = exe_facts(result["exe"])
facts.update(profile=info.get("profile"), profile_status=info.get("status", "untested"),
graphics=info.get("graphics", "d3d11"), fp_mem=info.get("fp_mem", "off"))
# frameport_agent forwards checks to the PC and deployment.json; top-level helper warnings aren't forwarded.
if result.get("warnings"):
facts["profile_warnings"] = result["warnings"]
if facts.get("exe_32bit"):
facts["wow64"] = "untested: requires GE WoW64, 32-bit graphics and SteamVR vrclient bridge under FEX"
if facts["graphics"] == "opengl":
facts["opengl"] = "untested: no FEX GL thunk configured; rootfs GL may use software rendering or Zink"
if facts["graphics"] == "d3d12":
# GE versions have used both split lib/lib64 and architecture-qualified Wine directories. Report what
# is actually installed; the Proton script remains responsible for selecting its own layout.
paths = [os.path.join(core.GE, "files", lib, "wine", "vkd3d-proton", tail, "d3d12.dll")
for lib in ("lib", "lib64") for tail in ("", "x86_64-windows", "i386-windows")]
facts["vkd3d_dlls"] = [os.path.relpath(p, core.GE) for p in paths if os.path.isfile(p)]
return facts
core.GAME_INFO_HOOKS.append(game_info)
core.INSTALL_INFO_HOOKS.append(install_info)
core.find_ime_target = find_ime_target
core.LAUNCHER_ENV_HOOKS.append(launcher_env)
core.INSTALL_CHECK_HOOKS.append(checks)
-396
View File
@@ -1,396 +0,0 @@
{
"_comment": [
"FEX compatibility profiles, loaded by fexrift.py and matched by fexrift_compat.py. No entitlement changes.",
"match: OR of canonical_names (exact Meta names), sha256 (list of exe hashes), executables (list of {name,size}, both required). Without match the key is the exact canonical name. Ambiguous matches are refused.",
"status: verified (headset checked), likely (static evidence; install with warning), untested (force_unverified required), blocked (refuse even force). graphics: d3d11|d3d9 (DXVK), d3d12 (vkd3d-proton), opengl (PROTON_USE_WINED3D), vulkan.",
"env: string-valued environment; args: optional launch arguments override (absent keeps manifest). dxvk: dxvk.conf lines written only to the launcher anchor. notes: evidence and first-launch checks. revive: false for direct OpenVR games, otherwise true. Without revive/meta_runtime the install picks the route from the build's files (fexrift_compat.vr_route). meta_runtime: false skips Meta's runtime (default: revive or the Platform SDK). vr_args: off keeps unverified games' arguments as they are (else Unreal gets -vr, Unity OpenVR routes -vrmode OpenVR).",
"ime_patch: optional fallback {rva,old,new}, RVA may be hex; generic finder always wins, including old modular Core.dll. Null means no fallback, never an exemption from IME checks.",
"fp_mem: off|candidate|enabled; candidate is informational and NEVER enables the unzeroed cache. enabled requires verified status. bigcache_mb: cache size when enabled, default 256. env FP_MEM is an explicit opt-in retained for First Contact.",
"exe is the verified First Contact fallback only; other profiles keep the Meta manifest launch path. msaa_ini allows --msaa for that verified game only."
],
"oculus-first-contact": {
"title": "Oculus First Contact",
"exe": "TouchNUX/Binaries/Win64/TouchNUX-Win64-Shipping.exe",
"args": [
"-gamemode=\"experienceonly\""
],
"ime_patch": {
"rva": "0x22a605",
"old": "c7862001000001000000",
"new": "c7862001000000000000"
},
"_env": "Unreal's large-block allocator gives 0.5-1.6 GB blocks back every few seconds and this game overwrites them completely: fp_mem keeps them (native/fexwine/fp_mem.c)",
"env": {
"FP_MEM": "1",
"FP_BIGCACHE_MB": "256"
},
"msaa_ini": true,
"status": "verified",
"graphics": "d3d11",
"fp_mem": "enabled",
"bigcache_mb": 256,
"notes": "Headset verified; r.MobileMSAA=2 prevented rendering. Other games remain unverified."
},
"arktika-1": {
"title": "Arktika 1",
"match": {
"executables": [
{
"name": "arktika1.exe",
"size": 20181504
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "graphics API unclear (?); custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; d3d11 is a trial default, not a detected API"
},
"asgards-wrath": {
"title": "Asgards Wrath",
"match": {
"executables": [
{
"name": "WrathGame-Win64-Shipping.exe",
"size": 63707648
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"brass-tactics": {
"title": "Brass Tactics",
"match": {
"executables": [
{
"name": "Brass-Win64-Shipping.exe",
"size": 52790272
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"chronos": {
"title": "Chronos",
"match": {
"executables": [
{
"name": "Chronos-Win64-Shipping.exe",
"size": 40722432
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": "off",
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "IME fix OFF: the generic finder matched member +0x100 in this UE 4.10 build and the patched game never submitted a frame; unpatched it renders (Frame headless 2026-10-16: 202 frames / 105 s, 1.9 fps while loading, headset not yet checked). Media Foundation videos need a playback test"
},
"defector": {
"title": "Defector",
"match": {
"executables": [
{
"name": "DFCTR.exe",
"size": 16204288
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
},
"hubris": {
"title": "Hubris",
"match": {
"executables": [
{
"name": "HubrisVR-Win64-Shipping.exe",
"size": 85706240
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenXR/OpenVR); Media Foundation videos need a playback test"
},
"lies-beneath": {
"title": "Lies Beneath",
"match": {
"executables": [
{
"name": "Kodiak-Win64-Shipping.exe",
"size": 63537664
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"lone-echo": {
"title": "Lone Echo",
"match": {
"executables": [
{
"name": "loneecho.exe",
"size": 22336512
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
},
"lone-echo-2": {
"title": "Lone Echo 2",
"match": {
"executables": [
{
"name": "loneecho2.exe",
"size": 33436160
}
]
},
"status": "untested",
"graphics": "d3d12",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "D3D12: needs vkd3d-proton on Turnip under FEX (untested); custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
},
"rick-and-morty-virtual-rick-ality": {
"title": "Rick and Morty - Virtual Rick-ality",
"match": {
"executables": [
{
"name": "RickAndMortyVR.exe",
"size": 21284352
}
]
},
"status": "untested",
"graphics": "opengl",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "OpenGL: no FEX GL thunk configured; rootfs GL renderer unverified; OpenVR directly, no Platform SDK; guest GL and speech WinRT need a device check",
"revive": false
},
"robo-recall": {
"title": "Robo Recall",
"match": {
"executables": [
{
"name": "RoboRecall-Win64-Shipping.exe",
"size": 198144
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR)"
},
"skydances-behemoth": {
"title": "Skydances BEHEMOTH",
"match": {
"executables": [
{
"name": "BHM-Win64-Shipping.exe",
"size": 144449024
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenXR); Media Foundation videos need a playback test"
},
"stormland": {
"title": "Stormland",
"match": {
"executables": [
{
"name": "Stormland.exe",
"size": 85195776
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; Media Foundation videos need a playback test"
},
"the-climb": {
"title": "The Climb",
"match": {
"executables": [
{
"name": "Climb.exe",
"size": 95534080
}
]
},
"status": "untested",
"graphics": "d3d9",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "D3D9: DXVK under FEX (untested); CryEngine engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; D3D9 preferred over imported GL; confirm the actual selected renderer"
},
"the-unspoken": {
"title": "The Unspoken",
"match": {
"executables": [
{
"name": "Unspoken.exe",
"size": 69496320
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; Media Foundation videos need a playback test"
},
"vader-immortal-episode-i": {
"title": "Vader Immortal - Episode I",
"match": {
"executables": [
{
"name": "WKND-Win64-Shipping.exe",
"size": 58100736
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR); Media Foundation videos need a playback test"
},
"vader-immortal-episode-ii": {
"title": "Vader Immortal - Episode II",
"match": {
"executables": [
{
"name": "WKND-Win64-Shipping.exe",
"size": 59464192
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR); Media Foundation videos need a playback test"
},
"vader-immortal-episode-iii": {
"title": "Vader Immortal - Episode III",
"match": {
"executables": [
{
"name": "WKND-Win64-Shipping.exe",
"size": 59814912
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"wilsons-heart": {
"title": "Wilsons Heart",
"match": {
"executables": [
{
"name": "WHVR.exe",
"size": 15379968
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
}
}
-367
View File
@@ -1,367 +0,0 @@
"""Local Rift copies in Meta libraries. Runs on the Frame, stdlib only; never touches entitlement or login data."""
import hashlib
import json
import os
import re
import shutil
import subprocess
import time
import uuid
import zlib
SEGMENT_SIZE = 10000000 # Meta's manifest format uses decimal 10 MB, not MiB
def canonical(value):
if not isinstance(value, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]+", value):
raise ValueError("invalid Meta canonical name")
return value
def relative(value):
if not isinstance(value, str):
raise ValueError("invalid relative game path")
value = value.replace("\\", "/")
if (not value or value.startswith("/") or any(p in ("", ".", "..") for p in value.split("/"))
or any(c in value for c in ':\x00\r\n')):
raise ValueError("game path escapes its folder")
return value
def skipped(name):
name = name.replace("\\", "/").rsplit("/", 1)[-1].lower()
return (name.endswith((".7z", ".ag")) or bool(re.search(r"\.7z\.0", name))
or name in ("data.bin", "agrepackinstaller.exe", "vd.bat"))
def confined(path, root):
"""Reject symlink components too: an upload or delete must never follow a game-controlled link."""
root, path = os.path.abspath(root), os.path.abspath(path)
if os.path.commonpath([path, root]) != root:
raise ValueError("path escapes the library")
cursor = path
while True:
if os.path.islink(cursor):
raise ValueError("symlink in local game path")
if cursor == root:
break
cursor = os.path.dirname(cursor)
if os.path.realpath(root) != root:
raise ValueError("symlink in library root")
return path
def hash_file(path):
total, segments = hashlib.sha256(), []
size = 0
with open(path, "rb") as f:
while True:
chunk = f.read(SEGMENT_SIZE)
if not chunk:
break
size += len(chunk)
total.update(chunk)
# The fixture's last element is the zlib-compressed length, not the uncompressed chunk size. The first
# element is an opaque Meta segment identifier: 0 explicitly means unknown for a local-only copy. These
# records register existing bytes; they are NOT a CDN download/repair recipe (device validation needed).
segments.append([0, hashlib.sha256(chunk).hexdigest(), len(zlib.compress(chunk))])
return {"sha256": total.hexdigest(), "size": size, "segmentSize": SEGMENT_SIZE, "segments": segments}
def register(core):
def record_path(app):
return os.path.join(core.ROOT, "local-games", canonical(app) + ".json")
def read_record(app):
return core.read_json(record_path(app)) or {}
def save_record(app, record):
os.makedirs(os.path.dirname(record_path(app)), exist_ok=True)
path = record_path(app)
with open(path + ".tmp", "w") as f:
json.dump(record, f, indent=1)
os.replace(path + ".tmp", path)
def layout(app, dest):
app = canonical(app)
if dest:
# The main agent validates this against list_drives / resolve_dest on EVERY command. No fallback when a
# drive disappears. Keep the physical game path simple while Meta sees its required Software/ layout.
if not os.path.isabs(dest) or not os.path.isdir(dest):
raise ValueError("destination drive is not mounted")
base = confined(os.path.join(dest, "FramePort", "fexrift-games"), dest)
library = confined(os.path.join(dest, "FramePort", "fexrift-library"), dest)
guid = str(uuid.uuid5(uuid.NAMESPACE_URL, "frameport-fex-library:" + dest))
else:
library = os.path.join(core.META_DIR, "Software")
base, guid = os.path.join(library, "Software"), core.LIBRARY_GUID
return {"game_dir": confined(os.path.join(base, app), base), "library": library,
"library_guid": guid, "dest": dest}
def validated_record(app):
rec = read_record(app)
if not rec:
raise ValueError("no local-copy upload reservation for this game")
expected = layout(app, rec.get("dest"))
if any(rec.get(k) != v for k, v in expected.items()):
raise ValueError("local-copy reservation has an invalid storage path")
return rec
def prepare(args):
app = canonical(args["app"])
package = args["package"]
files, seen = {}, set()
for name, st in args["files"].items():
rel = relative(name)
if skipped(rel) or rel.casefold() in seen:
raise ValueError("skipped or duplicate file in upload inventory")
if not isinstance(st["size"], int) or st["size"] < 0 or not isinstance(st["mtime_ns"], int):
raise ValueError("invalid source file stat")
seen.add(rel.casefold())
files[rel] = st
if not files:
raise ValueError("no game files to upload")
old = read_record(app)
dest = args.get("dest") or None
loc = layout(app, dest)
if old and (old.get("dest") != dest or old.get("package") != package):
raise ValueError("local copy already has another package or drive; uninstall it before changing either")
if not old and (os.path.exists(os.path.join(loc["library"], "Manifests", app + ".json"))
or os.path.exists(loc["game_dir"])):
raise ValueError("game already exists outside FramePort's local-copy installer")
existing = {}
for rel, st in files.items():
path = confined(os.path.join(loc["game_dir"], rel), loc["game_dir"])
confined(path + ".part", loc["game_dir"])
if old.get("files", {}).get(rel) != st:
# Delete completed bytes too: if this new attempt is cancelled before uploading them, the next
# prepare must not mistake the old same-size file for a completed transfer of the new source.
for stale in (path, path + ".part"):
if os.path.isfile(stale):
os.unlink(stale)
if (old.get("files", {}).get(rel) == st and os.path.isfile(path)
and os.path.getsize(path) == st["size"]):
existing[rel] = st["size"]
if old and set(old.get("files", {})) - set(files):
raise ValueError("source removed files since the last upload; uninstall the local copy before replacing it")
os.makedirs(loc["game_dir"], exist_ok=True)
st = os.statvfs(loc["game_dir"])
save_record(app, dict(old, **loc, app=app, package=package, files=files))
return dict(loc, existing=existing, free_bytes=st.f_bavail * st.f_frsize)
def registry_library(rec, remove=False):
guid, dest = rec["library_guid"], rec.get("dest")
key = rf"HKEY_CURRENT_USER\Software\Oculus VR, LLC\Oculus\Libraries\{guid}"
if remove:
text = f"Windows Registry Editor Version 5.00\r\n\r\n[-{key}]\r\n"
else:
if dest:
devices = os.path.join(core.PFX, "dosdevices")
os.makedirs(devices, exist_ok=True)
volume = os.path.join(devices, "volume{" + guid + "}")
if os.path.lexists(volume):
if not os.path.islink(volume) or os.path.realpath(volume) != dest:
raise ValueError("Wine volume mapping is already in use")
else:
os.symlink(dest, volume)
# Do not appropriate a user's drive letter. Reuse our mount mapping, else pick the first unused one.
letter = next((c for c in "defghijklmnopqrstuvwxy"
if os.path.islink(os.path.join(devices, c + ":"))
and os.path.realpath(os.path.join(devices, c + ":")) == dest), None)
if not letter:
letter = next((c for c in "defghijklmnopqrstuvwxy"
if not os.path.lexists(os.path.join(devices, c + ":"))), None)
if not letter:
raise ValueError("no free Wine drive letter")
os.symlink(dest, os.path.join(devices, letter + ":"))
rec["drive_letter"] = letter
original = letter.upper() + ":\\FramePort\\fexrift-library"
path = "\\\\?\\Volume{" + guid + "}\\FramePort\\fexrift-library"
else:
original = "C:\\Program Files\\Meta Horizon\\Software"
path = "\\\\?\\Volume{00000000-0000-0000-0000-000000000043}\\Program Files\\Meta Horizon\\Software"
text = "Windows Registry Editor Version 5.00\r\n\r\n"
if not dest:
text += (r"[HKEY_CURRENT_USER\Software\Oculus VR, LLC\Oculus\Libraries]" + "\r\n"
+ '"DefaultLibrary"=' + core.meta_reg_str(guid) + "\r\n\r\n")
text += (f"[{key}]\r\n" + '"OriginalPath"=' + core.meta_reg_str(original) + "\r\n"
+ '"Path"=' + core.meta_reg_str(path) + "\r\n")
reg = os.path.join(core.ROOT, "local-library.reg")
core.put_text(reg, text)
core.wine("regedit", "/S", core.winpath(reg), timeout=90)
def register_local(args):
app = canonical(args["app"])
rec = validated_record(app)
if args.get("package") != rec["package"]:
raise ValueError("upload belongs to another package")
exe = relative(args["exe"])
if exe not in rec["files"]:
raise ValueError("launch program is not an uploaded file")
app_id = args["app_id"]
if not isinstance(app_id, str) or not re.fullmatch(r"[1-9][0-9]*", app_id):
raise ValueError("invalid Meta app ID")
files = {}
for rel, st in rec["files"].items():
path = confined(os.path.join(rec["game_dir"], rel), rec["game_dir"])
if not os.path.isfile(path) or os.path.getsize(path) != st["size"]:
raise ValueError(f"upload incomplete: {rel}")
files[rel] = hash_file(path)
library = rec["library"]
os.makedirs(library, exist_ok=True)
if rec.get("dest"):
software = os.path.join(library, "Software")
target = os.path.dirname(rec["game_dir"])
if os.path.lexists(software):
if not os.path.islink(software) or os.path.realpath(software) != target:
raise ValueError("external Meta library Software path is already in use")
else:
os.symlink(target, software)
args_list = args.get("args") or []
if not isinstance(args_list, list) or any(not isinstance(a, str) or "\x00" in a for a in args_list):
raise ValueError("launch arguments must be strings")
# list2cmdline follows Windows argv quoting; Meta's own launchFile uses forward slashes. The local launcher
# keeps the original argv list in the reservation, avoiding POSIX reinterpretation of Windows quotes.
manifest = core.dawn_manifest({"packageType": "APP", "isCore": False, "appId": app_id,
"canonicalName": app, "launchFile": exe,
"launchParameters": subprocess.list2cmdline(args_list),
"launchParameters2D": "", "version": str(args.get("version") or "0.0.0"),
"versionCode": 1, "files": files})
# App fixtures serialize the manifest's derived properties before the package base properties. Match that
# order (core's runtime package writer uses base-first); both use the same defaults, CRLF and indentation.
first = ("parentCanonicalName", "files", "dlcs", "assetFiles")
manifest = {**{k: manifest[k] for k in first}, **{k: v for k, v in manifest.items() if k not in first}}
manifests = os.path.join(library, "Manifests")
os.makedirs(manifests, exist_ok=True)
for suffix, content in ((".json", manifest), (".json.mini", dict(manifest, files={
k: v for k, v in manifest["files"].items() if k.lower().endswith(".exe")}))):
path = os.path.join(manifests, app + suffix)
core.write_manifest(path + ".tmp", content)
os.replace(path + ".tmp", path)
registry_library(rec)
rec.update({k: args.get(k) for k in ("app_id", "app_id_source", "store_app_id", "skipped", "title")})
rec.update(source="local_copy", exe=exe, args=args_list, registered=True)
save_record(app, rec)
return local_info({"app": app})
def local_info(args):
rec = validated_record(args["app"])
return {k: rec.get(k) for k in ("source", "app_id", "app_id_source", "store_app_id", "skipped", "dest",
"package", "game_dir", "library_guid", "registered")}
def unregister_local(args):
app = canonical(args["app"])
rec = validated_record(app)
if args.get("package") != rec["package"]:
raise ValueError("local copy belongs to another package")
# Shared/default library stays. An external library is removed from the registry only after its last local
# game goes; other games, the Wine prefix, sign-in and save directories remain intact.
peers = [core.read_json(os.path.join(core.ROOT, "local-games", f)) or {}
for f in os.listdir(os.path.dirname(record_path(app))) if f.endswith(".json") and f != app + ".json"]
if rec.get("dest") and not any(p.get("library_guid") == rec["library_guid"] for p in peers):
registry_library(rec, remove=True)
if os.path.isdir(rec["game_dir"]):
shutil.rmtree(rec["game_dir"])
for suffix in (".json", ".json.mini"):
path = os.path.join(rec["library"], "Manifests", app + suffix)
if os.path.isfile(path):
os.unlink(path)
os.unlink(record_path(app))
return {"removed": True}
def runtime_state(args):
app = canonical(args["app"])
rec = validated_record(app) if read_record(app) else None
# Read only newly appended runtime log text. Never return log lines: runtime logs can contain account data.
logdir = os.path.join(core.USER_DIR, "AppData", "Local", "Oculus")
def logs():
return [os.path.join(logdir, n) for n in os.listdir(logdir)
if n.lower().endswith((".txt", ".log")) and any(
s in n.lower() for s in ("server", "service"))] if os.path.isdir(logdir) else []
offsets = {p: os.path.getsize(p) for p in logs()}
librarian = os.path.join(logdir, "OVRLibrarian.log")
lib_offset = os.path.getsize(librarian) if os.path.isfile(librarian) else 0
probe = subprocess.run(["pgrep", "-f", "[O]VRServer_x64.exe"], capture_output=True, timeout=5)
started, proc = probe.returncode != 0, None
end = time.monotonic() + 95 # leave room for wineserver's bounded cleanup, total <=120 s
state = "timeout"
try:
if started:
runtime = os.path.join(core.META_DIR, "Support", "oculus-runtime")
proc = subprocess.Popen([os.path.join(core.GEF, "files/bin/wine"), "./OVRServer_x64.exe"],
cwd=runtime, env=core.wine_env(), stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
while time.monotonic() < end:
if started and os.path.isfile(librarian):
with open(librarian, errors="replace") as f:
if os.path.getsize(librarian) < lib_offset:
lib_offset = 0
f.seek(lib_offset)
done = "invocation completed" in f.read(65536).lower()
lib_offset = f.tell()
if done:
subprocess.run(["pkill", "-9", "-f", "[O]VRLibrarian.exe"], capture_output=True, timeout=3)
for path in logs():
with open(path, errors="replace") as f:
off = offsets.get(path, 0)
f.seek(off if os.path.getsize(path) >= off else 0)
text = f.read(1 << 20)
offsets[path] = f.tell()
for line in text.splitlines():
if app not in line and (not rec or rec.get("app_id", "_") not in line):
continue
match = re.search(r"\bstate\s*:\s*(ready|install_available)\b", line, re.I)
if match:
state = match[1].lower()
# Meta's PackageManager lists every registered package at start ("Currently installed
# package: <name>, version code: N"); the "state:" line only comes later (app tracker / sign-in)
elif state == "timeout" and re.search(r"Currently installed package:\s*" + re.escape(app) + r"\s*,",
line):
state = "installed"
if state != "timeout" or (proc is not None and proc.poll() is not None):
break
time.sleep(1)
finally:
if started:
subprocess.run([os.path.join(core.GEF, "files/bin/wineserver"), "-k"], env=core.wine_env(),
capture_output=True, timeout=10)
if proc is not None:
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
return {"runtime_state": state, "reused_server": not started}
original_manifest = core.manifest_launch
original_info = core.game_info
def manifest_launch(app):
rec = read_record(app)
if not rec.get("registered"):
return original_manifest(app)
rec = validated_record(app)
manifest = core.read_json(os.path.join(rec["library"], "Manifests", app + ".json")) or {}
if not manifest.get("launchFile"):
raise ValueError("local-copy Meta manifest is missing; register the copy again")
return {"exe": relative(manifest["launchFile"]), "args": rec["args"], "title": rec["title"],
"game_dir": rec["game_dir"], "args_argv": True}
def game_info(app):
rec = read_record(app)
if not rec.get("registered"):
return original_info(app)
# the same profile rules as a game in Meta's library: a legacy entry (no "match") by name, else the
# compatibility hooks match the build; "verified" only from a verified profile
known = core.GAMES.get(app) or {}
legacy = app in core.GAMES and "match" not in known
info = dict(known) if legacy else {}
info.update(manifest_launch(app))
for hook in core.GAME_INFO_HOOKS:
hook(app, info)
return info, info.get("status", "verified" if legacy else "untested") == "verified"
core.manifest_launch = manifest_launch
core.game_info = game_info
core.COMMANDS.update(prepare_local=prepare, register_local=register_local, unregister_local=unregister_local,
local_info=local_info, runtime_state=runtime_state)
core.INSTALL_CHECK_HOOKS.append(lambda app, info, result: {"local_copy": True} if read_record(app) else {})
-400
View File
@@ -1,400 +0,0 @@
"""Meta's own browser sign-in, in the Frame's shared prefix. No credential files are read.
The broker is a separate, owner-only Unix socket process: native_sso URLs live only in its memory, never in a
status file, launcher, journal or argv sent over SSH. Helpers and Wine subprocesses have their output discarded.
"""
import base64
import json
import os
import re
import shlex
import signal
import socket
import subprocess
import sys
import time
import urllib.parse
from pathlib import Path
CORE = None
DESKTOP = "frameport-oculus.desktop"
REGKEY = r"HKCU\Software\Wine\WineBrowser"
MAX_URL = 65536
def folder():
return Path(CORE.ROOT) / "login"
def request(message):
with socket.socket(socket.AF_UNIX) as s:
s.settimeout(90)
s.connect(str(folder() / "broker.sock"))
s.sendall(json.dumps(message).encode())
s.shutdown(socket.SHUT_WR)
return json.loads(receive(s))
def receive(s):
data = bytearray()
while True:
part = s.recv(8192)
if not part:
return data.decode()
data.extend(part)
if len(data) > MAX_URL * 2:
raise ValueError("sign-in message too long")
def valid_url(url, callback=False):
if not isinstance(url, str) or len(url) > MAX_URL or any(ord(c) < 32 for c in url):
return False
try:
u = urllib.parse.urlsplit(url)
return (u.scheme, u.netloc, u.path) == (("oculus", "link", "/frl_login") if callback else
("https", "auth.meta.com", "/native_sso/confirm"))
except ValueError:
return False
def host_env():
env = dict(os.environ)
env.update(CORE.steam_display_env())
env.update(XDG_RUNTIME_DIR=f"/run/user/{os.getuid()}",
DBUS_SESSION_BUS_ADDRESS=f"unix:path=/run/user/{os.getuid()}/bus")
env.pop("LD_PRELOAD", None)
return env
def quiet(argv, **kw):
return subprocess.run(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60, **kw)
def wine_env():
env = CORE.wine_env({"ENABLE_GAMESCOPE_WSI": "0", "PROTON_NO_ZENITY": "1", "PROTONFIXES_DISABLE": "1",
"STEAM_COMPAT_CLIENT_INSTALL_PATH": CORE.STEAM})
env.pop("LD_PRELOAD", None)
env.pop("STEAM_COMPAT_INSTALL_PATH", None)
return env
def snapshot(paths):
return {str(p): base64.b64encode(p.read_bytes()).decode() if p.exists() else None for p in paths}
def restore_files(saved):
for name, data in saved.items():
p = Path(name)
if data is None:
p.unlink(missing_ok=True)
else:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(base64.b64decode(data))
def desktop_paths():
config = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
apps = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share") / "applications"
paths = {apps / DESKTOP, config / "mimeapps.list", apps / "mimeapps.list", apps / "defaults.list"}
for base in (config, apps):
paths.update(base.glob("*-mimeapps.list"))
for desktop in os.environ.get("XDG_CURRENT_DESKTOP", "").lower().split(":"):
if desktop and re.fullmatch(r"[a-z0-9_-]+", desktop):
paths.add(base / f"{desktop}-mimeapps.list")
return apps, paths
def desktop_entry(helper):
# Desktop Exec has its own quoting (single shell quotes are not valid here); %% is a literal percent.
escaped = str(helper).replace("%", "%%")
for c in ("\\", '"', "`", "$"):
escaped = escaped.replace(c, "\\" + c)
escaped = re.sub(r"[\r\n\t]", " ", escaped.replace("\\", "\\\\")) # Desktop string-value layer
return ('[Desktop Entry]\nType=Application\nName=Meta sign-in (FramePort)\n'
f'Exec="{escaped}" %u\nNoDisplay=true\nTerminal=false\nMimeType=x-scheme-handler/oculus;\n')
def helper_script(op):
# This tiny script never imports the core or prints exceptions (which could contain the supplied URL).
return ("#!/usr/bin/python3 -I\nimport json,socket,sys\ntry:\n"
" with socket.socket(socket.AF_UNIX) as s:\n"
" s.settimeout(90)\n"
f" s.connect({str(folder() / 'broker.sock')!r})\n"
f" s.sendall(json.dumps({{'op': {op!r}, 'url': sys.argv[1]}}).encode())\n"
" s.shutdown(socket.SHUT_WR)\n s.recv(4096)\n"
"except Exception:\n sys.exit(1)\n")
def launcher():
q = shlex.quote
env = wine_env()
keys = ("STEAM_COMPAT_DATA_PATH", "WINEPREFIX", "WINEDLLOVERRIDES", "WINEDEBUG", "FP_NATIVE_WSERVER",
"PROTON_NO_ZENITY", "PROTONFIXES_DISABLE", "STEAM_COMPAT_CLIENT_INSTALL_PATH", "XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS", "ENABLE_GAMESCOPE_WSI")
exports = "".join(f"export {k}={q(env[k])}\n" for k in keys)
display = "".join(f"export {k}={q(v)}\n" for k, v in CORE.steam_display_env().items())
return f'''#!/usr/bin/env bash
# FramePort Meta sign-in: discard Electron output, which can contain native_sso URLs.
exec >/dev/null 2>&1
exec 9>{q(str(folder() / '.launch.lock'))}; flock -n 9 || exit 0
{exports}{display}unset LD_PRELOAD STEAM_COMPAT_INSTALL_PATH STEAM_COMPAT_LIBRARY_PATHS PROTON_LOG PROTON_LOG_DIR
python3 -I {q(str(Path(CORE.HERE) / 'fexrift.py'))} login_ping '{{}}' || exit 0
G={q(CORE.GEF)}
L="$WINEPREFIX/drive_c/users/steamuser/AppData/Local/Oculus"
cleanup() {{
kill $LK 2>/dev/null
"$G/files/bin/wineserver" -k
rm -f {q(str(folder() / 'launch.pid'))}
}}
trap cleanup EXIT
trap 'exit 0' TERM INT HUP
# The start tick prevents --stop from signalling a reused PID after an interrupted launcher.
printf '%s %s\\n' "$$" "$(awk '{{print $22}}' /proc/$$/stat)" > {q(str(folder() / 'launch.pid'))}
cd {q(str(Path(CORE.META_DIR) / 'Support/oculus-runtime'))}
"$G/files/bin/wine" ./OVRServer_x64.exe </dev/null &
for i in $(seq 1 45); do
sleep 2
tail -n 3 "$L/OVRLibrarian.log" 2>/dev/null | grep -qi "invocation completed" && break
done
sleep 3; pkill -9 -f "[O]VRLibrarian.exe"; sleep 10
( while sleep 5; do pkill -9 -f "[O]VRLibrarian.exe"; done ) & LK=$!
cd {q(str(Path(CORE.META_DIR) / 'Support/oculus-client'))}
"$G/proton" run ./Client.exe
'''
def signed_in():
sessions = Path(CORE.PFX) / "drive_c/users/steamuser/AppData/Roaming/Oculus/sessions"
return CORE.signed_in(str(sessions)) # sessions/<numeric user id>/, not Meta's _oaf framework folder
def running(name):
# /proc, rather than pgrep -f, avoids matching the command requesting status. Scope to this prefix.
for p in Path("/proc").glob("[0-9]*/environ"):
try:
if (f"WINEPREFIX={CORE.PFX}".encode() in p.read_bytes().split(b"\0") and
name.encode().lower() in p.with_name("cmdline").read_bytes().lower()):
return True
except OSError:
pass
return False
def status(args):
st = CORE.read_json(str(folder() / "state.json"), {}) or {}
out = {"runtime_running": running("OVRServer_x64.exe"), "client_running": running("Client.exe"),
"page_opened_at": st.get("page_opened_at"), "callback_received_at": st.get("callback_received_at"),
"signed_in": signed_in()}
if args.get("take_url"):
try:
out.update(request({"op": "take_url"}))
except (OSError, ValueError):
pass
return out
def deliver(url):
if not valid_url(url, callback=True):
return {"delivered": False}
try:
# Never put the callback in argv, even between two local processes. The PE reads UTF-8 on stdin.
p = quiet([str(Path(CORE.GEF) / "proton"), "run", str(Path(CORE.HERE) / "fp_pipesend.exe")],
input=url.encode(), env=wine_env())
return {"delivered": p.returncode == 0}
except (OSError, subprocess.SubprocessError):
return {"delivered": False}
class Broker:
def __init__(self, via_pc):
self.via_pc = via_pc
self.pending = None
self.stopped = False
def handle(self, msg):
op = msg.get("op")
if op in ("page", "callback"):
url = msg.get("url")
if not valid_url(url, callback=op == "callback"):
return {"accepted": False}
st = CORE.read_json(str(folder() / "state.json"), {}) or {}
st["page_opened_at" if op == "page" else "callback_received_at"] = time.time()
if op == "page":
st["page_url"] = "https://auth.meta.com/native_sso/confirm"
CORE.write_json(str(folder() / "state.json"), st)
if op == "callback":
return deliver(url)
if self.via_pc:
self.pending = url
else:
quiet(["xdg-open", url], env=host_env())
return {"accepted": True}
if op == "take_url":
url, self.pending = self.pending, None
return {"open_url": url} if url else {}
if op == "stop":
self.pending = None
self.stopped = True
return {"ready": True}
def broker(args):
path = folder() / "broker.sock"
service = Broker(bool(args.get("via_pc")))
try:
with socket.socket(socket.AF_UNIX) as s:
s.bind(str(path))
os.chmod(path, 0o600)
s.listen(4)
s.settimeout(1)
end = time.monotonic() + int(args.get("timeout", 900))
while not service.stopped and time.monotonic() < end:
try:
conn, _ = s.accept()
except TimeoutError:
continue
with conn:
conn.settimeout(5)
try:
reply = service.handle(json.loads(receive(conn)))
conn.sendall(json.dumps(reply).encode())
except (OSError, ValueError, subprocess.SubprocessError):
pass # do not serialize an exception that might contain a URL
finally:
service.pending = None
restore()
path.unlink(missing_ok=True)
return {"stopped": True}
def restore():
path = folder() / "restore.json"
saved = CORE.read_json(str(path), None)
if saved is None:
return
# Keep the restore record until every step succeeds: --stop can repair an interrupted cleanup.
launcher_pid = stop_launcher()
CORE.wineserver_kill()
if launcher_pid:
for _ in range(100):
if process_tick(launcher_pid[0]) != launcher_pid[1]:
break
time.sleep(.1)
else:
raise CORE.FexError("Meta sign-in launcher is still stopping; retry fex login --stop")
(folder() / "launch.pid").unlink(missing_ok=True)
old = saved.get("browser")
if old:
CORE.wine("reg", "add", REGKEY, "/v", "Browsers", "/t", old[0], "/d", old[1], "/f")
else:
CORE.wine("reg", "delete", REGKEY, "/v", "Browsers", "/f", check=False)
restore_files(saved["files"])
path.unlink()
def stop_launcher():
# Killing Wine alone while launch.sh is waiting for OVRLibrarian lets it start Client.exe *after* cleanup.
# Signal the owning shell too; its pending TERM exits the startup loop as soon as the current sleep ends.
path = folder() / "launch.pid"
try:
pid, tick = path.read_text().split()
pid = int(pid)
if pid <= 1:
return
if process_tick(pid) == tick:
os.kill(pid, signal.SIGTERM)
return pid, tick
except (OSError, ValueError, IndexError):
pass
def process_tick(pid):
try:
return Path(f"/proc/{pid}/stat").read_text().rpartition(")")[2].split()[19]
except (OSError, IndexError):
return None
def stop(args):
try:
request({"op": "stop"})
for _ in range(900):
if not (folder() / "broker.sock").exists():
break
time.sleep(.1)
else:
raise CORE.FexError("Meta sign-in is still stopping; retry fex login --stop")
except (OSError, ValueError):
restore()
(folder() / "broker.sock").unlink(missing_ok=True)
return {"stopped": True, "signed_in": signed_in()}
def start(args):
timeout = int(args.get("timeout") or 900)
if not 1 <= timeout <= 86400:
raise CORE.FexError("sign-in timeout must be between 1 and 86400 seconds")
if not (Path(CORE.HERE) / "fp_pipesend.exe").is_file():
raise CORE.FexError("fp_pipesend.exe missing: build native/fexwine/pipesend.c and upload it with fex setup")
if not (Path(CORE.META_DIR) / "Support/oculus-client/Client.exe").is_file():
raise CORE.FexError("Meta's PC app isn't installed yet; run fex setup first")
if running("Client.exe") or running("OVRServer_x64.exe"):
raise CORE.FexError("close the Rift game or Meta app before starting sign-in (the prefix is shared)")
try:
request({"op": "ping"})
except (OSError, ValueError):
pass
else:
raise CORE.FexError("Meta sign-in already active; use fex login --stop first")
stop({}) # repair a previous interrupted run before snapshotting its handler
folder().mkdir(parents=True, exist_ok=True, mode=0o700)
folder().chmod(0o700)
apps, paths = desktop_paths()
previous = subprocess.run(["xdg-mime", "query", "default", "x-scheme-handler/oculus"],
capture_output=True, text=True, timeout=10, env=host_env()).stdout.strip()
reg = CORE.wine("reg", "query", REGKEY, "/v", "Browsers", check=False)
match = re.search(r"Browsers\s+(REG_\w+)\s+(.*)", reg.stdout)
CORE.write_json(str(folder() / "restore.json"),
{"browser": list(match.groups()) if match else None, "handler": previous,
"files": snapshot(paths)})
try:
for name, text in (("fp-open-url", helper_script("page")),
("fp-oculus-callback", helper_script("callback")), ("launch.sh", launcher())):
CORE.put_text(str(folder() / name), text, 0o700)
CORE.write_json(str(folder() / "state.json"), {})
apps.mkdir(parents=True, exist_ok=True)
(apps / DESKTOP).write_text(desktop_entry(folder() / "fp-oculus-callback"))
if quiet(["xdg-mime", "default", DESKTOP, "x-scheme-handler/oculus"], env=host_env()).returncode:
raise CORE.FexError("couldn't register the Frame's temporary oculus link handler")
CORE.wine("reg", "add", REGKEY, "/v", "Browsers", "/t", "REG_SZ", "/d",
str(folder() / "fp-open-url"), "/f")
subprocess.Popen([sys.executable, "-I", str(Path(CORE.HERE) / "fexrift.py"), "login_broker",
json.dumps({"via_pc": bool(args.get("via_pc")), "timeout": timeout + 180})],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
for _ in range(100):
try:
request({"op": "ping"})
break
except (OSError, ValueError):
time.sleep(.05)
else:
raise CORE.FexError("couldn't start Meta sign-in's private URL broker")
if args.get("start_now"):
if quiet(["systemd-run", "--user", "--collect", "--quiet", "--unit=frameport-fexlogin",
"--property=StandardOutput=null", "--property=StandardError=null",
str(folder() / "launch.sh")], env=host_env()).returncode:
raise CORE.FexError("couldn't start Meta's app; retry without --start-now and use Steam")
return {"launcher": str(folder() / "launch.sh"), "started": bool(args.get("start_now")),
"signed_in": signed_in()}
except Exception:
stop({})
raise
def register(core):
global CORE
CORE = core
core.COMMANDS.update(login_start=start, login_status=status, login_stop=stop, login_broker=broker,
login_ping=lambda args: request({"op": "ping"}),
login_callback=lambda args: request({"op": "callback", "url": args.get("url")}))
-575
View File
@@ -1,575 +0,0 @@
"""Launch-time performance experiments. Frame side, stdlib only; no account data is read here.
Settings contain numbers/booleans and a small environment whitelist, never arbitrary shell. A launch prepares its
own config and exports it before Proton starts. Bench owns the otherwise-idle shared prefix for at most 120 s.
"""
import collections
import ctypes as C
import fcntl
import hashlib
import json
import math
import os
import sys
import re
import shlex
import shutil
import signal
import struct
import subprocess
import time
from pathlib import Path
CORE = None
FEX_KEYS = {"FEX_TSOENABLED", "FEX_VECTORTSOENABLED", "FEX_MEMCPYSETTSOENABLED", "FEX_MULTIBLOCK",
"FEX_X87REDUCEDPRECISION"}
DEFAULTS = {"dxvk_disable_msaa": False, "dxgi_sync_interval": -1, "dxgi_max_frame_latency": 0,
"eye_scale": 1.5, "motion_smoothing": 2, "cores": "4-7", "ntsync": True,
"fp_mem": False, "bigcache_mb": 256, "fp_mem_zero": False, "fex": {},
"wine_large_address_aware": False}
BOOL_KEYS = {"dxvk_disable_msaa", "ntsync", "fp_mem", "fp_mem_zero", "wine_large_address_aware"}
INT_KEYS = {"dxgi_sync_interval": (-1, 4), "dxgi_max_frame_latency": (0, 16), "motion_smoothing": (0, 2),
"bigcache_mb": (1, 6144)}
def app_name(app):
if not isinstance(app, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}", app):
raise ValueError("invalid Meta app name")
return app
def validate(values):
if not isinstance(values, dict):
raise ValueError("settings must be an object")
out = {}
for key, value in values.items():
if key in BOOL_KEYS:
if type(value) is not bool:
raise ValueError(f"{key} must be true or false")
elif key in INT_KEYS:
lo, hi = INT_KEYS[key]
if type(value) is not int or not lo <= value <= hi:
raise ValueError(f"{key} must be an integer in {lo}..{hi}")
elif key == "eye_scale":
if type(value) not in (float, int) or value not in (1.0, 1.25, 1.5):
raise ValueError("eye_scale must be 1.0, 1.25 or 1.5 (a divisor)")
elif key == "cores":
if not isinstance(value, str) or not re.fullmatch(r"[0-7](?:-[0-7])?(?:,[0-7](?:-[0-7])?)*", value):
raise ValueError("cores must be a taskset CPU list within 0..7")
if any(len(p) == 3 and p[0] > p[2] for p in value.split(",")):
raise ValueError("cores range is reversed")
elif key == "fex":
if not isinstance(value, dict) or any(k not in FEX_KEYS or type(v) not in (str, int) or
str(v) not in ("0", "1") for k, v in value.items()):
raise ValueError("fex permits only boolean TSO, MULTIBLOCK and X87REDUCEDPRECISION keys")
value = {k: str(v) for k, v in value.items()}
else:
raise ValueError(f"unknown performance setting: {key}")
out[key] = value
return out
def settings_path(app):
return os.path.join(CORE.ROOT, "settings", app_name(app) + ".json")
def settings_get(args):
app = app_name(args["app"])
info = CORE.GAMES.get(app, {})
env = info.get("env", {})
defaults = dict(DEFAULTS, fp_mem=env.get("FP_MEM", "") not in ("", "0"),
bigcache_mb=int(env.get("FP_BIGCACHE_MB", 256)))
defaults.update(validate(info.get("perf", {})))
overrides = validate(CORE.read_json(settings_path(app), {}) or {})
return {"app": app, "settings": dict(defaults, **overrides), "overrides": overrides}
def settings_set(args):
app = app_name(args["app"])
# Validate the whole request before writing. Null removes an override (the catalog/default becomes active).
updates = {k: v for k, v in args.items() if k != "app"}
if any(k not in DEFAULTS for k in updates):
raise ValueError("unknown performance setting")
values = settings_get({"app": app})["overrides"]
values.update(validate({k: v for k, v in updates.items() if v is not None}))
for k, v in updates.items():
if v is None:
values.pop(k, None)
CORE.write_json(settings_path(app), values)
return settings_get({"app": app})
def scale_folder(scale):
return os.path.join(CORE.ROOT, "revive-scales", format(float(scale), "g"))
def eye_variant(data, scale):
"""Only the research Revive 3.2.0 eye-size site, with PE RVA translation. Never touch Oculus binaries.
Accept the stock eye-size load or the research divisor load. Refuse other instructions rather than guessing
at a new Revive build. Use a dedicated padding slot, leaving shared constants in the data section unchanged.
"""
if data[:2] != b"MZ":
raise ValueError("Revive eye scale: invalid PE")
pe = struct.unpack_from("<I", data, 0x3c)[0]
n, opt = struct.unpack_from("<H", data, pe + 6)[0], struct.unpack_from("<H", data, pe + 20)[0]
def offset(rva):
for i in range(n):
size, va, rawsize, raw = struct.unpack_from("<IIII", data, pe + 24 + opt + i * 40 + 8)
if va <= rva < va + min(size, rawsize):
return raw + rva - va
raise ValueError("Revive eye scale: RVA outside sections")
ins, slot = offset(0x12eab), offset(0x12e9c)
# Original movss xmm4,[1.0], or the research patch's load of the existing 1.5 at RVA 0x4eaa4.
# Put our divisor in verified function-alignment padding: changing a shared rdata constant affects other code.
old = data[ins:ins + 8]
original = bytes.fromhex("f30f102515bb0400")
research = b"\xf3\x0f\x10\x25" + struct.pack("<i", 0x4eaa4 - 0x12eb3)
if old not in (original, research) or data[offset(0x12e91)] != 0xc3 or data[slot:slot + 4] != b"\xcc" * 4:
raise ValueError("Revive eye scale: unexpected 3.2.0 eye-size instruction/padding")
out = bytearray(data)
struct.pack_into("<f", out, slot, scale)
out[ins:ins + 8] = b"\xf3\x0f\x10\x25" + struct.pack("<i", 0x12e9c - 0x12eb3)
return bytes(out)
def prepare_scales():
src = Path(CORE.REVIVE)
data = (src / "LibRevive64.dll").read_bytes()
# PC setup validates stock 3.2.0 and applies REVIVE_PATCHES (src/frameport/fexrift.py): the visibility fixes and
# the eye-size redirect to the 1.5 constant. Accept only that upload, or the same without the eye-size redirect.
uploaded = {"eda2a449d230832c95734a03e8c83eeb531668ce676693f636e19c315765af4e", # all six patches
"0a3a6733f5decec74abb16b85c1f72783a6f421160753f600ddae4e8cb6482c6"} # visibility fixes only
if hashlib.sha256(data).hexdigest() not in uploaded:
raise ValueError("Revive eye scale: needs FramePort's patched Revive 3.2.0 upload")
for scale in (1.0, 1.25, 1.5):
patched = eye_variant(data, scale) # validate before replacing any directory
dest = Path(scale_folder(scale))
tmp = dest.with_name(dest.name + ".new")
shutil.rmtree(tmp, ignore_errors=True)
shutil.copytree(src, tmp, copy_function=os.link)
# Break the hard link before changing the DLL: shared base and other variants stay intact.
dll = tmp / "LibRevive64.dll"
dll.unlink()
dll.write_bytes(patched)
shutil.rmtree(dest, ignore_errors=True)
os.replace(tmp, dest)
def perf_prepare(args):
app = app_name(args["app"])
s = settings_get({"app": app})["settings"]
config = os.path.join(CORE.ROOT, "settings", app + ".dxvk.conf")
os.makedirs(os.path.dirname(config), exist_ok=True) # first launch of a game nobody changed settings for
managed = ("d3d11.disableMsaa", "dxgi.syncInterval", "dxgi.maxFrameLatency") # these settings win
profile = [str(line) for line in args.get("dxvk", []) if "\n" not in str(line)
and str(line).split("=", 1)[0].strip() not in managed]
lines = profile + [f"{k} = {s[key]}" for k, key, default in (
("d3d11.disableMsaa", "dxvk_disable_msaa", False), ("dxgi.syncInterval", "dxgi_sync_interval", -1),
("dxgi.maxFrameLatency", "dxgi_max_frame_latency", 0)) if s[key] != default]
# Defaults = exactly the launch verified in the headset (First Contact, 2026-10-10): no dxvk.conf, the uploaded
# Revive (its eye-size patch is 1.5), no large-address-aware flag; only a changed setting adds something.
if lines:
CORE.put_text(config, "\n".join(lines + [""]))
elif os.path.lexists(config):
os.remove(config)
if s["eye_scale"] == 1.5:
revive = CORE.REVIVE
else:
revive = scale_folder(s["eye_scale"])
if not os.path.isfile(os.path.join(revive, "LibRevive64.dll")):
prepare_scales()
exports = {"FP_CORES": s["cores"], "FP_REVIVE_DIR": revive,
"FP_MEM": "1" if s["fp_mem"] else "", "FP_BIGCACHE_MB": str(s["bigcache_mb"]),
"FP_MEM_ZERO": "1" if s["fp_mem_zero"] else "0", "PROTON_NO_NTSYNC": "0" if s["ntsync"] else "1",
"FP_MOTION_SMOOTHING": json.dumps({"section": f"steam.app.{CORE.GAME_ID}",
"key": "motionSmoothingOverride", "kind": "i",
"value": s["motion_smoothing"]})}
exports.update({k: str(s["fex"].get(k, "0" if "TSO" in k else "1" if k == "FEX_MULTIBLOCK" else "0"))
for k in FEX_KEYS})
if lines:
exports["DXVK_CONFIG_FILE"] = config
if s["wine_large_address_aware"]:
exports["WINE_LARGE_ADDRESS_AWARE"] = "1"
shell = "\n".join(f"export {k}={shlex.quote(v)}" for k, v in exports.items())
if s["ntsync"]:
shell += "\nunset PROTON_NO_NTSYNC"
return {"shell": shell, "settings": s}
def launcher_env(app, info):
# stdout is an isolated helper's JSON, then a tiny decoder emits only validated exports. Failure aborts launch:
# continuing with an old config would give misleading experimental results (and could enable stale fp_mem).
# the compat profile's dxvk.conf lines (stream C) go into the same per-game config as these settings
dxvk = [str(line) for line in info.get("dxvk", []) if "\n" not in str(line) and "\r" not in str(line)]
arg = shlex.quote(json.dumps({"app": app_name(app), "dxvk": dxvk}))
decode = 'import json,sys; print(json.load(sys.stdin)["result"]["shell"])'
return [f'FP_PERF=$(python3 -I "$R/artifacts/fexrift.py" perf_prepare {arg}) || exit 1',
f'eval "$(printf \'%s\' "$FP_PERF" | python3 -I -c {shlex.quote(decode)})"']
# OpenVR IVRCompositor_022 Compositor_FrameTiming, including its 80-byte TrackedDevicePose_t. Keeping the tail
# prevents GetFrameTimings overwriting a truncated ctypes structure. Versions are pinned, never probed by index.
class FrameTiming(C.Structure):
_fields_ = [(n, C.c_uint32) for n in ("size", "index", "presents", "mis_presents", "dropped", "reprojection")]
_fields_ += [("system_time", C.c_double)]
_fields_ += [(n, C.c_float) for n in ("pre_gpu", "post_gpu", "gpu_ms", "compositor_gpu", "compositor_cpu",
"compositor_idle", "client_interval", "present_call", "wait_present",
"submit", "poses_called", "poses_ready", "frame_ready", "update_start",
"update_end", "render_start")]
_fields_ += [("pose", C.c_byte * 80), ("vsyncs_ready", C.c_uint32), ("vsyncs_first", C.c_uint32)]
class VR:
def __init__(self):
self.core, self.method, self.settings = CORE.vr_settings()
try:
self.compositor = self.interface(b"IVRCompositor_022")
self.system = self.interface(b"IVRSystem_022")
except BaseException:
self.close()
raise
def interface(self, name):
err = C.c_int()
obj = self.method(self.core, 3, C.c_void_p, C.c_char_p, C.POINTER(C.c_int))(name, C.byref(err))
if not obj or err.value:
raise ValueError("benchmark needs " + name.decode())
return obj
def activity(self):
# IVRSystem_022::GetTrackedDeviceActivityLevel(HMD=0). UserInteraction (1) and its timeout (2) refuse.
return self.method(self.system, 15, C.c_int, C.c_uint32)(0)
def screen_timeout(self):
err = C.c_int()
value = self.method(self.settings, 7, C.c_float, C.c_char_p, C.c_char_p, C.POINTER(C.c_int))(
b"power", b"turnOffScreensTimeout", C.byref(err))
if err.value or not math.isfinite(value) or value <= 0:
raise ValueError("cannot read screen timeout; benchmark refused")
return value
def timings(self):
rows = (FrameTiming * 128)()
for row in rows:
row.size = C.sizeof(FrameTiming)
n = self.method(self.compositor, 9, C.c_uint32, C.POINTER(FrameTiming), C.c_uint32)(rows, 128)
return [{"index": r.index, "presents": r.presents, "gpu_ms": r.gpu_ms,
"cpu_ms": r.client_interval, "system_time": r.system_time} for r in rows[:min(n, 128)]]
def scene_pid(self):
return self.method(self.compositor, 22, C.c_uint32)() # GetCurrentSceneFocusProcess
def close(self):
self.method(self.core, 1, None)()
def drm_engines(text):
"""DRM fdinfo nanoseconds, deduplicated by drm-client-id by the caller (dup fds share one client)."""
out = {}
for line in text.splitlines():
m = re.fullmatch(r"drm-engine-([\w-]+):\s*(\d+)\s+ns", line.strip())
if m:
out[m[1]] = int(m[2])
return out
def process_sample(pids, proc="/proc"):
engines, waits, seen = {}, collections.Counter(), set()
for pid in pids:
base = Path(proc) / str(pid)
for fd in (base / "fdinfo").glob("*"):
try:
text = fd.read_text()
except OSError:
continue
client = re.search(r"^drm-client-id:\s*(\d+)", text, re.M)
device = re.search(r"^drm-pdev:\s*(.+)", text, re.M)
if not client:
continue
identity = (device[1] if device else "", client[1])
if identity in seen:
continue
seen.add(identity)
for engine, ns in drm_engines(text).items():
engines[(identity, engine)] = ns
for task in (base / "task").glob("*"):
try:
waits[task.joinpath("wchan").read_text().strip()] += 1
except OSError:
pass
return engines, waits
def gpu_delta(before, after):
# Clients that open during the interval have no baseline; do not attribute their lifetime counters to one tick.
return sum(max(0, v - before[k]) for k, v in after.items() if k in before)
def processes(proc="/proc"):
out = {}
for p in Path(proc).glob("[0-9]*"):
try:
if p.stat().st_uid != os.getuid():
continue
cmd = p.joinpath("cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
comm = p.joinpath("comm").read_text().strip()
out[int(p.name)] = (comm, cmd)
except OSError:
pass
return out
def busy_processes(rows):
# Do not print cmdlines: another stream may be handling an Oculus browser sign-in.
return [pid for pid, (comm, cmd) in rows.items() if
(re.search(r"(?i)(\.exe(?: |$)|(?:^|/)(?:proton|wine(?:64)?(?:-preloader)?)(?: |$)|lepton-steamlaunch-)",
cmd)
or (comm == "reaper" and not re.search(r"\bAppId=250820\b", cmd))
or comm.startswith("wineserver") or comm in ("FEXInterpreter", "FEXLoader", "pressure-vessel"))]
def recent_steam_input(steam, now=None):
"""Steam input log is a supplementary guard, HMD activity is the authoritative one. Never read login logs."""
now = time.time() if now is None else now
path = Path(steam) / "logs/controller.txt"
try:
# A recent controller log write can be a device reconnection, so conservatively refuse it too.
return now - path.stat().st_mtime < 60
except FileNotFoundError:
return False
def vr_set(section, key, kind, value):
# In its own process: cmd_vrsetting in the process that holds VR()'s SteamVR connection segfaulted on the
# second call (reproduced on the Frame 2026-10-16) after the first had turned the display's standby pause off.
result = vrsetting_subprocess(section, key, kind, value)
if result.get("error"):
raise ValueError(f"SteamVR refused {section}/{key}")
def stop_launcher(child):
# The shared prefix was verified idle before launch, so -k cannot interrupt an earlier game or login.
try:
subprocess.run([os.path.join(CORE.GEF, "files/bin/wineserver"), "-k"], env=CORE.wine_env(),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
finally:
if child is not None:
try:
os.killpg(child.pid, signal.SIGTERM)
child.wait(timeout=5)
except ProcessLookupError:
pass
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
child.wait(timeout=5)
START_WAIT = 180 # seconds the bench waits for the game's process after starting its launcher
def bench_run(args, launcher, vr):
seconds = args.get("seconds", 120)
if type(seconds) is not int or not 1 <= seconds <= 120:
raise ValueError("seconds must be an integer in 1..120")
if busy_processes(processes()) or recent_steam_input(CORE.STEAM) or vr.activity() != 3:
raise ValueError("benchmark refused: game, Wine, container, HMD activity or recent Steam input")
screen = vr.screen_timeout() # no setting is changed until both safety checks and this read succeed
vrserver_log = os.path.join(CORE.STEAM, "logs", "vrserver.txt")
log_start = os.path.getsize(vrserver_log) if os.path.isfile(vrserver_log) else 0
guard_write(screen=screen) # before any change: the parent restores from it if this process dies
child, old_handler = None, None
settings = settings_get(args)["settings"]
frames, waits, gpu, gpu_seconds = {}, collections.Counter(), 0, 0.0
started = time.monotonic()
def interrupted(signum, frame):
raise ValueError("benchmark interrupted")
try:
old_handler = signal.signal(signal.SIGTERM, interrupted)
vr_set("power", "pauseCompositorOnStandby", "b", False)
vr_set("power", "turnOffScreensTimeout", "f", float(seconds + START_WAIT + 10))
# Save the initial frame index so stale scene frames in the compositor ring are excluded.
initial = {r["index"] for r in vr.timings()}
with open(os.devnull, "wb") as sink:
child = subprocess.Popen([launcher], stdin=subprocess.DEVNULL, stdout=sink, stderr=sink,
start_new_session=True, close_fds=True)
guard_write(screen=screen, pgid=getattr(child, "pid", None))
# The launcher starts Meta's runtime and waits for it (60-100 s under FEX) before the game: the window
# starts when the game's process appears, not at the launch.
wait_end = time.monotonic() + START_WAIT
while not [q for q, (_, cmd) in processes().items() if args["exe"].lower() in cmd.lower()]:
if time.monotonic() > wait_end:
raise ValueError(f"benchmark: the game didn't start within {START_WAIT} s; inspect launch.log")
if child.poll() is not None:
raise ValueError("benchmark launcher exited before the game started; inspect launch.log")
level = vr.activity()
if level == 1: # controller.txt isn't a signal here: the starting game loads its input bindings
raise ValueError(f"benchmark stopped: owner interaction (activity {level})")
time.sleep(1)
before, previous = {}, time.monotonic()
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
# Before the launch the headset must be in standby (3); the game itself then wakes the compositor
# (activity leaves standby), so during the run only real use stops it: 1 = user interaction (worn or
# moved), or new controller input.
level = vr.activity()
if level == 1: # controller.txt isn't a signal here: the starting game loads its input bindings
raise ValueError(f"benchmark stopped: owner interaction (activity {level})")
if child.poll() is not None:
raise ValueError("benchmark launcher exited before the sampling window ended; inspect launch.log")
rows = processes()
# Only the actual game's exe (or FEX's argv containing it), not the runtime/compositor GPU client.
pids = [p for p, (_, cmd) in rows.items() if args["exe"].lower() in cmd.lower()]
after, w = process_sample(pids)
now = time.monotonic()
if before.keys() & after.keys():
gpu += gpu_delta(before, after)
gpu_seconds += now - previous
before, previous = after, now
waits.update(w)
focus = vr.scene_pid()
for r in vr.timings():
if focus in pids and r["index"] not in initial:
frames[r["index"]] = r # ring revisits update presents, not another frame
time.sleep(min(0.5, max(0, deadline - time.monotonic())))
finally:
# Each cleanup is attempted even when the preceding one fails. Display safety outranks benchmark success.
try:
stop_launcher(child)
finally:
try:
vr_set("power", "pauseCompositorOnStandby", "b", True)
finally:
try:
vr_set("power", "turnOffScreensTimeout", "f", screen)
finally:
if old_handler is not None:
signal.signal(signal.SIGTERM, old_handler)
records = list(frames.values())
# Without a tracking universe (IMU fallback, e.g. after a boot without the headset worn) Rift games wait at
# startup forever: SteamVR's own frames are all a run then counts (seen 2026-10-16, ~1.9/s, game GPU ~0 %).
imu_fallback = False
try:
with open(vrserver_log, errors="replace") as f:
f.seek(log_start if os.path.getsize(vrserver_log) >= log_start else 0)
imu_fallback = "IMU fallback is active" in f.read(8 << 20)
except OSError:
pass
duration = max(0.001, time.monotonic() - started)
times = [r["system_time"] for r in records]
span = max(times) - min(times) if len(times) > 1 else 0
return {"app": args["app"], "seconds": seconds, "elapsed_s": round(duration, 3), "frames": len(records),
"imu_fallback": imu_fallback, # true: the result says nothing about the game (put the headset on once)
"valid": len(records) >= 2 and span > 0 and not imu_fallback, "sample_span_s": round(span, 3),
"fps": round((len(records) - 1) / span, 2) if span > 0 else None,
"hitches": sum(r["presents"] >= 3 for r in records),
"hitches_per_20s": round(20 * sum(r["presents"] >= 3 for r in records) / span, 2) if span > 0 else None,
"game_gpu_busy_pct": round(100 * gpu / (gpu_seconds * 1e9), 2) if gpu_seconds else None,
"render_gpu_ms": round(sum(r["gpu_ms"] for r in records) / len(records), 3) if records else None,
"client_interval_ms": round(sum(r["cpu_ms"] for r in records) / len(records), 3) if records else None,
"thread_wchan_samples": dict(waits), "settings": settings}
def bench(args):
app = app_name(args["app"])
# Launcher path is supplied by the owning agent's deployment record, not an arbitrary remote shell command.
launcher = args["launcher"]
if not os.path.isfile(launcher) or os.path.basename(launcher) != "launch.sh":
raise ValueError("install the game before benchmarking")
info, _ = CORE.game_info(app)
exe = os.path.basename(info["exe"].replace("\\", "/"))
os.makedirs(CORE.ROOT, exist_ok=True)
with open(os.path.join(CORE.ROOT, ".bench.lock"), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return bench_guarded(dict(args, app=app, exe=exe), launcher)
# The measurement talks to SteamVR through ctypes (vrclient.so). A native crash there kills the process without
# running bench_run's finally, which once left pauseCompositorOnStandby=false (display kept on) on the Frame
# (2026-10-16). So it runs in a forked child, and the parent restores the display settings and stops the game from
# a guard file when the child returns no result, each restore in its own process (another crash can't skip it).
def guard_path():
return os.path.join(CORE.ROOT, ".bench.guard.json")
def guard_write(**kw):
CORE.write_json(guard_path(), kw)
def vrsetting_subprocess(section, key, kind, value):
"""fexrift.py vrsetting in a fresh process: {"error": code} from SteamVR, or {"error": "..."} if it failed."""
arg = json.dumps({"section": section, "key": key, "kind": kind, "value": value})
p = subprocess.run([sys.executable, "-I", os.path.join(CORE.HERE, "fexrift.py"), "vrsetting", arg],
capture_output=True, text=True, timeout=60)
try:
out = json.loads(p.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
return {"error": f"vrsetting exited {p.returncode}"}
return out.get("result", {}) if out.get("ok") else {"error": out.get("error", "failed")}
def crash_cleanup():
guard = CORE.read_json(guard_path(), {}) or {}
try:
if guard.get("pgid"):
try:
os.killpg(int(guard["pgid"]), signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
subprocess.run([os.path.join(CORE.GEF, "files/bin/wineserver"), "-k"], env=CORE.wine_env(),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
finally:
vrsetting_subprocess("power", "pauseCompositorOnStandby", "b", True)
if guard.get("screen") is not None:
vrsetting_subprocess("power", "turnOffScreensTimeout", "f", float(guard["screen"]))
def bench_guarded(args, launcher):
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid == 0: # child: measure, report through the pipe
os.close(read_fd)
code = 0
try:
vr = VR()
try:
out = {"ok": True, "result": bench_run(args, launcher, vr)}
finally:
vr.close()
except Exception as e: # noqa: BLE001 - reported to the parent as the command's error
out, code = {"ok": False, "error": f"{type(e).__name__}: {e}"}, 1
with os.fdopen(write_fd, "w") as w:
w.write(json.dumps(out))
os._exit(code)
os.close(write_fd)
try:
with os.fdopen(read_fd) as r:
raw = r.read()
_, status = os.waitpid(pid, 0)
out = json.loads(raw) if raw.strip() else None
if out is None: # crashed or killed: bench_run's own cleanup didn't run
crash_cleanup()
raise ValueError(f"benchmark process died ({'signal ' + str(-os.waitstatus_to_exitcode(status)) if os.WIFSIGNALED(status) else 'no result'}); display settings restored, game stopped")
if not out["ok"]:
raise ValueError(out["error"])
return out["result"]
finally:
try:
os.remove(guard_path())
except FileNotFoundError:
pass
def register(core):
global CORE
CORE = core
core.COMMANDS.update(settings_get=settings_get, settings_set=settings_set, perf_prepare=perf_prepare, bench=bench)
core.LAUNCHER_ENV_HOOKS.append(launcher_env)
# Use the existing setup step so --steps revive prepares the variants too, without another download.
def revive():
result = core.step_revive()
prepare_scales()
return result
core.STEPS = [(name, revive if name == "revive" else fn) for name, fn in core.STEPS]
+4 -244
View File
@@ -44,7 +44,7 @@ try:
except ImportError: # Windows: pc_revive loads this file for its VDF code only (GitHub #131)
fcntl = None
AGENT_VERSION = 94
AGENT_VERSION = 91
HOME = os.path.expanduser("~")
STEAM = os.path.join(HOME, ".local/share/Steam")
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
@@ -1142,7 +1142,7 @@ def shortcut_args(pkg):
icon = app_icon_for(dep, anchor, steam=True)[0] # a Linux app's own icon unless the user chose one
flat = dep.get("vr") is False
kind = dep.get("kind")
tag = ("Windows game on Frame" if flat else "PC VR on Frame") if kind in ("pcvr", "frame_fex") else \
tag = ("Windows game on Frame" if flat else "PC VR on Frame") if kind == "pcvr" else \
"Linux app on Frame" if kind == "linux" else "Quest on Frame"
return f'"{anchor}/launch.sh"', dep["title"], anchor, icon, tag, dep.get("tags") or [], not flat
@@ -1891,7 +1891,7 @@ def app_media_dirs(ext):
def lepton_external(pkg):
dep = deployment(pkg)
if not dep or dep.get("kind") in ("pcvr", "frame_fex"):
if not dep or dep.get("kind") == "pcvr":
raise AgentError(f"{pkg} is not an installed Quest (Lepton) game")
return os.path.join(dep["base"], "lepton-data", "external")
@@ -5460,11 +5460,8 @@ def cmd_uninstall(args):
base = dep["base"]
pcvr = dep.get("kind") == "pcvr"
linux = dep.get("kind") == "linux"
fex = dep.get("kind") == "frame_fex"
if (pcvr_pids(base) if pcvr or linux or fex else container_running(dep["appid"])):
if (pcvr_pids(base) if pcvr or linux else container_running(dep["appid"])):
raise AgentError("the game is running")
if fex: # the game lives in the shared Meta runtime prefix (with the user's login): only the launcher goes
return fex_uninstall(pkg, dep, args)
if is_overlay(dep) or os.path.exists(os.path.join(ANCHORS, pkg, OVERLAY_MANIFEST)):
unregister_overlay(pkg) # SteamVR forgets the overlay app (before its manifest's folder goes)
keep_data = args.get("keep_data", True)
@@ -5815,8 +5812,6 @@ def cmd_stop(args):
run(["systemctl", "--user", "stop", f"frameport-test-{dep['appid']}"])
if dep.get("kind") == "pcvr":
stop_pcvr(dep)
elif dep.get("kind") == "frame_fex": # the launcher's EXIT trap stops Wine (wineserver -k)
run(["pkill", "-TERM", "-f", re.escape(os.path.join(ANCHORS, dep["package"], "launch.sh"))])
elif dep.get("kind") == "linux":
for pid in pcvr_pids(dep["base"]):
run(["kill", "-TERM", pid])
@@ -5929,8 +5924,6 @@ def cmd_launch_test(args):
if is_overlay(dep): # nothing to see without a game; register_vr_overlay's SteamVR check is the test
return {"state": "SKIPPED", "skipped": "overlay app", "elapsed": 0, "log": None, "log_size": 0,
"crash_log": None, "kind": dep.get("kind")}
if dep.get("kind") == "frame_fex":
raise AgentError("launch tests aren't available for Rift games with Meta's runtime (experimental) yet")
if dep.get("kind") == "pcvr":
return launch_test_pcvr(dep, anchor, log, seconds)
if dep.get("kind") == "linux":
@@ -7913,239 +7906,6 @@ def monitor_session(stdin, stdout, monitor=None, sleep=time.sleep, max_ticks=Non
return 0
# ------------------------------------------------------------------------------------------ Rift via FEX (experimental)
# Oculus Rift games that need Meta's PC runtime, on the Frame alone: x86_64 GE-Proton under FEX + Meta's runtime +
# Revive in one shared Wine prefix. The work is done by fexrift.py (uploaded with its binaries by the PC, see
# src/frameport/fexrift.py and native/fexwine/README.md); these commands only start it and track games (kind
# "frame_fex"; the game's files stay inside the prefix where Meta's app put them).
FEX_ROOT = os.path.join(HOME, ".local/share/frameport/fexrift")
FEX_ARTIFACTS = os.path.join(FEX_ROOT, "artifacts")
FEX_HELPER = os.path.join(FEX_ARTIFACTS, "fexrift.py")
def fex_helper(command, args=None, timeout=900):
if not os.path.isfile(FEX_HELPER):
raise AgentError("the files for Rift games on the Frame aren't here yet (run the setup first)")
# Game inventories can exceed Linux's per-argument limit; the helper already accepts JSON on stdin.
p = run([sys.executable, "-I", FEX_HELPER, command], input=json.dumps(args or {}), timeout=timeout)
try:
out = json.loads(p.stdout.strip().splitlines()[-1])
except (IndexError, ValueError):
raise AgentError(f"fexrift {command} failed: {(p.stderr or p.stdout)[-400:]}") from None
if not out.get("ok"):
raise AgentError(out.get("error") or f"fexrift {command} failed")
return out["result"]
def cmd_fex_prepare(args):
"""Where the PC uploads fexrift.py + its binaries (artifacts/) and the login archive (incoming/), and what's
already there (unchanged files aren't re-sent)."""
incoming = os.path.join(FEX_ROOT, "incoming")
for d in (FEX_ARTIFACTS, incoming):
os.makedirs(d, exist_ok=True)
os.chmod(incoming, 0o700)
st = os.statvfs(FEX_ROOT)
return {"root": FEX_ROOT, "artifacts": FEX_ARTIFACTS, "incoming": incoming,
"existing": tree_manifest(FEX_ARTIFACTS), "free_bytes": st.f_bavail * st.f_frsize,
"fex": os.path.isdir(os.path.join(STEAM, "steamapps/common/FEX-Emu"))}
def cmd_fex_status(args):
if not os.path.isfile(FEX_HELPER):
return {"helper": False}
res = fex_helper("status", timeout=60)
res["helper"] = True
return res
def cmd_fex_setup(args):
"""Start the setup (GE-Proton download, Meta's runtime from Meta's CDN, the prefix): ~10-20 min, detached;
progress via fex_status (setup.state / step / error)."""
if not os.path.isfile(FEX_HELPER):
raise AgentError("upload the files first (fex_prepare)")
steps = [s for s in args.get("steps") or [] if re.fullmatch(r"[a-z]+", str(s))]
unit = f"frameport-fexsetup-{int(time.time())}"
p = run(["systemd-run", "--user", "--collect", "--quiet", f"--unit={unit}", "--setenv=HOME=" + HOME,
sys.executable, "-I", FEX_HELPER, "setup", json.dumps({"steps": steps})])
if p.returncode != 0:
raise AgentError(f"couldn't start the setup: {p.stderr.strip()[-300:]}")
return {"started": True, "unit": unit}
def cmd_fex_import_login(args):
"""The login archive the PC uploaded to incoming/login.tar (fexrift.py deletes it afterwards)."""
return fex_helper("import_login", {"tar": os.path.join(FEX_ROOT, "incoming", "login.tar")})
# Local-copy extension commands: validate removable storage here (the helper has no drive discovery). Never let a
# missing mount silently turn an SD-card install into an upload to the root filesystem.
def fex_local_dest(dest):
if not dest or dest == "internal":
return None
for d in cmd_drives({})["drives"]:
if not d["internal"] and d["path"] == dest:
resolve_dest(dest) # existing filesystem / writable-mount checks
return dest
raise AgentError("--dest must name an available external drive's mount point (see frame drives)")
def cmd_fex_prepare_local(args):
pkg = check_pkg(args["package"])
dep = deployment(pkg)
if dep and (dep.get("kind") != "frame_fex" or dep.get("source") != "local_copy"
or dep.get("app") != args.get("app")):
raise AgentError(f"{pkg} is already installed in another way; uninstall it first")
return fex_helper("prepare_local", dict(args, package=pkg, dest=fex_local_dest(args.get("dest"))))
def cmd_fex_register_local(args):
info = fex_helper("local_info", {"app": args["app"]})
fex_local_dest(info.get("dest"))
return fex_helper("register_local", args, timeout=7200) # hashes large copies on the Frame, not on NTFS
def cmd_fex_runtime_state(args):
return fex_helper("runtime_state", {"app": args["app"]}, timeout=120)
# Browser sign-in: this block deliberately uses stdin, not fex_helper's JSON argv. A callback carries credentials.
FEX_LOGIN_PACKAGE = "linux.frameport_meta_signin"
def fex_login_call(command, args=None):
if not os.path.isfile(FEX_HELPER):
raise AgentError("run fex setup before signing in")
p = subprocess.run([sys.executable, "-I", FEX_HELPER, command], input=json.dumps(args or {}),
capture_output=True, text=True, timeout=120)
try:
out = json.loads(p.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
raise AgentError("Meta sign-in helper did not answer") from None
if not out.get("ok"):
# No raw subprocess output in errors for the commands handling URLs.
raise AgentError(out.get("error", "Meta sign-in failed") if command == "login_start" else
"Meta sign-in helper failed; retry fex login --stop")
return out["result"]
def cmd_fex_login(args):
result = fex_login_call("login_start", {"start_now": bool(args.get("start_now")),
"via_pc": bool(args.get("via_pc")),
"timeout": int(args.get("login_timeout") or 900)})
if not args.get("start_now"):
anchor = os.path.join(ANCHORS, FEX_LOGIN_PACKAGE)
os.makedirs(anchor, exist_ok=True)
launcher = os.path.join(anchor, "launch.sh")
if os.path.lexists(launcher):
os.remove(launcher)
os.symlink(result["launcher"], launcher)
with open(os.path.join(anchor, "deployment.json"), "w") as f:
json.dump({"package": FEX_LOGIN_PACKAGE, "kind": "linux", "title": "Meta sign-in (FramePort)",
"base": os.path.join(FEX_ROOT, "login"), "vr": False, "desktop_entry": False,
"appid": shortcut_appid(f'"{launcher}"', "Meta sign-in (FramePort)")}, f)
result["package"] = FEX_LOGIN_PACKAGE
return result
def cmd_fex_login_status(args):
return fex_login_call("login_status", {"take_url": bool(args.get("take_url"))})
def cmd_fex_login_callback(args):
return fex_login_call("login_callback", {"url": args.get("url")})
def cmd_fex_login_cancel(args):
result = fex_login_call("login_stop")
anchor = os.path.join(ANCHORS, FEX_LOGIN_PACKAGE)
if os.path.exists(os.path.join(anchor, "deployment.json")):
cmd_shortcuts({"remove": [{"exe": f'"{anchor}/launch.sh"'}], "restart": True})
devkit_unregister(FEX_LOGIN_PACKAGE, steam_running=run(["pgrep", "-x", "steam"]).returncode == 0)
remove_tree(anchor)
return result
def cmd_fex_install(args):
"""A game Meta's app downloaded (now in the prefix) as a Steam game: per-game fixes + launch.sh +
deployment.json (kind frame_fex). The Steam shortcut is added like for other games (shortcuts)."""
pkg = check_pkg(args["package"])
app = str(args.get("app") or "")
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]+", app):
raise AgentError(f"bad app name {app!r}")
anchor = os.path.join(ANCHORS, pkg)
dep = deployment(pkg)
if dep and dep.get("kind") != "frame_fex":
raise AgentError(f"{pkg} is already installed in another way")
local = None
if args.get("source") == "local_copy" or (dep or {}).get("source") == "local_copy":
local = fex_helper("local_info", {"app": app})
if local.get("package") != pkg or not local.get("registered"):
raise AgentError("local copy must be registered for this package first")
fex_local_dest(local.get("dest"))
msaa = args.get("msaa")
res = fex_helper("install", {"app": app, "anchor": anchor, "msaa": msaa if msaa in (1, 2, 4) else None,
"force_unverified": bool(args.get("force_unverified"))})
title = str(args.get("title") or res.get("title") or pkg).replace("\n", " ")
appid = dep["appid"] if dep else shortcut_appid(f'"{anchor}/launch.sh"', title)
dep = {"package": pkg, "kind": "frame_fex", "app": app, "appid": int(appid), "title": title,
"base": res["game_dir"], "exe": res["exe"], "tags": args.get("tags") or [], "vr": True,
"fixes": {k: res.get(k) for k in ("ime_patch", "msaa")}, "verified": bool(res.get("verified")),
"checks": res.get("checks") or {},
"agent_version": AGENT_VERSION, "installed": int(time.time())}
if local:
dep.update({k: local.get(k) for k in ("source", "app_id", "app_id_source", "store_app_id", "skipped", "dest")})
path = os.path.join(anchor, "deployment.json")
with open(path + ".tmp", "w") as f:
json.dump(dep, f, indent=1)
os.replace(path + ".tmp", path)
return {"package": pkg, "appid": dep["appid"], "title": title, "launcher": res["launcher"], "fixes": dep["fixes"],
"verified": dep["verified"], "checks": dep["checks"]}
# ---------------------------------------------------------------------- FEX launch-time settings / bounded bench
# Kept separate from install: settings are read at launch and never require changing the game's files.
def cmd_fex_settings(args):
values = args.get("values")
if values is not None and (not isinstance(values, dict) or "app" in values):
raise AgentError("values must be a settings object without app")
return fex_helper("settings_set" if values is not None else "settings_get",
dict(values or {}, app=args["app"]), timeout=60)
def cmd_fex_bench(args):
seconds = args.get("seconds", 120)
if type(seconds) is not int or not 1 <= seconds <= 120:
raise AgentError("seconds must be an integer in 1..120")
if game_running(): # includes Lepton containers even when their processes are in another PID namespace
raise AgentError("benchmark refused: a game or container is running")
app = args["app"]
for pkg in sorted(os.listdir(ANCHORS)) if os.path.isdir(ANCHORS) else []:
dep = deployment(pkg)
if dep and dep.get("kind") == "frame_fex" and dep.get("app") == app:
return fex_helper("bench", {"app": app, "seconds": seconds,
"launcher": os.path.join(ANCHORS, pkg, "launch.sh")},
timeout=seconds + 240) # + the wait for the game to start (START_WAIT)
raise AgentError("install this FEX game before benchmarking")
def fex_uninstall(pkg, dep, args):
"""Meta-owned games stay; FramePort local copies lose their game folder and manifests, preserving the prefix."""
anchor = os.path.join(ANCHORS, pkg)
if dep.get("source") == "local_copy":
fex_local_dest(dep.get("dest"))
fex_helper("unregister_local", {"app": dep["app"], "package": pkg}, timeout=180)
removed_sc = False
if args.get("remove_shortcut") and steam_users():
removed_sc = cmd_shortcuts({"remove": [{"exe": f'"{anchor}/launch.sh"', "appid": dep.get("appid")}]})["started"]
if args.get("remove_shortcut"):
try:
devkit_unregister(pkg, steam_running=run(["pgrep", "-x", "steam"]).returncode == 0)
except Exception: # noqa: BLE001 (the files go anyway at the next purge)
pass
remove_tree(anchor)
return {"removed": True, "kept_saves": True, "shortcut_removed": removed_sc}
COMMANDS = {n[4:]: f for n, f in globals().items() if n.startswith("cmd_")}
+40
View File
@@ -0,0 +1,40 @@
# Announcements
`current.md` is the one announcement FramePort shows as a pop-up in the app. Edit it on `main`: the app reads it
from GitHub `main` (raw.githubusercontent.com) at most every 6 hours, so a push reaches everyone without a release.
## Who sees it
- **Only people who already used FramePort before the announcement's `date`.** A new install never shows one, and
nor does an announcement published before FramePort was installed.
- **Once.** Closing it in any way (the X, a click outside it, Escape, or its button) dismisses it for good. The app
remembers dismissals in its settings (`announce.dismissed`).
- **A new announcement = a new `id`.** Fixing a typo with the same `id` doesn't show it again to anyone who closed it.
A new `id` shows to everyone who used FramePort before its `date`, whether they closed the earlier one or not.
## The file
```markdown
---
active: true # false = nothing is shown (the fields are still checked)
id: meetup-2026-11 # letters, digits, . _ - — change it for every new announcement
title: Steam Frame meetup on Discord # required
date: 2026-11-02T18:00:00Z # required: when it was published (UTC; a bare date = midnight UTC)
image: announcements/meetup.png # optional: a file in this folder, or an https URL (PNG, JPEG, WebP, GIF; ≤ 5 MiB)
image_alt: The meetup poster # optional: what the picture shows (screen readers)
button: Join the meetup # optional: an action button, with url
url: https://example.com/meetup
expires: 2026-11-30 # optional: not shown after this day (UTC, inclusive)
---
The body, in Markdown: **bold**, *italic*, `code`, [links](https://frameport.app/), lists, headings.
```
The body is Markdown (no HTML). A `date` in the future works as a schedule: nobody sees it before then.
Images look best at about 2:1 (e.g. 1200×600). The pop-up is 600 px wide and shows between 140 and 320 px of the
picture's height.
`pytest tests/test_announcements.py` checks this file, so a broken announcement fails CI instead of silently showing
nothing.
To turn announcements off for testing: `FRAMEPORT_NO_ANNOUNCEMENTS=1`.
+16
View File
@@ -0,0 +1,16 @@
---
# The announcement FramePort shows once (announcements/README.md). Switched off: set active: true.
active: false
id: example-2026-10
title: Example announcement
date: 2026-10-15T12:00:00Z
# image: announcements/example.png
# image_alt: What the picture shows
# button: Read more
# url: https://frameport.app/changelog/
# expires: 2026-11-30
---
This is where the text goes, in **Markdown**: *emphasis*, `code`, [links](https://frameport.app/) and lists.
- Keep it short: one or two paragraphs.
- Change `id` for every new announcement.
-9
View File
@@ -1,9 +0,0 @@
3e9099b5015e8f486c00bcea9d111ee721faba355a89bcf1df69561e3dc6325c ./digicert-assured-id-root-ca.der
e04db8044185c1c77941252e61794e84af7156c449fedcda4a826d7a9fc91989 ./dlls/crypt32.dll
ec1387fad1f9b65503077e5aa24e3a3b60b3b04b85fd9412e0f2c451772f9b25 ./dlls/dnsapi.dll
00ebfab0f3a066d9c85820332e0ec91cf4040797e580516dcafa048dfe758aa7 ./dlls/sechost.dll
41584c41db41991f20a0b55011efa94618e0817ab351579f793ca01dbb488a0e ./dlls/windows.devices.enumeration.dll
420b21045ddc4f166733bf6d2d7227f0131e20f161c4568accb2b9c15a6d8e86 ./fp_mem.so
f8d6aaaa123337c47837d0be5852f7f6687bb9c4bfaaa108aaab3f04af1ad5b9 ./fp_pipesend.exe
13d455b700b08f40eb3e3452ab264bf535cb3d176c92ec9a3324a635ce4f8588 ./windows.devices.wifi.dll
941a65274007db76b1c40880117fe7d881db32c5394ad09f80ccc44a08213a75 ./wineserver.arm64
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6
View File
@@ -7,8 +7,14 @@ xr: OpenXR
status: works
notes: Uses Meta XR Audio via FMOD (not covered by patch_meta_xr_audio); if audio is missing, that is the likely
cause.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 63fff470777f2753d55ad50f8355573ced8fa48bcaee0f5e6a0c10369f951a38
updated: '2026-10-15'
@@ -6,9 +6,15 @@ engine: Unity
xr: VrApi
status: issues
notes: Right eye distorts during movement (unresolved; swap, tracking, Valve layers, depth and pacing ruled out).
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Legacy VrApi via OVRPlugin; overport swaps in an OpenXR OVRPlugin. Do not remove VrApi.
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 192ff250f5fbec38b9c4e898f0b8408edc25901f46bb4b227f7ca60bbd9f0bba
updated: '2026-10-15'
@@ -6,9 +6,15 @@ engine: Unity
xr: OpenXR
status: works
notes: Needed the GLES/sRGB swapchain fallback.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Also available as a native PC SteamVR title.
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 158f7c4f5e8558029dc8cc5e8dcb4e67e846b261bf34e3e448fee7f657c74597
updated: '2026-10-15'
+20
View File
@@ -0,0 +1,20 @@
package: com.CreaTeam.Sclerosis
title: Sclerosis
status: works
notes: Copy the "Amnesia The Dark Descent" folder from a Windows/Proton install to "FramePort/com.CreaTeam.Sclerosis/lepton-data/external".
Default hand positions are rather askew and should be amended via VR Controller Mappings in Steam itself. FOV
warping effects are EXTREMELY disorienting in VR, beware. Otherwise seems to work without issue.
tested_version: 1.10.7
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-10-16'
known_good_sha256: e17421ad9894f5e57fb9b1b8110544715166756ef924b5a86831f6f20e70a6d5
app: 1.2.0
overport_cli: 1.2.5
issue: 339
source_hint: Sclerosis_v1.10.7
@@ -0,0 +1,24 @@
package: com.Curve.LawnMowingSimulatorVR
title: Lawn Mowing Simulator VR
status: issues
notes: Left eye textures flicker only when mowing in specific areas.
tested_version: 1.0.50
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
adapter:
haptic_fix: 1
pose_consistency: 1
hide_space_warp: 1
verified:
date: '2026-10-16'
known_good_sha256: 2653e9b1dfbd11d607b5dd17b9c07ab19d9e98e1004ef9b14cb52867b5f959dc
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 344
source_hint: com.Curve.LawnMowingSimulatorVR
@@ -0,0 +1,10 @@
package: com.FlatHeadStudio.DeadlyDelivery
title: Deadly Delivery
status: unsupported
notes: "Quits after Meta's entitlement check fails: it needs Meta's online services."
tested_version: 1.0.30
engine: Unity
xr: OpenXR
verified:
date: '2026-10-15'
issue: 322
@@ -6,8 +6,14 @@ engine: Unity
xr: OpenXR
status: works
notes: Recommended pilot title.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 2300f628ce04c1da60b52fed18335d6a31b88cc88313fd6d2c0e1a8e7785126f
updated: '2026-10-15'
@@ -0,0 +1,22 @@
package: com.HypetrainDigitalLtd.Breathedge
title: Breathedge VR
status: works
notes: Loading fade is broken and only shows a small square but the game works!
tested_version: 1.0.7
engine: Unreal
xr: VrApi
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.hw_video_decode
adapter:
haptic_fix: 1
verified:
date: '2026-10-16'
known_good_sha256: 4975a32fbf36b4d417142a944bf7d771c18a184dc0320b5937ac2c67bd013575
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 347
source_hint: Breathadge
@@ -5,9 +5,14 @@ source_hint: 'Sniper Elite VR- Winter Warrior'
engine: Unity
xr: OpenXR
status: works
notes: ''
notes: frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 6b8170da5826b9a35326a20967a0e5a242d46fb569a0a3c669e1cbd368102dd3
updated: '2026-10-15'
@@ -0,0 +1,28 @@
package: com.Miragesoft.RealVrFishingQ
title: Real VR Fishing
status: issues
notes: Seems to be almost 100% functional with meta permissions enabled. In the new Mixed Reality mode, the room
scan doesn't seem to do anything and I can't seem to manually place anything either.
tested_version: '3.06096'
engine: Unity
xr: OpenXR
frame:
- frame.vivox_audio_route
- frame.unity_text_input
- frame.oculusos
- frame.meta_permissions
device:
- device.text_input_window
adapter:
haptic_fix: 1
scene_emul: 1
controller_models: 1
verified:
date: '2026-10-16'
known_good_sha256: 8b17dd26ef0486618ec006f9d948a60dabea4d7763bbe6061db07ee8aad27c76
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 91
issue: 333
source_hint: Real VR Fishing
+5
View File
@@ -6,11 +6,14 @@ engine: Unity
xr: OpenXR
status: works
notes: Passthrough + Meta scene/room emulated from the Steam guardian (scene_emul=1).
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Mixed-reality-only; builds its level from the room model, which the adapter emulates from the Steam guardian.
overport_extra:
- patch_force_passthrough
adapter:
scene_emul: 1
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
@@ -18,3 +21,5 @@ verified:
known_good_sha256: 9f900fc86fbb2663abe83c82ab79cc72bbf1f93fea54f7583fd274dd07e3d09c
frame:
- frame.meta_permissions
- frame.unity_text_input
updated: '2026-10-15'
@@ -0,0 +1,22 @@
package: com.SchellGames.LostRecipes
title: Lost Recipes
status: works
tested_version: 1.0.1+273175
engine: Unreal
xr: VrApi
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.unreal_skip_obb_check
- frame.hw_video_decode
adapter:
haptic_fix: 1
verified:
date: '2026-10-16'
known_good_sha256: f071a1deea3e3b6dce0c3a923127f540a48b88532106536c1838f496e9d3e6c9
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 340
source_hint: Lost Recipes
@@ -6,12 +6,18 @@ engine: Unity
xr: OpenXR
status: issues
notes: Hand-tracking game; the Frame synthesizes hands from controllers, so it is janky.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Hand-tracking-only game; Steam Frame has no optical hand tracking. Built with controller_fix=0 so hand
data passes through if the runtime ever provides it.
adapter:
controller_fix: 0
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: a19b80db0c300d422cbba35a4924ab59211b39bcb6485e200d310e3e1372ddb7
updated: '2026-10-15'
+12 -10
View File
@@ -1,22 +1,24 @@
package: com.UNIVRS.Freedom
title: Freedom
status: issues
notes: Volume can't be changed in the game.
title: 'Attack on Titan VR: Unbreakable'
status: works
notes: Keep the extra files that come with the APK and OBB next to the OBB (they hold the audio). Cutscenes are
detached from the head but still viewable.
tested_version: 1.0.2950
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.asset_files
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-10'
known_good_sha256: 24662272c4cbe5dc7c4f3c803bdb9dead9661ac3d59bf80cca2e260256acc4bc
app: 0.12.0
date: '2026-10-16'
known_good_sha256: 1b3ced1a24b3b708f66aba6aa879863b667c0e502ef153d8a8cfa03e529d21fd
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 59
issue: 132
source_hint: AOT VR
frame_build: '20261015.6141207'
agent: 91
issue: 337
source_hint: Aot
+6 -1
View File
@@ -7,10 +7,15 @@ xr: OpenXR
status: works
notes: FrameBridge turns its upside-down UI panels upright (flip emulation, in place since FramePort 1.2.0). Ubisoft
login may not work.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Ubisoft online login may not work. Data folder holds raw assets (start0..2, .climb, bundles), not .obb
files; install to obb as-is.
overport_extra:
- patch_ac_nexus_no_appsw_90
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
@@ -18,5 +23,5 @@ verified:
known_good_sha256: 89644a12bf8df956fa3d3a9a40540ba9e1fb62f63494714a05c9f05984383ac8
no_appsw_90: '2026-10-02, OVRPort 1.2.5 (owner: 90 Hz felt better than 72 Hz; same known issues)'
flip_in_place: '2026-10-14, owner in the headset: launch warnings and tutorial pop-ups upright (GitHub #138)'
updated: '2026-10-14'
updated: '2026-10-15'
min_app: 1.2.0
+1 -1
View File
@@ -1,5 +1,5 @@
package: com.asg.clockworkdev
title: Clockwork
title: The Last Clockwinder
status: works
tested_version: '1.29'
engine: Unity
+5 -1
View File
@@ -2,6 +2,7 @@ package: com.camouflaj.manta
title: 'Batman: Arkham Shadow'
status: works
notes: Large data set (~27 GiB) incl. all language packs.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: 'Uses Meta XR Audio (Wwise), handled by patch_meta_xr_audio. Cutscenes are 8K HEVC panoramas: frame.hw_video_decode
decodes them on the Frame''s hardware, adapter.surface_native shows them in stereo (PRs #96, #128). Includes all
language packs (~28 GB). sync_guard (to test, GitHub #102) - a reporter''s game quit to Steam''s waiting screen
@@ -13,15 +14,18 @@ overport_extra:
- patch_disable_space_warp
frame:
- frame.hw_video_decode
- frame.unity_text_input
adapter:
sync_guard: 1
surface_native: 1
fade_quad: 1
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 796d1cab08f614d72c50d9702974c719c0908f5de91183cfe02d1fd5eb09551a
updated: '2026-10-13'
updated: '2026-10-15'
min_app: 1.1.0
source_hint: Batman- Arkham Shadow
@@ -6,9 +6,15 @@ engine: Unity
xr: OpenXR
status: works
notes: Co-op unavailable.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: 'Release notes: for DLC use an older version. Co-op likely unavailable.'
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 06428a6328a49b3ca769e070dd0d2bb55c2122c8fba5d07a69b1b206a532c212
updated: '2026-10-15'
+21
View File
@@ -0,0 +1,21 @@
package: com.crytek.climb
title: The Climb
status: works
tested_version: '666.0'
engine: CryEngine
xr: VrApi
frame:
- frame.vrapi_bridge
device_files:
user.cfg: 'r_vr_foveated = 0
'
verified:
date: '2026-10-16'
known_good_sha256: 3899967dd6d3ee0ce3409e94d543405c779e9c282ead29536abe93b3531ca285
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 341
source_hint: TheClimb
@@ -0,0 +1,22 @@
package: com.fasttravelgames.mascot
title: 'Cities: VR'
status: works
notes: Loading screen Cities VR Logo doesn't load right.
tested_version: 1.00.502
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-16'
known_good_sha256: 5537e4e9333a04eda8c1b2f96cdc9572c1bbed52a9d3af42269ba442ce9ba801
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 345
source_hint: CitiesSkylines
@@ -6,11 +6,17 @@ engine: Unity
xr: OpenXR
status: works
notes: Passthrough emulated with the Frame cameras (greyscale).
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Mixed-reality-only title; relies on passthrough (emulated).
overport_extra:
- patch_force_passthrough
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 65ca3a8f46cc9acfd268949418f9adeecb0cf9f59d11591ba95fe2ba9ea966d8
updated: '2026-10-15'
+8 -1
View File
@@ -2,10 +2,17 @@ package: com.nexxr.nexplayer
title: NEX Player
status: works
notes: 'Confirmed in the headset by the owner (2026-10-01): 72 fps, local 2D/360/3D videos play (it browses /sdcard/Movies
itself). USB-drive browsing can''t work in Lepton.'
itself). USB-drive browsing can''t work in Lepton. Typing (frame.unity_text_input + device.text_input_window,
owner in the headset 2026-10-15): SteamVR''s keyboard button works and typed text reaches the fields; the keyboard
doesn''t open by itself when a field is selected.'
tested_version: 1.3.1.0
frame:
- frame.unity_text_input
device:
- device.text_input_window
engine: Unity
xr: OpenXR
verified:
date: '2026-10-01'
source_hint: NEX - NEXt-Gen Video Player
updated: '2026-10-15'
@@ -0,0 +1,22 @@
package: com.s3d.ExplodingKittensVR.TestRelease
title: Exploding Kittens VR
status: issues
notes: Requires online for most modes. Practice lobby does work though.
tested_version: 1.4.25779
engine: Unreal
xr: OpenXR
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.hw_video_decode
adapter:
haptic_fix: 1
verified:
date: '2026-10-16'
known_good_sha256: 4b0a2348a5553851dcec820835e02c93a1a64927a30533d554943a9b81b3baa0
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 343
source_hint: com.s3d.ExplodingKittensVR.TestRelease
@@ -6,8 +6,14 @@ engine: Unity
xr: OpenXR
status: works
notes: Layers with failed swapchains are dropped by the adapter.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: c3f8cba1c22762231b6a6fbd881668db859d83224884ebeae0c1a3ba716f298c
updated: '2026-10-15'
@@ -6,9 +6,15 @@ engine: Unity
xr: OpenXR
status: works
notes: Use VR mode.
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
details: Has VR and MR modes; use VR mode (passthrough not forced).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: 5ba09a2bc0046c8cb587272ab81e8d32739334fef523b10ab26531a733d54f12
updated: '2026-10-15'
+24
View File
@@ -0,0 +1,24 @@
package: jp.co.hit_point.vneko
title: Neko Atsume Purrfect
status: works
tested_version: 2.3.0
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.oculusos
device:
- device.text_input_window
adapter:
controller_models: 1
haptic_fix: 1
scene_emul: 1
verified:
date: '2026-10-16'
known_good_sha256: da0196efa495d6ea7b34be2cea5b279acf23489134bb1dd1acef7cf54aa57da6
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261015.6141207'
agent: 91
issue: 338
source_hint: jp.co.hit_point.vneko
+18
View File
@@ -0,0 +1,18 @@
package: org.crisiszone.vr
title: Crisis Zone VR
status: works
notes: Played the beginning of the first mission without issues.
tested_version: 0.1.4
engine: Other
xr: OpenXR
frame:
- frame.sdl_clipboard
verified:
date: '2026-10-15'
known_good_sha256: 747d1e6613ae443ef03e509b509e4ec89039eec1aecf3689643db4057e53266a
app: 1.2.1.dev433
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 91
issue: 331
source_hint: CrisisZoneVR-v0.1.4-quest3
@@ -5,9 +5,14 @@ source_hint: Toy Master
engine: Unity
xr: OpenXR
status: works
notes: ''
notes: frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: e951595c67b6e448f3fb4afd07e6b83e98e589094bb3b73374cfb28aa01e96ee
updated: '2026-10-15'
@@ -7,6 +7,9 @@ xr: OpenXR
status: works
notes: Needs Oculus OS telemetry class stubs and the no-ForceQuit build (the normal build quits right after
starting).
frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
device:
- device.text_input_window
verified:
date: '2026-10-02' # owner-confirmed with the no-ForceQuit build
overport_cli: 1.2.3
@@ -14,6 +17,8 @@ verified:
known_good_sha256: 31469d50b8ee292597291db7cc3bc3eca8e851f533cd92bba0d64214893580cc
frame:
- frame.oculusos
- frame.unity_text_input
alt_overport:
- patch_remove_unreal_force_quit
use_alt: true
updated: '2026-10-15'
+6 -6
View File
@@ -1,9 +1,9 @@
package: xyz.TheAviary.Vermillion
title: Vermillion
status: issues
notes: Runs. The canvas used to hide the hand and brush while painting (the Frame draws the game's canvas layer in
front of everything); the recipe makes the game draw canvases in the scene instead (fix found by Klownicle, GitHub
#200). Not yet confirmed in the headset with this patch.
status: works
notes: "The canvas used to hide the hand and brush while painting (the Frame draws the game's canvas layer in front
of everything); the recipe makes the game draw canvases in the scene instead (fix found by Klownicle, GitHub #200).
Confirmed in the headset by Klownicle."
tested_version: 1.7.2
engine: Unity
xr: OpenXR
@@ -16,10 +16,10 @@ adapter:
haptic_fix: 1
scene_emul: 1
verified:
date: '2026-10-11'
date: '2026-10-15'
app: 1.0.1
frame_build: '20261007.6125817'
agent: 79
issue: 200
updated: '2026-10-12'
updated: '2026-10-15'
source_hint: Vermillion - VR Painting
+6 -1
View File
@@ -5,9 +5,14 @@ source_hint: H.U.N.T
engine: Unity
xr: OpenXR
status: works
notes: ''
notes: frame.unity_text_input and device.text_input_window added from detection (not headset-verified).
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: c35373d0f7c870ade148e3259abcc74098b6bc89fe2c2f3a2e55168df642e391
updated: '2026-10-15'
+17 -44
View File
@@ -6,55 +6,21 @@
# with diagnostics. Launch tests and real play sessions (agent session_log, `frameport session`) are both matched.
# Sources: every failure we hit porting 34 games to the Steam Frame (see docs/PLAYBOOK.md).
signatures:
# FEX Rift compatibility (stream C): PC runtime/renderer failures; never suggest entitlement workarounds.
- id: fex-missing-entitlement
kind: pcvr
pattern: '(?i:Missing entitlement)'
severity: info
diagnosis: Meta reports that the signed-in account does not own this game. This is not a FramePort bug. Use an account that owns it; entitlement and Platform SDK checks remain intact.
suggest: []
- id: fex-registration-missing
kind: pcvr
pattern: '(?i:OVRServer[^\r\n]*install_available|install_available[^\r\n]*OVRServer)'
severity: error
diagnosis: Meta's runtime sees the app as available to install rather than registered as installed. Reinstall or register the game through the FEX install flow with its matching Meta manifest, then retry.
suggest: []
- id: fex-imu-fallback
kind: pcvr
pattern: 'Rejecting new committed universe since IMU fallback is active'
severity: warning
diagnosis: SteamVR has not acquired headset tracking since boot. Put the headset on once, wait for tracking, then retry the FEX game. A headless launch before that can wait forever.
suggest: []
- id: fex-librarian-stuck
kind: pcvr
pattern: '(?s)\A(?=.*(?i:Service invocation completed))(?=.*OVRLibrarian[^\r\n]*(?i:still running|did not exit))'
severity: warning
diagnosis: OVRLibrarian completed its work but remains alive under FEX and blocks later client registration. End only OVRLibrarian.exe after completion, then retry; the FEX launcher normally performs this cleanup.
suggest: []
- id: fex-vkd3d-init
kind: pcvr
pattern: '(?i:vkd3d[^\r\n]*(?:failed to (?:create|initialize)|could not (?:create|initialize)|no (?:suitable|compatible).*(?:device|adapter)))'
severity: error
diagnosis: The D3D12 route could not initialize vkd3d-proton or a Vulkan device. Check GE's shipped vkd3d-proton DLLs, clear PROTON_NO_D3D12 and PROTON_USE_WINED3D, and verify the FEX Vulkan thunk reaches Turnip. This route still needs a device test.
suggest: []
- id: fex-wined3d-init
kind: pcvr
pattern: '(?i:wined3d[^\r\n]*(?:failed to (?:create|initialize|find)|could not (?:create|initialize)|OpenGL support is disabled))'
severity: error
diagnosis: Wine's OpenGL renderer could not initialize. The FEX route has no configured GL thunk; verify the guest rootfs GL driver and display access. A Vulkan thunk alone does not provide host OpenGL. Prefer the game's D3D9 or D3D11 route when available.
suggest: []
- id: fex-revive-injector
kind: pcvr
pattern: '(?i:ReviveInjector[^\r\n]*(?:failed|unable|error (?:code|inject)))'
severity: error
diagnosis: ReviveInjector could not start or inject the game. Check the game executable and x86_64 Revive files in the shared GE-Proton prefix, and use OpenVR mode (without /openxr). An OpenVR-only game can launch directly. Do not change entitlement or Platform SDK checks.
suggest: []
# End FEX Rift compatibility (stream C).
- id: meta-asset-status-error
pattern: 'Asset status error\s+\(code 100\)'
severity: error
diagnosis: A DLC manager reports a Meta asset-file status error after VR starts (e.g. PixelRipped 1995). The asset-file check failed; the log does not identify the native call or asset ID. Try the experimental asset-file bypass (empty list, installed status with no file path); this does not supply DLC and has not been verified in the game.
suggest: [frame.asset_files_stub]
- id: meta-entitlement
# Quest games (the pcvr oculus-entitlement signature covers Rift games). Only explicit failure results: a bare
# ovr_PlatformInitialize error isn't matched. `error`, not fatal: offline games may log it and play on; an online
# game that then quits (e.g. Deadly Delivery, GitHub #322) fails the test through its exit.
pattern: '(?i)entitlement check failed|\bnot entitled to (use|play)|ovrPlatformInitialize_(NotEntitled|UnableToVerify|FileInvalid|SignatureInvalid)'
severity: error
diagnosis: The game's Meta licence check (entitlement) failed. It needs Meta's online login and licence check,
which the Frame doesn't have; games that depend on it (often online games) quit or stay offline. FramePort
doesn't get around such checks.
suggest: []
- id: lua-lightuserdata-pointer
pattern: 'bad light userdata pointer'
severity: fatal
@@ -105,6 +71,13 @@ signatures:
severity: fatal
diagnosis: This app is a website, not a game, and it can't open on the Frame. It is a Trusted Web Activity that opens Meta's browser (com.oculus.browser), which the Frame doesn't have; open the website (TWALauncherActivity's "Using URL" line) in a browser instead.
suggest: []
- id: gvr-not-supported
# GitHub #335 (Blade Runner: Revelations, Daydream, Unity 2017.4): Unity's "Google VR Error [Daydream]", the GVR
# library's Java side missing on the 32-bit bridge, or a bind to Daydream's VrCore service
pattern: 'Google VR Error \[(Daydream|Cardboard)\]|Google VR had a fatal issue while loading|class com/google/vr/sdk/base/CardboardViewNativeImpl not found|act=com\.google\.vr\.vrcore\.\S+ pkg=com\.google\.vr\.vrcore'
severity: fatal
diagnosis: This is a Google Daydream / Cardboard VR build (Google VR SDK), and its VR can't reach the Frame's headset. Daydream needs Google's VR services (VrCore) and Cardboard draws for a phone in a viewer; FramePort has no translation for either, so the game runs as a flat window at best, usually without working controls. An Oculus build of the same game (Meta Quest, Oculus Go or Gear VR) goes through FramePort's normal path.
suggest: []
- id: unity-render-crash
pattern: 'CRASH\s*:.*#\d+\s+pc [0-9a-f]+\s+\S*libgallium_dri\.so'
severity: fatal
+32 -5
View File
@@ -13,11 +13,14 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Arkio | Quest | ✅ Works | |
| Asgard's Wrath 2 | Quest | ✅ Works | |
| Assassin's Creed Nexus | Quest | ✅ Works | |
| Attack on Titan VR: Unbreakable | Quest | ✅ Works | |
| Audica | Quest | ✅ Works | |
| AugmentedEmpire | Quest | ✅ Works | |
| BAM | Quest | ✅ Works | |
| BARTENDER VR SIMULATOR | Quest | ✅ Works | |
| Batman: Arkham Shadow | Quest | ✅ Works | |
| BattleGlide | Quest | ✅ Works | |
| Battlemarked | Quest | ✅ Works | |
| BattleSisters | Quest | ✅ Works | |
| Beat Saber | Quest | ✅ Works | |
| Beat Saber | Quest | ✅ Works | |
@@ -27,16 +30,19 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| BlazeRush | Quest | ✅ Works | |
| BodyCombat | Quest | ✅ Works | |
| BONELAB | Quest | ✅ Works | |
| Breathedge VR | Quest | ✅ Works | |
| Carve Snowboarding | Quest | ✅ Works | |
| Caves | Quest | ✅ Works | |
| Clockwork | Quest | ✅ Works | |
| Cities: VR | Quest | ✅ Works | |
| COMPOUND | Quest | ✅ Works | |
| Cook-Out | Quest | ✅ Works | |
| Cosmodread | Quest | ✅ Works | |
| Creed | Quest | ✅ Works | |
| Crisis Zone VR | Quest | ✅ Works | |
| cubism | Quest | ✅ Works | |
| Dance Central | Quest | ✅ Works | |
| Deep Cuts | Quest | ✅ Works | |
| Demeo | Quest | ✅ Works | |
| Demeter | Quest | ✅ Works | |
| Dinosaur Island | Quest | ✅ Works | |
| Doom3Quest | Quest | ✅ Works | |
@@ -46,10 +52,12 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Eleven Table Tennis | Quest | ✅ Works | |
| Eleven: Table Tennis VR | PC VR | ✅ Works | |
| Espire 2 | Quest | ✅ Works | |
| Eye of the Temple | Quest | ✅ Works | |
| FrenzyVR | Quest | ✅ Works | |
| Fruit Ninja | Quest | ✅ Works | |
| Fruit Salon | Quest | ✅ Works | |
| Genotype | Quest | ✅ Works | |
| Ghost Town | Quest | ✅ Works | |
| Ghostbusters: Rise of the Ghost Lord | Quest | ✅ Works | |
| GORN2 | Quest | ✅ Works | |
| Gravity Lab | Quest | ✅ Works | |
@@ -61,25 +69,33 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| In Death: Unchained | Quest | ✅ Works | |
| Into The Radius 2 | Quest | ✅ Works | |
| Job Simulator | Quest | ✅ Works | |
| Journey of the Gods | Quest | ✅ Works | |
| Jurassic World Aftermath Collection | Quest | ✅ Works | |
| Keep Talking and Nobody Explodes | Quest | ✅ Works | |
| Kill It With Fire VR | Quest | ✅ Works | |
| Ladder | Quest | ✅ Works | |
| Lambda1VR | Quest | ✅ Works | |
| LEGO® Bricktales | Quest | ✅ Works | |
| Lost Recipes | Quest | ✅ Works | |
| Lucky's Tale | Quest | ✅ Works | |
| Maestro | Quest | ✅ Works | |
| Marvel's Deadpool VR | Quest | ✅ Works | |
| Marvel's Iron Man VR | Quest | ✅ Works | |
| Max Mustard | Quest | ✅ Works | |
| Medieval Dynasty New Settlement | Quest | ✅ Works | |
| Metro Awakening | Quest | ✅ Works | |
| Mini Motor Racing X | Quest | ✅ Works | |
| Mobile Suit Gundam: Silver Phantom | Quest | ✅ Works | |
| Moss | Quest | ✅ Works | |
| Moss: Book II | Quest | ✅ Works | |
| Munkr Funkr (The Legacy Days) | Quest | ✅ Works | |
| Nano | Quest | ✅ Works | |
| Neko Atsume Purrfect | Quest | ✅ Works | |
| NEX Player | Quest | ✅ Works | |
| NFL PRO ERA II | Quest | ✅ Works | |
| NOPE CHALLENGE | Quest | ✅ Works | |
| Ocean Rift | Quest | ✅ Works | |
| Operation Wolf Returns: First Mission VR | Quest | ✅ Works | |
| palazzo_santacruz | Quest | ✅ Works | |
| Path of the Warrior | Quest | ✅ Works | |
| Pistol Whip | Quest | ✅ Works | |
@@ -97,9 +113,12 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Riven | Quest | ✅ Works | |
| Robo Recall | Quest | ✅ Works | |
| RUINSMAGUS | Quest | ✅ Works | |
| Sclerosis | Quest | ✅ Works | |
| Shadow Point | Quest | ✅ Works | |
| Shoot The Zombirds VR | Quest | ✅ Works | |
| Shores of Loci | Quest | ✅ Works | |
| SilentSlayer | Quest | ✅ Works | |
| Smash Drums | Quest | ✅ Works | |
| Sniper Elite VR | Quest | ✅ Works | |
| Sniper Elite VR: Winter Warrior | Quest | ✅ Works | |
| Space Pirate Trainer Quest | Quest | ✅ Works | |
@@ -112,9 +131,12 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| SUPERHOT VR | Quest | ✅ Works | |
| SynthRiders | Quest | ✅ Works | |
| Taskmaster | Quest | ✅ Works | |
| Tea For God | Quest | ✅ Works | |
| TetrisEffect | Quest | ✅ Works | |
| The Boys VR | Quest | ✅ Works | |
| The Climb | Quest | ✅ Works | |
| The Climb 2 | Quest | ✅ Works | |
| The Last Clockwinder | Quest | ✅ Works | |
| The Room VR | Quest | ✅ Works | |
| The Tale of Onogoro | Quest | ✅ Works | |
| Time Crisis II VR (Test) | Quest | ✅ Works | |
@@ -128,6 +150,8 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Vader Immortal: Episode II | Quest | ✅ Works | |
| Vader Immortal: Episode III | Quest | ✅ Works | |
| Vampire Survivors | Quest | ✅ Works | |
| Vendetta Forever | Quest | ✅ Works | |
| Vermillion | Quest | ✅ Works | |
| VR HOT Quest | Quest | ✅ Works | |
| VR4 | Quest | ✅ Works | |
| Walkabout Mini Golf | Quest | ✅ Works | |
@@ -141,26 +165,29 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Does it Stack? | Quest | ⚠️ Works with issues | Mixed reality mode does not work (works on Demeo), everything else seems to be OK |
| Dungeons of Eternity | Quest | ⚠️ Works with issues | It can not connect to servers |
| End Space | Quest | ⚠️ Works with issues | Controls stop responding after the first mission loads. |
| Exploding Kittens VR | Quest | ⚠️ Works with issues | Requires online for most modes. |
| ExploreVR | Quest | ⚠️ Works with issues | The 3D world warps and shifts with head movement (wrong perspective). |
| Fisherman | Quest | ⚠️ Works with issues | Loading screens have corruption, but everything works otherwise. |
| Freedom | Quest | ⚠️ Works with issues | Volume can't be changed in the game. |
| Homeworld: Vast Reaches | Quest | ⚠️ Works with issues | The game starts but after selecting to start a new game it seems to crash. |
| Lawn Mowing Simulator VR | Quest | ⚠️ Works with issues | Left eye textures flicker only when mowing in specific areas. |
| MacacoVR | Quest | ⚠️ Works with issues | 2d loading screens are glitchy, otherwise main gameplay is fine |
| Majora's Mask VR | Quest | ⚠️ Works with issues | Audio on the file select screen sounds crunchy. |
| Myst | Quest | ⚠️ Works with issues | Minor graphical glitches on some objects. |
| Phantom: Covert Ops | Quest | ⚠️ Works with issues | DLC/store button crashes (no Meta store). |
| Pinball FX VR | Quest | ⚠️ Works with issues | Plays; mixed reality mode not working yet. |
| Plezy | Quest | ⚠️ Works with issues | Some videos play with strong artifacts and wrong colours; the cause is unknown, possibly hardware video decoding. |
| Quantum Void | Quest | ⚠️ Works with issues | no hands |
| Ragnarock | Quest | ⚠️ Works with issues | |
| Real VR Fishing | Quest | ⚠️ Works with issues | Seems to be almost 100% functional with meta permissions enabled. |
| Silhouette | Quest | ⚠️ Works with issues | Hand-tracking game; the Frame synthesizes hands from controllers, so it is janky. |
| Spunky Dungeon | Quest | ⚠️ Works with issues | Gear VR / Oculus Go game (32-bit only), runs through FramePort's 32-bit bridge (experimental). |
| Swarm 2 | Quest | ⚠️ Works with issues | MSAA creates visible seams around edge geometry and also the skybox edge |
| The Light Brigade | Quest | ⚠️ Works with issues | Judder in weapons |
| The Thrill Of The Fight | Quest | ⚠️ Works with issues | Right eye doesn't draw the opponent or the referee. |
| Time Stall | Quest | ⚠️ Works with issues | Both eyes distort during movement (unresolved). |
| Vermillion | Quest | ⚠️ Works with issues | Runs. |
| WiiCompiled VR | Quest | ⚠️ Works with issues | To add a game: in FramePort's Files tab, upload your .wcgame file to this game's storage, folder Android/data/org.wiicompiled.quest/files/WiiCompiledOpenXRVR… |
| Deadly Delivery | Quest | ❌ Doesn't run | Quits after Meta's entitlement check fails: it needs Meta's online services. |
| Espire 1: VR Operative (Quest Edition) | Quest | ❌ Doesn't run | Mesa GL driver crash during texture upload. |
| GOLF+ | Quest | ❌ Doesn't run | Black screen. |
| HITMAN 3 VR: Reloaded | Quest | ❌ Doesn't run | Vulkan driver crash (freedreno), even without Valve layers. |
| Journey of the Gods | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
| Roblox | Quest | ❌ Doesn't run | Crashes on its first VR frame on the Frame. |
| Shadow Point | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
+83
View File
@@ -0,0 +1,83 @@
# Evaluating patch heuristics
`scripts/eval_heuristics.py` compares `engine.suggest(analysis, use_catalog=False)` with the bundled
`catalog/games/*.yaml` entries. It does not merge personal or remote catalog recipes into the benchmark.
It supports the original dumps command, or a precomputed `scripts/heuristics_snapshot.py` snapshot:
```sh
.venv/bin/python scripts/eval_heuristics.py '<dumps folder>' --verbose
.venv/bin/python scripts/eval_heuristics.py --snapshot analyses.json --split all --json baseline.json
.venv/bin/python scripts/eval_heuristics.py --snapshot analyses.json --fit-report --out fit-report.md
```
Use a scratch `FRAMEPORT_HOME`, `FRAMEPORT_NO_CATALOG_UPDATE=1`, and an empty `FRAMEPORT_WINDOWS_DATA` for offline
measurement. Snapshot mode reads no APKs or game data. Each snapshot read copies the source to a temporary file,
then parses the copy, retrying incomplete JSON. To compare multiple splits against an actively growing snapshot,
freeze one valid copy first and use that file for every run.
The default split is `dev`. `split_packages({package: analysis_engine})` sorts packages by SHA-256 within Unity,
Unreal, and Other strata, then holds out the nearest 20% (half rounded up). Pass only packages with both an analysis
and a catalog entry. The same input set always yields the same split regardless of iteration order; adding packages
can move the cutoff. Very small strata can have no holdout. Unsupported entries participate in splitting.
## What is scored
Ground truth contains catalog choices and patch registry defaults, with no inherited heuristic adapter settings.
Default expectations are determined per analysis, using each default patch's own detection in the same way as the
engine's initial heuristic pass. Thus a conditional default that is not detected (e.g. LTW on a game without LTW)
is not expected. Explicit catalog `overport_remove` and `frame_remove` entries remove expected defaults. An absent
expected default is represented as `remove:<patch id>`; enabled defaults do not inflate patch scores.
Opt-in overport/frame/device/PC VR IDs, default removals, adapter values, device-file names, foveation parameters,
and alternate-build patch IDs are compared. Alternate-build identities use `alt:<patch id>` so choosing one in a
fallback is distinct from choosing it in the primary build. Device-file content is not compared. Adapter values
must match: a wrong value contributes both an FP and an FN for `adapter.<key>`. Patch precision, recall and F1 are
micro-averaged across games; an empty denominator is reported as zero. Exact-game accuracy also compares the
unsupported status flag. Fields report matching games, including empty-field matches.
`RUNTIME_ONLY` lists choices excluded from the headline: `use_alt`, selected runtime adapter settings, Lepton
environment variables, and config-sync settings. They have their own exact, field and patch metrics. Catalog
entries with status `unsupported` are excluded from both headline and runtime supported-game metrics, and have
separate metrics and per-game diffs. Converted analyses are included and marked. JSON contains all metrics per
engine, all game signatures, split assignments, and missing/extra decisions.
## Dated score: catalog gaps vs. detection errors
The strict score treats the catalog as complete, but older entries were verified before many patches existed, and
a catalog recipe inherits every heuristic adapter setting and device patch (except `device.text_input_window`)
without listing them (`engine.suggest`), so the verified build had those. The dated score (`headline_dated`, printed
under "Dated") sets aside, on both sides:
- patches first committed after the entry's `verified.date` (the verifier couldn't have chosen them), and
- inherited adapter/device picks (`inherited_decisions`).
What remains are real disagreements: an extra on an entry verified after the patch existed, or a catalog choice
the heuristics don't make. Gaps are counted per patch ("Catalog gaps by patch"). The dated score needs the intro
date cache that `--fit-report` writes; without it only inherited picks are set aside.
Before tuning a rule to remove an "extra", check which kind it is: a gap on an old entry is a candidate for the
catalog (fit report), not a detection error. Before adding a patch to a working entry, weigh its benefit (does it
fix something the game hits?) against a rebuild prompt for everyone who installed it; adapter settings never need
adding (inherited). Results 2026-10-15: strict 5/65 exact, F1 73.8%; dated 39/65, F1 88.6% (dev 90.5%, holdout
79.5%). Remaining misses are one-game fixes found at runtime (e.g. Vader's gl_error_clear, BlazeRush's GL settings).
An evaluation writes JSON even when its headline has differences, then exits 1 for compatibility with the original
script. It exits 0 when exact, or after producing a fit report.
## New patch fit
The fit report covers all catalog entries, independently of `--split`. Candidates come from the final heuristic
recipe, preserving platform, flat-app, dependency, and 32-bit normalization rules. A candidate must also be opt-in,
applicable and recommended by its own `detect()`. Entries already listing or explicitly removing the patch are
excluded; a listed adapter key is excluded regardless of its value. This report proposes additions, not value edits.
Each candidate includes its reason, experimental/strict flags, first local git introduction date, catalog entry
date (`verified.date`; `updated` only without one, since it also moves for unrelated edits), and whether the
patch is newer. Unknown dates are marked unknown. Warnings
come from the full catalog recipe plus that one candidate; they may include pre-existing conflicts. Missing-analysis
entries appear as metadata-only rows. Intro dates, including unknown results, are cached in
`patch-intro-dates.json` beside the snapshot (or dumps folder); subsequent runs only query uncached patch IDs.
`tests/test_eval_heuristics.py` uses synthetic data. The opt-in real-dump test in `tests/test_games.py` ratchets the
supported all-split exact ratio and patch F1 against measured, rounded-down baseline constants. Machine-local
`.eval-home/` and `.eval-results/` scratch outputs are ignored by git.
+5
View File
@@ -167,6 +167,10 @@ FramePort downloads it, checks it, restarts and keeps your games and settings. *
- Settings → **Updates** turns the check off or turns on **Install updates automatically**.
- **Recipes** (the tested patches and settings for each game) update by themselves. A game whose recipe changed shows
**Update on Frame**.
- **A newer version of a game:** right-click it (or use **…** on its page) → **Update with a newer APK…** (Quest and
Android games) or **Update with a newer version…** (Linux apps: the new AppImage, archive or folder; PC VR games:
the new game folder). Its name, artwork, tags and your settings stay. Then click **Update on Frame** (or **on this
PC**).
- **Dev builds:** if you're asked to test a change before its release, use Settings → Updates → **Install the latest
dev build…**. The next release then arrives as a normal update.
@@ -255,6 +259,7 @@ option. The main ones:
|---|---|
| `scan <folder>` / `list` / `show <game>` | add games, list the library, show a game's patches |
| `add-linux <path> [--exe <program>]` | add a Linux app (AppImage, folder or archive) |
| `new-version <game> <path>` | point a game at its newer version (APK, Linux app file/folder, PC VR game folder) |
| `recipe <game> --enable/--disable <patch>` | change a game's patches (`patches` lists them all) |
| `build <game>` / `install <game>` / `test <game>` | build, install on the Frame (`--to pc` for this PC), launch test |
| `frame discover` / `frame connect` / `frame info` | find, connect to and describe the Frame |
+37 -36
View File
@@ -39,7 +39,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Patch Oculus detection for Unity](#patch_oculus_unity) | `patch_oculus_unity` | Patches from OVRPort | default |
| [Patch Oculus detection for Unreal](#patch_oculus_unreal) | `patch_oculus_unreal` | Patches from OVRPort | default |
| [Remove localized app names](#patch_remove_localized_names) | `patch_remove_localized_names` | Patches from OVRPort | default |
| [Remove Unreal's ForceQuit](#patch_remove_unreal_force_quit) | `patch_remove_unreal_force_quit` | Patches from OVRPort | 38 |
| [Remove Unreal's ForceQuit](#patch_remove_unreal_force_quit) | `patch_remove_unreal_force_quit` | Patches from OVRPort | 41 |
| [Remove uses-library](#patch_remove_uses_library) | `patch_remove_uses_library` | Patches from OVRPort | default |
| [Remove VrApi library](#patch_remove_vrapi) | `patch_remove_vrapi` | Patches from OVRPort | |
| [Replace application label and icon](#patch_replace_icon_label) | `patch_replace_icon_label` | Patches from OVRPort | default |
@@ -47,7 +47,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [VrApi → OpenXR adapter (OVRPort)](#patch_vrapi_openxr) | `patch_vrapi_openxr` | Patches from OVRPort | |
| [32-bit ARM bridge (Gear VR / Go games)](#frame-a32_bridge) | `frame.a32_bridge` | Steam Frame patches | 6 |
| [FrameBridge OpenXR adapter](#frame-adapter) | `frame.adapter` | Steam Frame patches | default |
| [Content files from the game's data](#frame-asset_files) | `frame.asset_files` | Steam Frame patches | 1 |
| [Content files from the game's data](#frame-asset_files) | `frame.asset_files` | Steam Frame patches | 2 |
| [Asset-file service bypass](#frame-asset_files_stub) | `frame.asset_files_stub` | Steam Frame patches | |
| [Skip Meta avatars](#frame-avatar_stub) | `frame.avatar_stub` | Steam Frame patches | 1 |
| [bHaptics: skip the Bluetooth permission request](#frame-bhaptics_permission) | `frame.bhaptics_permission` | Steam Frame patches | 5 |
@@ -56,22 +56,22 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [OpenGL ES: multiview shaders on flat panels (HUD, menus)](#frame-gl_multiview_fbo) | `frame.gl_multiview_fbo` | Steam Frame patches | 1 |
| [GL shim (Mesa GLSL compatibility)](#frame-gl_shim) | `frame.gl_shim` | Steam Frame patches | 2 |
| [Godot apps: start without a clipboard service](#frame-godot_clipboard) | `frame.godot_clipboard` | Steam Frame patches | |
| [Hardware video decoding (H.264, HEVC, VP9)](#frame-hw_video_decode) | `frame.hw_video_decode` | Steam Frame patches | 19 |
| [Hardware video decoding (H.264, HEVC, VP9)](#frame-hw_video_decode) | `frame.hw_video_decode` | Steam Frame patches | 22 |
| [Language packs from the game's files](#frame-langpacks) | `frame.langpacks` | Steam Frame patches | |
| [Launcher category (INFO → LAUNCHER)](#frame-launcher) | `frame.launcher` | Steam Frame patches | default |
| [GL wrapper: OpenGL ES depth formats (Minecraft)](#frame-ltw_depth) | `frame.ltw_depth` | Steam Frame patches | default |
| [Fix Lua startup crashes on Frame](#frame-luajit_pointers) | `frame.luajit_pointers` | Steam Frame patches | |
| [Declare Meta-only permissions](#frame-meta_permissions) | `frame.meta_permissions` | Steam Frame patches | 2 |
| [Declare Meta-only permissions](#frame-meta_permissions) | `frame.meta_permissions` | Steam Frame patches | 3 |
| [Meta XR Audio: skip Quest telemetry class](#frame-metaxr_telemetry) | `frame.metaxr_telemetry` | Steam Frame patches | default |
| [Clear android:debuggable](#frame-nodebug) | `frame.nodebug` | Steam Frame patches | 3 |
| [Oculus OS telemetry class stubs](#frame-oculusos) | `frame.oculusos` | Steam Frame patches | 15 |
| [Oculus OS telemetry class stubs](#frame-oculusos) | `frame.oculusos` | Steam Frame patches | 17 |
| [Fix crash when the game prepares the microphone](#frame-ovr_microphone) | `frame.ovr_microphone` | Steam Frame patches | |
| [Keep the same Meta user between starts](#frame-ovr_stable_user) | `frame.ovr_stable_user` | Steam Frame patches | default |
| [Trace Meta platform requests (diagnostics)](#frame-ovr_trace) | `frame.ovr_trace` | Steam Frame patches | |
| [Platform compat (ovrMessageType_ToString)](#frame-ovrplatformcompat) | `frame.ovrplatformcompat` | Steam Frame patches | default |
| [Stub missing Meta platform functions](#frame-ovrstubs) | `frame.ovrstubs` | Steam Frame patches | default |
| [Unpaired pointer-authentication checks](#frame-pac_hints) | `frame.pac_hints` | Steam Frame patches | 1 |
| [SDL apps: start without a clipboard service](#frame-sdl_clipboard) | `frame.sdl_clipboard` | Steam Frame patches | 4 |
| [SDL apps: start without a clipboard service](#frame-sdl_clipboard) | `frame.sdl_clipboard` | Steam Frame patches | 5 |
| [Stress Level Zero: let Unity start Vulkan itself](#frame-slz_vulkan_hooks) | `frame.slz_vulkan_hooks` | Steam Frame patches | 1 |
| [Start straight in VR (skip the 2D launcher)](#frame-start_activity) | `frame.start_activity` | Steam Frame patches | |
| [Allow swapchains larger than 4096 px](#frame-swapchain_limit) | `frame.swapchain_limit` | Steam Frame patches | default |
@@ -82,7 +82,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Unity: skip OVROverlay layers (fades, splash screens)](#frame-unity_no_overlay_copy) | `frame.unity_no_overlay_copy` | Steam Frame patches | 2 |
| [Unity: start VR without Meta's system apps](#frame-unity_oculus_check) | `frame.unity_oculus_check` | Steam Frame patches | 12 |
| [Unity: keep MSAA off at runtime (OVRManager)](#frame-unity_runtime_msaa_off) | `frame.unity_runtime_msaa_off` | Steam Frame patches | 28 |
| [Make Unity text fields work](#frame-unity_text_input) | `frame.unity_text_input` | Steam Frame patches | 85 |
| [Make Unity text fields work](#frame-unity_text_input) | `frame.unity_text_input` | Steam Frame patches | 107 |
| [Unity: share thread keys (games that run out of them)](#frame-unity_tls_key_pool) | `frame.unity_tls_key_pool` | Steam Frame patches | 1 |
| [Unity: headset always counts as worn](#frame-unity_user_presence) | `frame.unity_user_presence` | Steam Frame patches | 1 |
| [GL shim for Unreal (no multisampled render-to-texture)](#frame-unreal_gl_shim) | `frame.unreal_gl_shim` | Steam Frame patches | 1 |
@@ -90,21 +90,21 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Unreal: stand-ins for OVRPlugin functions OVRPort lacks](#frame-unreal_ovrp_entrypoints) | `frame.unreal_ovrp_entrypoints` | Steam Frame patches | 2 |
| [Unreal: Quest controller bindings (RPOC key map)](#frame-unreal_quest_keymap) | `frame.unreal_quest_keymap` | Steam Frame patches | 3 |
| [Unreal: don't wait for the Quest shader precompile](#frame-unreal_quest_precompile) | `frame.unreal_quest_precompile` | Steam Frame patches | 3 |
| [Unreal: start without the OBB check](#frame-unreal_skip_obb_check) | `frame.unreal_skip_obb_check` | Steam Frame patches | 5 |
| [Unreal: start without the OBB check](#frame-unreal_skip_obb_check) | `frame.unreal_skip_obb_check` | Steam Frame patches | 6 |
| [Unreal: skip the OBB delivery check](#frame-unreal_skip_obb_delivery) | `frame.unreal_skip_obb_delivery` | Steam Frame patches | 1 |
| [Unreal: bypass the stalled loading splash](#frame-unreal_splash_bypass) | `frame.unreal_splash_bypass` | Steam Frame patches | 1 |
| [Unreal: thumb follows the capacitive touches](#frame-unreal_thumb_touch) | `frame.unreal_thumb_touch` | Steam Frame patches | 7 |
| [Vermillion: paint canvases in the scene](#frame-vermillion_scene_canvas) | `frame.vermillion_scene_canvas` | Steam Frame patches | 1 |
| [Vivox voice chat: skip Android 12 audio routing](#frame-vivox_audio_route) | `frame.vivox_audio_route` | Steam Frame patches | 1 |
| [Vivox voice chat: skip Android 12 audio routing](#frame-vivox_audio_route) | `frame.vivox_audio_route` | Steam Frame patches | 2 |
| [Vulkan: drop invalid render-pass pointers](#frame-vk_sanitize) | `frame.vk_sanitize` | Steam Frame patches | default · 1 |
| [VrApi → OpenXR bridge](#frame-vrapi_bridge) | `frame.vrapi_bridge` | Steam Frame patches | 3 |
| [VrApi → OpenXR bridge](#frame-vrapi_bridge) | `frame.vrapi_bridge` | Steam Frame patches | 4 |
| [Quiet Meta's VrApi loader (OpenXR games)](#frame-vrapi_stub) | `frame.vrapi_stub` | Steam Frame patches | 2 |
| [OpenGL ES: shader fixes (Vulkan layer under Zink)](#frame-zink_shader_fix) | `frame.zink_shader_fix` | Steam Frame patches | 1 |
| [Pointer start](#adapter-aim_forward) | `adapter.aim_forward` | Game settings | |
| [Pointer angle](#adapter-aim_pitch) | `adapter.aim_pitch` | Game settings | |
| [Pointer turn](#adapter-aim_yaw) | `adapter.aim_yaw` | Game settings | |
| [Use controllers](#adapter-controller_fix) | `adapter.controller_fix` | Game settings | 1 |
| [Show Steam Frame controllers](#adapter-controller_models) | `adapter.controller_models` | Game settings | 4 |
| [Show Steam Frame controllers](#adapter-controller_models) | `adapter.controller_models` | Game settings | 6 |
| [Stand in for cube layers](#adapter-cube_standin) | `adapter.cube_standin` | Game settings | |
| [Show curved menus and screens](#adapter-cylinder_strips) | `adapter.cylinder_strips` | Game settings | |
| [Show 360° backgrounds and videos](#adapter-equirect_emul) | `adapter.equirect_emul` | Game settings | 5 |
@@ -127,9 +127,9 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [GL shim: high-precision vertex shaders](#adapter-gl_highp_markers) | `adapter.gl_highp_markers` | Game settings | 1 |
| [GL shim: integer vertex inputs](#adapter-gl_int_attribs) | `adapter.gl_int_attribs` | Game settings | 1 |
| [Flat panel diagnostics (log)](#adapter-gl_mv_debug) | `adapter.gl_mv_debug` | Game settings | |
| [Fix freezes when controllers vibrate](#adapter-haptic_fix) | `adapter.haptic_fix` | Game settings | 81 |
| [Fix freezes when controllers vibrate](#adapter-haptic_fix) | `adapter.haptic_fix` | Game settings | 88 |
| [Vibration strength](#adapter-haptic_scale) | `adapter.haptic_scale` | Game settings | |
| [Turn off space warp](#adapter-hide_space_warp) | `adapter.hide_space_warp` | Game settings | 4 |
| [Turn off space warp](#adapter-hide_space_warp) | `adapter.hide_space_warp` | Game settings | 5 |
| [Controller input diagnostics (log)](#adapter-input_diag) | `adapter.input_diag` | Game settings | |
| [Extra diagnostics (log)](#adapter-layer_debug) | `adapter.layer_debug` | Game settings | |
| [Drop broken layers](#adapter-layer_fix) | `adapter.layer_fix` | Game settings | |
@@ -137,7 +137,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Unity frame loop: wait for skipped frames](#adapter-ovrp_begin_gate) | `adapter.ovrp_begin_gate` | Game settings | 1 |
| [Steadier hands (older Unity)](#adapter-ovrp_hold_physics) | `adapter.ovrp_hold_physics` | Game settings | 1 |
| [See your room](#adapter-passthrough_emul) | `adapter.passthrough_emul` | Game settings | |
| [Steadier head tracking](#adapter-pose_consistency) | `adapter.pose_consistency` | Game settings | 1 |
| [Steadier head tracking](#adapter-pose_consistency) | `adapter.pose_consistency` | Game settings | 2 |
| [Pose timing diagnostics (log)](#adapter-pose_debug) | `adapter.pose_debug` | Game settings | |
| [Fix hands lagging behind controllers](#adapter-pose_time_fix) | `adapter.pose_time_fix` | Game settings | 14 |
| [Treat newer Quest controllers as Touch](#adapter-profile_remap) | `adapter.profile_remap` | Game settings | |
@@ -148,7 +148,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Re-create play space](#adapter-respace_kick) | `adapter.respace_kick` | Game settings | |
| [Sharpness](#adapter-scale) | `adapter.scale` | Game settings | 4 |
| [Room depth](#adapter-scene_depth) | `adapter.scene_depth` | Game settings | |
| [Pretend room layout](#adapter-scene_emul) | `adapter.scene_emul` | Game settings | 9 |
| [Pretend room layout](#adapter-scene_emul) | `adapter.scene_emul` | Game settings | 11 |
| [Room height](#adapter-scene_height) | `adapter.scene_height` | Game settings | |
| [Room width](#adapter-scene_width) | `adapter.scene_width` | Game settings | |
| [Eye-image snapshots (diagnostics)](#adapter-snapshot) | `adapter.snapshot` | Game settings | |
@@ -170,12 +170,12 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [OpenGL ES shader fixes](#adapter-zink_shader_fix) | `adapter.zink_shader_fix` | Game settings | 1 |
| [Keep the game's saved resolution in step](#device-config_sync) | `device.config_sync` | Files and settings on the Frame | 1 |
| [Show as VR or as a flat window](#device-display_mode) | `device.display_mode` | Files and settings on the Frame | |
| [Settings files for the game](#device-files) | `device.files` | Files and settings on the Frame | 2 |
| [Settings files for the game](#device-files) | `device.files` | Files and settings on the Frame | 3 |
| [Foveated rendering (Valve)](#device-foveation) | `device.foveation` | Files and settings on the Frame | 3 |
| [Hide Android's navigation bar](#device-hide_navbar) | `device.hide_navbar` | Files and settings on the Frame | |
| [Extra Lepton settings](#device-lepton_env) | `device.lepton_env` | Files and settings on the Frame | 3 |
| [Controllers as a gamepad (Steam Input)](#device-steam_gamepad) | `device.steam_gamepad` | Files and settings on the Frame | |
| [Show the app's Android window (for typing)](#device-text_input_window) | `device.text_input_window` | Files and settings on the Frame | 88 |
| [Show the app's Android window (for typing)](#device-text_input_window) | `device.text_input_window` | Files and settings on the Frame | 110 |
| [Launch options (SteamVR or OpenXR)](#pcvr-launch_args) | `pcvr.launch_args` | PC VR (Proton and Revive) | 2 |
| [Provide the Oculus runtime from Revive (Frame)](#pcvr-libovr_redirect) | `pcvr.libovr_redirect` | PC VR (Proton and Revive) | |
| [No Unreal crash reporter](#pcvr-no_crash_reporter) | `pcvr.no_crash_reporter` | PC VR (Proton and Revive) | |
@@ -420,7 +420,7 @@ Stops some Unreal games from closing themselves right after starting.
- `patch_remove_unreal_force_quit`
- **Changes:** Changes the APK (during the OVRPort conversion).
- **Offered (off):** Built as the alternate APK for Unreal games (use it if the game quits itself).
- **Catalog games (38):** Asgard's Wrath 2, BARTENDER VR SIMULATOR, Carve Snowboarding, Creed, Dance Central, Espire 1: VR Operative (Quest Edition), Espire 2, ExploreVR and 30 more.
- **Catalog games (41):** Asgard's Wrath 2, BARTENDER VR SIMULATOR, Breathedge VR, Carve Snowboarding, Creed, Dance Central, Espire 1: VR Operative (Quest Edition), Espire 2 and 33 more.
- **Suggested by launch-test signatures:**
- `force-quit` (error): The game quit itself right after starting.
- **Source:** [patches/overport.py](../src/frameport/patches/overport.py)
@@ -526,7 +526,7 @@ Lets the game find extra content it keeps next to its data (for example Star War
- `frame.asset_files`
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** The game asks Meta's platform for asset files and its data has … content file(s) (*.pak) that OVRPort's loader doesn't report.
- **Catalog games (1):** Star Wars: Tales from the Galaxy's Edge.
- **Catalog games (2):** Attack on Titan VR: Unbreakable, Star Wars: Tales from the Galaxy's Edge.
- **Source:** [patches/frame/langpack.py](../src/frameport/patches/frame/langpack.py)
> Some games keep content in separate files next to their OBB (for example Star Wars: Tales from the Galaxy's Edge: its seasons and sound banks) and ask Meta's platform for them as asset files. OVRPort's platform loader doesn't know them, so the game waits for content that never arrives (black screen after loading). Lists the content files shipped with the game's data (*.pak) as installed and answers their download request at once with the file's path; nothing is copied or downloaded. Shares the language-pack library.
@@ -645,7 +645,7 @@ Plays the game's videos on the Frame's video hardware, so 4K and 8K video runs s
- `frame.hw_video_decode` · also for 2D apps
- **Changes:** Install only: written on the Frame when the game is installed; the APK isn't changed.
- **Suggested (on):** The game plays video through Android's decoders (MediaCodec, ExoPlayer or VLC): decode it on the Frame's hardware.
- **Catalog games (19):** 4XVR Video Player, AugmentedEmpire, Batman: Arkham Shadow, Battlemarked, Dance Central, Eye of the Temple, Fruit Ninja, Ghost Town and 11 more.
- **Catalog games (22):** 4XVR Video Player, AugmentedEmpire, Batman: Arkham Shadow, Battlemarked, Breathedge VR, Dance Central, Exploding Kittens VR, Eye of the Temple and 14 more.
- **Source:** [patches/frame/hw_video_decode.py](../src/frameport/patches/frame/hw_video_decode.py)
> Decodes the game's videos on the Frame's hardware video decoder instead of Android's software decoders, which stutter or fall behind with 4K/8K video (for example video players, Batman: Arkham Shadow's cutscenes). Adds FramePort's codec plugin (OMX.frameport.avc/hevc/vp9.decoder) to this game's container only; the APK isn't changed. When the hardware is busy (for example Steam's own hardware video decoding is on) the video is decoded in software as before.
@@ -706,7 +706,7 @@ Declares Meta's permissions some mixed-reality games ask for, so they don't stop
- `frame.meta_permissions`
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Mixed-reality game that needs the room model: its 'use spatial data' permission must be granted (for example Demeter).
- **Catalog games (2):** Arkio, Demeter.
- **Catalog games (3):** Arkio, Demeter, Real VR Fishing.
- **Source:** [patches/frame/manifest_fixes.py](../src/frameport/patches/frame/manifest_fixes.py)
> Declares com.oculus.permission.* / horizonos.permission.* that the app uses, so Android grants them at install (for example the 'use spatial data' permission of mixed-reality games like Demeter).
@@ -749,7 +749,7 @@ Provides stand-ins for Quest system calls some games make at start.
- **Suggested (on):** The Unreal build of Meta XR Audio looks up com.oculus.os.AnalyticsEvent and aborts without it (for example NOPE Challenge).
- **Suggested (on):** Several Meta SDK libraries look up com.oculus.os.AnalyticsEvent (…); games like this abort without the stub (for example Nano).
- **Offered (off):** … references com.oculus.os.AnalyticsEvent; usually harmless (for example Batman: Arkham Shadow and LEGO Bricktales run without it). Enable if the game aborts with ClassNotFoundException.
- **Catalog games (15):** AgeOfJoy, AllInOneSports, Caves, Deep Cuts, Does it Stack?, Nano, NOPE CHALLENGE, RC Pilot Trainer and 7 more.
- **Catalog games (17):** AgeOfJoy, AllInOneSports, Caves, Deep Cuts, Does it Stack?, Nano, Neko Atsume Purrfect, NOPE CHALLENGE and 9 more.
- **Suggested by launch-test signatures:**
- `oculus-os-class` (fatal): The game looks up a Quest-only system class and aborts.
- **Source:** [patches/frame/telemetry.py](../src/frameport/patches/frame/telemetry.py)
@@ -838,7 +838,7 @@ Lets SDL and LÖVE games start on the Frame (they'd crash looking for a clipboar
- `frame.sdl_clipboard` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** SDL app: it crashes at start in Lepton, which has no clipboard service.
- **Catalog games (4):** Majora's Mask VR, Time Crisis II VR (Test), Time Crisis VR (Experimental), WiiCompiled VR.
- **Catalog games (5):** Crisis Zone VR, Majora's Mask VR, Time Crisis II VR (Test), Time Crisis VR (Experimental), WiiCompiled VR.
- **Suggested by launch-test signatures:**
- `sdl-no-clipboard` (fatal): The app crashed at start because the Frame's Android has no clipboard.
- **Source:** [patches/frame/sdl_clipboard.py](../src/frameport/patches/frame/sdl_clipboard.py)
@@ -904,7 +904,7 @@ Stops a gray or frozen screen in Unity games that turn on anti-aliasing while ru
- `frame.unity_gl_shim`
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity GLES game that may switch to MSAA at runtime: hide multisampled render-to-texture, which crashes the Frame's GL driver (for example The Room VR).
- **Catalog games (23):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 15 more.
- **Catalog games (23):** Audica, BattleSisters, Beat Saber, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight, End Space and 15 more.
- **Suggested by launch-test signatures:**
- `unreal-msrtt-crash` (fatal): The game's graphics crashed a few seconds after start.
- **Source:** [patches/frame/vrapi_bridge.py](../src/frameport/patches/frame/vrapi_bridge.py)
@@ -973,7 +973,7 @@ Keeps a smoothing setting off that the game turns on itself and that can freeze
- `frame.unity_runtime_msaa_off` · revision 2
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** GLES Unity game whose OVRManager turns 4x MSAA on at runtime: multisampled render-to-texture can hang the Frame's GPU.
- **Catalog games (28):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 20 more.
- **Catalog games (28):** Audica, BattleSisters, Beat Saber, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight, End Space and 20 more.
- **Suggested by launch-test signatures:**
- `unity-render-crash` (fatal): The game's graphics crashed, so the picture freezes or stays gray.
- `unity-runtime-msaa` (info): The game turns MSAA on at runtime, which can hang the Frame's GPU.
@@ -989,7 +989,7 @@ Lets you type into this app's text fields on the Frame (they'd close at once).
- `frame.unity_text_input` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity app with text fields (…): they close at once on the Frame because it has no system keyboard.
- **Catalog games (85):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, AugmentedEmpire, Battlemarked, BattleSisters and 77 more.
- **Catalog games (107):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arcsmith, Arkio, Assassin's Creed Nexus, Attack on Titan VR: Unbreakable, Audica and 99 more.
- **Source:** [patches/frame/unity_text_input.py](../src/frameport/patches/frame/unity_text_input.py)
> Unity's TMP_InputField / InputField wait for Android's on-screen keyboard and close themselves a frame later when there is none (Lepton has no on-screen keyboard; Meta's system keyboard does this on a Quest), so a selected text field only flashes a caret. Rewrites TouchScreenKeyboardShouldBeUsed -&gt; false and isKeyboardUsingEvents (TMP) / InPlaceEditing (uGUI) -&gt; true in libil2cpp.so, found per game with Cpp2IL (downloaded on first use), so fields stay selected and take key presses: Steam's keyboard (with "Show the app window") or Type on Frame from the PC.
@@ -1000,6 +1000,7 @@ Lets Unity 6 games with many native libraries start when they run out of thread
- `frame.unity_tls_key_pool` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity 6 with Firebase Firestore and Gecko: these native runtimes can exhaust Android's 128 thread keys alongside the Frame's graphics and XR libraries. Pool Unity's keys to leave room for them.
- **Offered (off):** Unity 6 with …: turn on if the game aborts at start with "cannot create thread specific key" (for example Wander).
- **Catalog games (1):** Wander.
- **Suggested by launch-test signatures:**
@@ -1091,7 +1092,7 @@ Starts Unreal games without re-checking their data file (they'd seem to hang on
- `frame.unreal_skip_obb_check` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unreal checks the OBB's contents before starting (bVerifyOBBOnStartUp); on the Frame a failed or slow check can't be seen and the game seems to hang.
- **Catalog games (5):** Dance Central, Kill It With Fire VR, MacacoVR, Maestro, Ragnarock.
- **Catalog games (6):** Dance Central, Kill It With Fire VR, Lost Recipes, MacacoVR, Maestro, Ragnarock.
- **Suggested by launch-test signatures:**
- `unreal-obb-check-stuck` (fatal): The game stays on Unreal's OBB check screen (DownloaderActivity), which the Frame doesn't show, and never starts VR (for example Contractors, GitHub #159).
- **Source:** [patches/frame/unreal_obb_check.py](../src/frameport/patches/frame/unreal_obb_check.py)
@@ -1157,7 +1158,7 @@ Lets games with Vivox voice chat start on the Frame (they'd crash on an Android
- `frame.vivox_audio_route` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Vivox voice chat: it calls Android 12 audio methods, which Lepton (Android 11) lacks, and crashes.
- **Catalog games (1):** Dungeons of Eternity.
- **Catalog games (2):** Dungeons of Eternity, Real VR Fishing.
- **Suggested by launch-test signatures:**
- `vivox-api31` (fatal): The game's Vivox voice-chat SDK calls Android 12 audio-routing methods (AudioManager communication devices) without checking the Android version; Lepton runs Android 11, so the app crashes (for example Green Hell VR).
- **Source:** [patches/frame/vivox_audio_route.py](../src/frameport/patches/frame/vivox_audio_route.py)
@@ -1188,7 +1189,7 @@ Lets games built on Meta's oldest VR interface run on the Frame.
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** The engine calls libvrapi.so directly; OVRPort can't translate it.
- **Conflicts with:** [`frame.vrapi_stub`](#frame-vrapi_stub)
- **Catalog games (3):** BlazeRush, Path of the Warrior, The Climb 2.
- **Catalog games (4):** BlazeRush, Path of the Warrior, The Climb, The Climb 2.
- **Suggested by launch-test signatures:**
- `direct-vrapi` (warning): The game uses Meta's VrApi directly and needs the VrApi bridge.
- `vrapi-frame-rejected` (fatal): The VrApi bridge rejected the game's frame options, so no picture reaches the headset even though frame pacing can appear in the log.
@@ -1294,7 +1295,7 @@ For games that show the headset's own controllers. Takes effect after a reinstal
- **Options:**
- Value: int, default `0`.
- Game settings → Controllers → "Show Steam Frame controllers".
- **Catalog games (4):** Ocean Rift, SynthRiders, VR HOT Quest, Walkabout Mini Golf.
- **Catalog games (6):** Neko Atsume Purrfect, Ocean Rift, Real VR Fishing, SynthRiders, VR HOT Quest, Walkabout Mini Golf.
- **Suggested by launch-test signatures:**
- `render-model-requested` (info): The game shows Quest controllers (or none) because the Frame doesn't provide controller models.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
@@ -1632,7 +1633,7 @@ For games that freeze the Frame when a controller vibrates (for example Lucky's
- **Options:**
- Value: int, default `0`.
- Game settings → Controllers → "Fix freezes when controllers vibrate" (advanced).
- **Catalog games (81):** AgeOfJoy, Ancient_Dungeon, Audica, AugmentedEmpire, Battlemarked, BattleSisters, Beat Saber, Caves and 73 more.
- **Catalog games (88):** AgeOfJoy, Ancient_Dungeon, Attack on Titan VR: Unbreakable, Audica, AugmentedEmpire, Battlemarked, BattleSisters, Beat Saber and 80 more.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Routes OVRPlugin through FramePort's extension shim, which turns Meta's amplitude-envelope vibrations into plain ones: OVRPort's loader reads their nanosecond duration as seconds and allocates gigabytes, freezing the Frame when the game vibrates a controller (for example Lucky's Tale's save slots, GitHub #9). Needs a rebuild.
@@ -1661,7 +1662,7 @@ For games whose picture flickers or smears (for example Into The Radius 2).
- **Options:**
- Value: int, default `0`.
- Game settings → Troubleshooting → "Turn off space warp" (advanced).
- **Catalog games (4):** Into The Radius 2, Metro Awakening, Pinball FX VR, The Boys VR.
- **Catalog games (5):** Into The Radius 2, Lawn Mowing Simulator VR, Metro Awakening, Pinball FX VR, The Boys VR.
- **Suggested by launch-test signatures:**
- `space-warp-used` (info): The game uses Meta's space warp (it renders half of its frames plus motion vectors, and the runtime makes up the rest).
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
@@ -1780,7 +1781,7 @@ For games that judder or shimmer while you hold your head still (for example I A
- **Options:**
- Value: int, default `0`.
- Game settings → Picture → "Steadier head tracking" (advanced).
- **Catalog games (1):** I Am Cat.
- **Catalog games (2):** I Am Cat, Lawn Mowing Simulator VR.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Repeat xrLocateViews queries for the same display time get the first, fully tracked answer again. Games that ask several times per frame got slightly different poses and rendered parts of the frame with different heads: judder (for example I Am Cat; proposed by Klownicle, GitHub #8).
@@ -1940,7 +1941,7 @@ Mixed-reality games that build their level from your room get a simple room with
- **Options:**
- Value: int, default `0`.
- Game settings → Mixed reality → "Pretend room layout".
- **Catalog games (9):** Arkio, AugmentedEmpire, Battlemarked, Demeo, Demeter, Ghostbusters: Rise of the Ghost Lord, Ocean Rift, Smash Drums and 1 more.
- **Catalog games (11):** Arkio, AugmentedEmpire, Battlemarked, Demeo, Demeter, Ghostbusters: Rise of the Ghost Lord, Neko Atsume Purrfect, Ocean Rift and 3 more.
- **Suggested by launch-test signatures:**
- `scene-missing` (warning): The game wants Meta's room data (scene API), which the Frame lacks.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
@@ -2271,7 +2272,7 @@ Puts settings files next to the game on the Frame, for example to turn off an un
- **Changes:** Install only: written on the Frame when the game is installed; the APK isn't changed.
- **Suggested (on):** CryEngine: variable-rate shading isn't supported on the Frame, so user.cfg turns it off (… = 0; The Climb / The Climb 2).
- **Options:** `files`: text, default none — path relative to files/ -&gt; content
- **Catalog games (2):** SUPERHOT VR, The Climb 2.
- **Catalog games (3):** SUPERHOT VR, The Climb, The Climb 2.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Writes config files into the game's Android/data/&lt;package&gt;/files/ on the Frame, to turn off engine features the Frame doesn't support (for example a CryEngine user.cfg with r_variable_rate_shading = 0, as The Climb 2 needs).
@@ -2334,7 +2335,7 @@ Lets typing reach this app from Steam's on-screen keyboard or your PC's keyboard
- `device.text_input_window`
- **Changes:** Install only: written on the Frame when the game is installed; the APK isn't changed.
- **Suggested (on):** App with text fields: key presses only reach a shown Android window.
- **Catalog games (88):** AFFECTED: The Manor, AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, AugmentedEmpire, Battlemarked and 80 more.
- **Catalog games (110):** AFFECTED: The Manor, AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arcsmith, Arkio, Assassin's Creed Nexus, Attack on Titan VR: Unbreakable and 102 more.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Lepton runs VR apps headless: their Android window is never shown, so it never gets keyboard focus and no key press (Steam's on-screen keyboard, a USB/Bluetooth keyboard, Type on Frame) reaches the app's text fields. With Lepton's lepton-show-flatscreen marker the window is shown (behind the VR view, which keeps working) and Steam's keyboard opens for a selected text field. Steam lists the shown window as "Gamescope" (the Frame's compositor). Pairs with "Make Unity text fields work without a system keyboard".
+4 -16
View File
@@ -24,6 +24,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| A Unity OpenXR game closes right after the OpenXR instance is created: `F VrApiLoader: vrapi_SetPropertyInt was called before vrapi_Initialize()!`, SIGABRT on UnityMain (GitHub #62, Jurassic World Aftermath) | the APK still ships Meta's VrApi loader; OVRPlugin (1.89, on OpenXR) calls it without starting VrApi and Meta's loader aborts. The VrApi bridge can't replace it (39 of the loader's 114 functions: OVRPlugin wouldn't link) | `frame.vrapi_stub` (same exports, each returns 0); triage `vrapi-before-init` |
| A VrApi game exits at once: `UnsatisfiedLinkError … dlopen failed: cannot locate symbol "vrapi_PollEvent"` (GitHub #57, BlazeRush) | the engine imports a VrApi function the VrApi bridge didn't implement | the bridge has `vrapi_PollEvent`, `RecenterPose`, `SetDisplayRefreshRate`, `GetSystemPropertyFloatArray` (rebuild the game); the static check "VrApi functions resolvable" names any other missing one; triage `vrapi-symbol-missing` |
| A Team Beef port (Lambda1VR, RTCWQuest, …) exits at once: `UnsatisfiedLinkError: dlopen failed: library "libopenxr_loader_valve.so" not found` (GitHub #59) | TBXR loads `openxr_loader_<Build.MANUFACTURER>` (Lepton: valve) and takes the Meta path only when `strstr(OPENXR_HMD, "meta")` matches, else Pico's | `frame.tbxr_vendor` (empty `libopenxr_loader_valve.so` + the "meta" literal → "alve"). Game data (`xash/`, …) goes to /sdcard: upload it with the Files tab to the game's storage. Black eyes with `TBXR: Incomplete frame buffer object: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE`: TBXR always uses multisampled render-to-texture (even `--msaa 1`); `frame.tbxr_vendor` links the GL shim, which hands it single-sampled versions (log `GL shim: multisampled render-to-texture … drawn single-sampled`) |
| A Quest game renders, then logs `Entitlement check failed` / `ovrPlatformInitialize_NotEntitled` (often with retries) and quits, e.g. `SIG: 9` after `[Photon] Disconnected` (GitHub #322, Deadly Delivery) | The game's Meta licence check (entitlement) needs Meta's online login, which the Frame doesn't have; online-only games quit (triage `meta-entitlement`) | None: FramePort doesn't get around entitlement checks. Offline games that log it and play on are fine |
| Black screen after VR starts; `Asset status error (code 100)` in `DLC_Manager:AssetStatusCallback` (GitHub #203, e.g. PixelRipped 1995) | Meta asset-file status fails after entitlement succeeds; the log does not identify the native call or asset ID | Try `frame.asset_files_stub` (opt-in, triage-only): native/langpack answers GetList with an empty successful list and StatusById with installed status, an empty path and the requested ID. No DLC files are supplied; download requests retain their existing behavior. Disable with `FRAMEPORT_ASSET_FILES_STUB=0`. Host-tested only; whether this fixes startup needs a game/device test |
| Missing sound or extra content in a game whose OBB folder has separate `*.pak` files (GitHub #61, Star Wars: Tales from the Galaxy's Edge: seasons + Wwise banks) | the game asks Meta's platform for these asset files (`ovr_AssetFile_GetList` / `DownloadById`); OVRPort's loader doesn't list them | copy every content/sound-bank PAK and use `frame.asset_files` (native/langpack lists the data's `*.pak` as installed `default` assets, IAP `free`, and answers DownloadById at once with the path; off: env FRAMEPORT_ASSET_FILES=0). Tales also needs the splash and depth-size fixes below |
| A SideQuest backup has `apk/` and a sibling `obb/` with content/sound-bank PAKs, but the Frame only has the main OBB (GitHub #61, Tales from the Galaxy's Edge) | older scans treated that layout as loose expansion files and selected only the named OBBs; the asset-file patch then found no PAKs | the scanner chooses the OBB folder by version first, then keeps the whole sibling data folder when all its expansion files are selected for this APK; app updates repair affected library entries and refresh asset/language-pack detection. Reinstall to copy the missing files, or scan the backup again first. Folders with other packages or unselected OBB versions still send only the selected OBBs |
@@ -62,6 +63,8 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| Un-cracked Oculus PC VR game: "Initializing OVR session" then exits / signature check on the runtime | Revive's hooks don't install on Proton-arm64; the Oculus shim rejects the unsigned Revive runtime | Not runnable on the Frame without the repack's crack extracted (not done by FramePort); use the PC version |
| PC VR game: `Failed to initialize Oculus API (-3001)` / `Unable to load LibOVRRT DLL` | Revive's LoadLibrary hook doesn't work under Proton arm64 (ARM64EC kernelbase); the game's LibOVR shim finds no runtime DLL | Symlink `LibOVRRT64_1.dll` → Revive's DLL in the prefix's system32 (manual so far) → then -3021 (runtime signature check; open) |
| Uploads to the Frame are slow | The link, storage or transfer backend can limit throughput | Check the job's "Transfer link"; try the Frame's hotspot or USB cable. Large install files prefer system OpenSSH SFTP, retaining paired-host checks and `.part` resume; unavailable or failed native uploads fall back to Paramiko. The log names the backend. Settings → Installing → Parallel uploads accepts 1–8 (default 3; saved preferences are preserved). More is not always faster. Measure the production path with `scripts/upload_bench.py --methods app-files-3 --check-resume` (three repetitions, checksum verification) |
| Log: `OpenSSH SFTP failed (255): … Permission denied (publickey,password)`, then Paramiko | OpenSSH offered keys the Frame doesn't authorize (GitHub #242) | The log lists the keys OpenSSH offered (`Offering public key`) and its warnings. A connection that logged in with the PC's own keys/agent makes OpenSSH use them too (copies of `~/.ssh/id_*` + the agent); a refused FramePort key is retried that way once. A Frame that accepts only another key file: Settings → Installing → SSH keys (CLI `frameport frame ssh-keys --add <file>`); passphrase keys go through the SSH agent |
| Log: `OpenSSH SFTP failed (1): stat C://…/[…: No such file or directory` | sftp got glob escapes inside its quotes (GitHub #324, fixed): `[` in a local folder name | Update FramePort; the native_upload `quote()` passes only `\\` and `\"` escapes, Windows paths with `/` |
| PC VR game exits right away: `Unhandled Exception: 0xc06d007e` (after `FOnlineSubsystemOculus::InitWithWindowsPlatform`) | Delay-loaded `LibOVRPlatform64_1.dll` (Oculus Platform SDK, installed with the Oculus app) is missing | None on the Frame (entitlement check; FramePort doesn't replace it). PC mode with the Oculus app |
| Unity PC VR game (Oculus + SteamVR build: `OVRPlugin.dll` and `openvr_api.dll` in `<Name>_Data/Plugins`) opens a window and quits after ~20 s; no VR Vulkan instance after the game's DXVK device in launch.log; Unity log (`unity log … Player.log`, agent v67): `OpenVR failed initialization` / `Initialization of device … failed` | Unity's built-in VR tries its SDKs in list order (Oculus first) unless `-vrmode` picks one; a catalog recipe verified with another build of the game (for example SUPERHOT VR's OpenXR build, GitHub #105) used to drop the build's own arguments | `pcvr.launch_args` = `-vrmode OpenVR` (detected for such builds; kept when the catalog's `xr` differs from the build's). A game's Electron launcher next to it (SHVR.exe) is ranked below the game |
| Unreal PC VR game opens the crash reporter instead of closing | UE starts CrashReportClient.exe on a crash | `pcvr.no_crash_reporter` (default for Unreal Rift games): `-nocrashreports` + CrashReportClient.exe renamed `.disabled` in the Frame copy |
@@ -84,6 +87,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| 32-bit Unity game on the bridge: player stands in the floor (Spunky Dungeon) | Unity's floor-level tracking origin: `vrapi_SetTrackingSpace(1)` (LOCAL_FLOOR) was ignored | The VrApi bridge puts the origin on the STAGE floor for LOCAL_FLOOR/STAGE |
| Crash at start: `NoClassDefFoundError: … Landroid/window/OnBackInvokedCallback;` or `NoSuchMethodError: No static method storeStoreFence()V in class Ljava/lang/invoke/VarHandle;` (GitHub #71/#72, triage `android-too-new`) | The APK needs Android 13+ (minSdk 33 or more; those were 34) and calls its classes at start; Lepton's Android is 11 (API 30). OVRPort lowers minSdk to 29, so it installs anyway. minSdk ≤ 32 (Quest's Android 12L) is fine: 16 working catalog games declare 32 | None (analysis `extra.min_sdk` > 32 → a warning on the game page/CLI and in the recipe notes; never unsupported from the manifest alone, the launch test's triage decides). Waits for Valve to update Lepton's Android |
| Nothing opens; `TWALauncherActivity: Using URL from Manifest (https://…)`, `Creating TwaLauncher for com.oculus.browser`, `NameNotFoundException: com.oculus.browser` (GitHub #86 Mahjong Table VR, triage `web-wrapper`) | The APK is a Trusted Web Activity (Bubblewrap / Meta's PWA packaging): a website that opens in Meta's browser, which Lepton doesn't have | None: open the URL in a browser. Analysis `extra.web_wrapper` (manifest meta-data `android.support.customtabs.trusted.DEFAULT_URL`, resolved through resources.arsc, or androidbrowserhelper's LauncherActivity) → a warning with the URL (not unsupported: the manifest alone never decides) |
| A flat window, no VR and no way to interact; `Google VR Error [Daydream]: Google VR had a fatal issue while loading`, `class com/google/vr/sdk/base/CardboardViewNativeImpl not found` (32-bit bridge), `Unable to start service Intent { act=com.google.vr.vrcore.… }` (GitHub #335 Blade Runner: Revelations, triage `gvr-not-supported`) | A Google Daydream / Cardboard build: Google's VR SDK (GVR, `libgvr.so`) or the Cardboard SDK. Daydream needs Google's VrCore service, Cardboard draws a distorted side-by-side image for a phone screen; neither reaches OpenXR, the Frame's only way into the headset | None: get the game's Oculus build (Quest, Go or Gear VR), which goes through the normal path. Analysis `extra.google_vr` (`daydream`/`cardboard`: manifest categories `com.google.intent.category.DAYDREAM`/`CARDBOARD`, `enableVrMode="com.google.vr.vrcore/…"`, `libgvr.so`/Cardboard SDK libraries, GVR Java classes, Unity `vr-device-list`; not `libgvraudio.so`, which Quest games ship too) → a warning on the game page/CLI and in the recipe notes, only when the APK has no Oculus support; never unsupported from the manifest alone. A GVR → OpenXR shim (like the VrApi bridge) is possible in principle but not built |
| `UnsatisfiedLinkError` / `cannot locate symbol "ovr_…"` | overport's platform loader lacks Meta platform functions | `frame.ovrstubs` (automatic, generated stubs) |
| missing `ovrMessageType_ToString` | same, but the game needs a real string | `frame.ovrplatformcompat` (automatic) |
| The game stays in its built-in language or waits at start although its OBB / files hold language packs (`<tag>.lang`, for example `de.lang`) | overport's platform loader answers `ovr_LanguagePack_GetCurrent/SetCurrent` with request id 0, so the game never gets the pack's path | `frame.langpacks` (opt-in, experimental, shown for games whose data has `*.lang`; `native/langpack`, build it with `python native/build.py --only langpack`). Default pack: the one the game applies, else env `FRAMEPORT_LANGPACK=<tag>`, else the only pack; search path override `FRAMEPORT_LANGPACK_DIRS`. Unreal games (Deadpool VR) gray out a pack whose asset `Metadata` differs from the game's version string: the patch writes the APK's versionName as Metadata (env `FRAMEPORT_LANGPACK_META` overrides) and reports the pack under the `/storage/emulated/0/Android/obb/<pkg>/` spelling of its path; with `/sdcard/…` the text switched but the dialogue stayed silent (verified in the headset with Deadpool VR) |
@@ -267,19 +271,3 @@ Scan a folder with Rift game dumps (Windows game folders) like Quest dumps; they
| Proton game hangs at start in a headless/SSH launch; log `no driver could be loaded` / `explorer process failed to start` | no display session (DISPLAY/GAMESCOPE_WAYLAND_DISPLAY) | the Proton launch.sh takes them from the running Steam (built in) |
| Unreal game starts (window created) then `CrashReportClient` runs | the game crashed under Proton; often no VR runtime reached it (Revive off) | keep `pcvr.revive` on (repacks' bundled LibRevive64.dll isn't loaded by itself); read the game log + crash summary in the launch log |
| `VK_ERROR_DEVICE_LOST` under DXVK | freedreno GPU hang | `pcvr.proton_log` to capture; PC mode |
## Experimental Rift through FEX
These signatures apply to PC VR logs (`kind: pcvr`). Compatibility profiles describe static evidence until a
headset test verifies them. Meta's entitlement and runtime signature checks remain intact.
| Symptom | Cause | Fix |
|---|---|---|
| Meta runtime says `Missing entitlement` | The signed-in Meta account does not own the game | Informational, not a FramePort bug; use an account that owns it. No bypass or patch is offered (`fex-missing-entitlement`) |
| `OVRServer` reports `install_available` | The matching app is not registered as installed | Reinstall/register through the FEX install flow with the matching Meta manifest (`fex-registration-missing`) |
| `Rejecting new committed universe since IMU fallback is active` | SteamVR has not acquired headset tracking since boot | Wear the headset once and wait for tracking before retrying (`fex-imu-fallback`) |
| `Service invocation completed`, followed by confirmation `OVRLibrarian still running` | Wine Mono's OVRLibrarian never exits under FEX and blocks later clients | End only OVRLibrarian.exe after completion; check that the FEX launcher's cleanup runs. Completion alone is healthy (`fex-librarian-stuck`) |
| `vkd3d` fails to create/initialize a device | D3D12 renderer initialization failed | Check GE's bundled vkd3d-proton, clear inherited wined3d/no-D3D12 flags, verify FEX Vulkan thunk to Turnip (`fex-vkd3d-init`) |
| `wined3d` fails to initialize OpenGL | No working guest GL/display route; the Vulkan thunk does not provide a GL thunk | Inspect guest Mesa renderer and display access; prefer the game's D3D9/11 route if available (`fex-wined3d-init`) |
| `ReviveInjector` reports failure to start/inject | Wrong exe, missing x64 Revive files or injection failure | Check executable and shared GE prefix; use OpenVR mode, without `/openxr`. OpenVR-only games can run directly (`fex-revive-injector`) |
| Robo Recall has no IME CVar in ApplicationCore or Slate | Older modular Unreal keeps FWindowsApplication in Core | Search `*-Core-Win64-Shipping.dll` with the same anchored CVar finder; this surveyed build has the constructor default at RVA `0x15ffe5`. Never patch an unanchored boolean based on an assumed member offset |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 415 KiB

After

Width:  |  Height:  |  Size: 421 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 668 KiB

After

Width:  |  Height:  |  Size: 663 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 99 KiB

-302
View File
@@ -1,302 +0,0 @@
# Rift through FEX: compatibility stream C
Compatibility is static evidence until a headset test verifies a build. First Contact remains the only verified
profile. No game entitlement, Platform SDK or Oculus signature checks are changed. A Meta account without ownership
must receive **Missing entitlement**; this is an informational result, not a bug to work around.
## Implementation and profile schema
`agent/fexrift_compat.py` registers a `GAME_INFO_HOOKS` handler, launcher environment handler and install-check
handler. `game_info()` obtains the exe and launch arguments from Meta's manifest, then applies a matching profile.
The helper reports `verified: false` for likely/untested builds. Likely profiles install with a warning (also in
`checks.profile_warnings`, which the parent agent forwards); untested builds need `force_unverified`; blocked
profiles are refused even with force. `checks` records the selected profile, status, route, cache eligibility and
32-bit warning. No agent version bump is included.
`agent/fexrift_games.json` is data, not executable configuration. Its `_comment` describes these fields:
| Field | Meaning |
|---|---|
| `match.canonical_names` | List of exact Meta canonical app names; no fuzzy title matching |
| `match.sha256` | List of exact executable SHA-256 strings |
| `match.executables` | List of `{name, size}` objects: case-insensitive basename **and** exact byte size must match |
| `status` | `verified`, `likely`, `untested`, `blocked` |
| `graphics` | `d3d11` (default), `d3d9`, `d3d12`, `opengl`, `vulkan` |
| `env` | String environment values |
| `ime_patch` | Optional fallback `{rva, old, new}`, with integer/hex RVA; null means no fallback |
| `fp_mem` | `off`, `candidate` (informational, no preload), `enabled` (verified per-game opt-in) |
| `bigcache_mb` | Cache size when enabled, default 256 |
| `dxvk` | List of dxvk.conf lines; launcher writes `$A/dxvk.conf` and exports `DXVK_CONFIG_FILE` |
| `args` | Optional argument list override; omit to preserve manifest arguments |
| `notes` | Evidence and first-launch cautions |
| `revive` | Optional, defaults true; false launches an OpenVR-only game directly |
| `meta_runtime` | Optional; false starts the game without Meta's runtime. Default: true with Revive or the Platform SDK |
| `vr_args` | Optional `off`: unverified installs keep their arguments exactly (no `-vr` / `-vrmode OpenVR`) |
### Route and VR arguments from the build's files
Without an explicit `revive`/`meta_runtime` (and for any game that isn't verified), `install_info()` reads the game's
folder (`oculus_facts`, after RiftLift's `detection.py`): LibOVR (`LibOVRRT*`, `OVRPlugin.dll`, `OculusXRPlugin.dll`,
`*OculusHMD*` file names, or "LibOVRRT" ASCII/UTF-16 in the exe), the Platform SDK (`LibOVRPlatform*`, `pnsovr.dll`,
`*OnlineSubsystemOculus*`, or "LibOVRPlatform" in the exe), OpenVR (`openvr_api.dll`) and Unity. `vr_route()`:
- Platform SDK, or no OpenVR → `revive`: Meta's runtime + ReviveInjector (the route First Contact is verified on).
- OpenVR and no LibOVR, or a Unity build with both providers (it picks one per launch) → `openvr`: straight to
SteamVR, no Revive and no Meta runtime (`FP_META_RUNTIME=0` in launch.sh; no OVRServer/OVRLibrarian under FEX).
- Unreal builds with both plugins stay on `revive` (no device evidence for `-hmd=SteamVR` yet).
Unverified games then get the engine's VR switch if their arguments don't already pick one (`vr_args`, after
RiftLift's `oculus_launch_arguments`): Unity on the OpenVR route `-vrmode OpenVR`, Unreal on Revive `-vr`. Verified
profiles keep the launch they were verified with. `checks.vr` records the facts, route and added arguments.
Over-detection only keeps a game on the proven route; the OpenVR route needs a headset check per game.
Local copies now run the same profile hooks as games in Meta's library: before this, a profile key equal to the
local name counted as verified whatever its status (Chronos, `likely`) and build-matched profiles never applied.
`touch <anchor>/debug-wine` turns on Wine debug channels for the next launches (`+loaddll,+wintrust,+chain,+openxr,
+vrclient,+steamclient,+seh` with timestamps, into launch.log); remove the file afterwards. It slows the game under
FEX.
Match alternatives are OR, while basename and size within an executable match are AND. Multiple matching profiles
are refused. With no `match`, the profile key is the exact canonical name (legacy First Contact compatibility).
The surveyed profiles use basename+size because the owner's folders do not establish authoritative Meta canonical
names; their keys identify profiles, **not** presumed Meta app IDs. They preserve the manifest's exe and arguments.
A different store build/size needs a new survey or an explicit untested install; do not guess its identity.
A SHA-only identity should be rechecked against the original executable after any game-byte patch: patching changes
its hash. Prefer canonical names or basename+size for profiles that need the IME fix. Size matches choose launch
settings only; the anchored finder independently verifies the bytes before patching.
`fp_mem: candidate` is set only when the surveyed lower bound of the UE version is >=4.18 (Binned2 big-block path).
It never enables the unzeroed cache. Every other game needs evidence that it fully overwrites reused memory before
an opt-in. First Contact's existing explicit environment/cache settings remain enabled.
## Older Unreal: Robo Recall
The premise that Robo Recall lacks `Slate.DeferWindowsMessageProcessing` was a search-location error. Its modular
`RoboRecall-Core-Win64-Shipping.dll` contains the UTF-16 CVar at file offset `0x1e1bb0`; the existing anchored finder
returns RVA `0x15ffe5`, old `c7860002000001000000`, new `c7860002000000000000`. This changes the constructor's
`mov dword ptr [rsi+0x200],1` immediate to zero, with the existing expected-byte guard and `.orig` backup.
Older Unreal placed `FWindowsApplication` in Runtime/Core; newer trees split it into Runtime/ApplicationCore.
`bAllowedToDeferMessageProcessing` and `GetDeferMessages` control the same Windows message deferral path, so an old
engine is not exempt from the IME deadlock merely because ApplicationCore/Slate lack the marker. The extension
extends `find_ime_target()` to search `*-Core-Win64-Shipping.dll` (and Win32/Core.dll forms), using the unchanged
CVar/xref/storage finder. It never patches a guessed member offset. Synthetic tests cover successful Core discovery,
repeat installs, and a CVar name without an anchored reference. No Unreal source checkout was available offline;
the observed binary is the evidence for this build, rather than an inferred engine-version exemption.
## Graphics and remaining device questions
DXVK handles D3D9/11; D3D12 uses GE's own vkd3d-proton selection. The launcher clears inherited
`PROTON_USE_WINED3D`, `PROTON_NO_D3D12` and `PROTON_NO_D3D11`, keeps `FP_VKTHUNK=1`, and lets Proton select/copy its
shipped DLLs. It makes no renderer DLL edits in a game. `checks.vkd3d_dlls` reports installed d3d12 DLLs under
`files/{lib,lib64}/wine/vkd3d-proton/{,x86_64-windows/,i386-windows/}`. These are discovery candidates, not a hardcoded
installation prerequisite. GE-Proton's script/archive was not available locally, and network/device access was
prohibited: verify the exact 11-7 layout and its script logic on the device before claiming D3D12 support.
The `opengl` profile exports `PROTON_USE_WINED3D=1`. A native OpenGL game still calls OpenGL directly; this flag
selects Wine's GL renderer for any D3D calls. There is **no configured FEX GL thunk**. Host acceleration would need
FEX's matching guest libGL/libEGL thunk libraries, host counterparts and enabled GL thunk configuration, with a
working display/GLX/EGL bridge. Guest rootfs Mesa might instead use software rendering or Zink through Vulkan;
inspect the actual renderer before attributing a game failure to Wine or promising hardware acceleration.
The Climb prefers its imported D3D9 route; imports alone do not prove which renderer its config selects.
A 32-bit exe is flagged in the survey and install checks. GE WoW64 under FEX still needs working 32-bit graphics
and SteamVR's 32-bit vrclient bridge; it is not promoted to likely based on engine alone. XAudio2 and Bink are facts
to watch; Media Foundation is flagged for a real movie-playback check. Anti-cheat detected by filenames/imports
makes a generated profile blocked. Absence of a static marker is not proof that runtime-loaded middleware is absent.
## Reproduce the offline survey
Use an isolated `FRAMEPORT_HOME`; never set `FRAMEPORT_WINDOWS_DATA`. No program in a dump is executed, no archive
is extracted, and no file in a game folder is written. The report contains local paths and must stay uncommitted.
```bash
export FRAMEPORT_HOME="$PWD/.home"
uv run python - <<'PY'
import subprocess, sys
from pathlib import Path
root = Path('/mnt/d/Backup Data/Misc/emus/VR_META_QUEST/ARMGDDN_PCVR_OCULUS')
cmd = [sys.executable, 'scripts/rift_fex_survey.py', '--out', '.home/survey']
for folder in sorted(root.iterdir()):
if folder.is_dir():
cmd += ['--folder', str(folder)]
subprocess.run(cmd, check=True)
PY
```
Outputs: `.home/survey/survey.json`, `survey.md`, and `profiles.json` (ready to paste, but review argument overrides
and direct OpenVR routing). The Unreal pak/ini reader is deliberately left in place for stream B's extraction.
## Owner's library: static results
All 19 selected game exes are x86_64; no selected 32-bit client was found. Eighteen use the Platform SDK; Rick and
Morty is the exception. The table contains **10** likely titles (including Robo Recall and all three Vader episodes),
plus nine untested titles. Profile IDs below are data keys matched by exe basename+size, not canonical app names.
`candidate` means cache eligibility only; it is off at launch. No surveyed game is promoted to verified.
| Game / profile ID | Route | Status | Platform SDK | fp_mem | Watch at first launch |
|---|---|---|---|---|---|
| Arktika 1 / `arktika-1` | d3d11 trial; API undetected | untested | yes | off | Establish actual renderer and custom-engine startup; do not infer D3D11 from this default |
| Asgard's Wrath / `asgards-wrath` | d3d11 | likely | yes | candidate | Large-block stalls/memory, Media Foundation movies, entitlement |
| Brass Tactics / `brass-tactics` | d3d11 | likely | yes | off | Media Foundation movies, tracking and IME startup |
| Chronos / `chronos` | d3d11 | likely | yes | off | Older UE D3D11 path, movies and controller input |
| Defector / `defector` | d3d11 | untested | yes | off | Custom-engine startup and Bink cutscenes |
| Hubris / `hubris` | d3d11 | likely | yes | candidate | XAudio2 sound, Media Foundation movies, shader/GPU cost |
| Lies Beneath / `lies-beneath` | d3d11 | likely | yes | candidate | Platform SDK delay load/entitlement; IME fix and movies |
| Lone Echo / `lone-echo` | d3d11 (also imports d3d9) | untested | yes | off | Runtime tracks client, entitlement; custom-engine startup and allocator stalls |
| Lone Echo II / `lone-echo-2` | d3d12 | untested | yes | off | vkd3d-proton DLL layout and Vulkan device creation on Turnip |
| Rick and Morty / `rick-and-morty-virtual-rick-ality` | opengl; direct OpenVR | untested | **no** | off | Actual GL renderer/acceleration; SteamVR bridge; speech WinRT; never inject Revive |
| Robo Recall / `robo-recall` | d3d11 | likely | yes | off | Core DLL IME fix at `0x15ffe5`; Meta entitlement and tracking |
| Skydance's Behemoth / `skydances-behemoth` | d3d11 | likely | yes | candidate | XAudio2 sound, Media Foundation movies and heavy GPU/memory use |
| Stormland / `stormland` | d3d11 | untested | yes | off | Custom engine, Media Foundation and Bink cutscenes |
| The Climb / `the-climb` | d3d9 preferred; also imports GL | untested | yes | off | Confirm CryEngine selects D3D9 and DXVK; GL import alone is not a selected renderer |
| The Unspoken / `the-unspoken` | d3d11 | untested | yes | off | Custom engine, Media Foundation and Bink cutscenes |
| Vader Immortal I / `vader-immortal-episode-i` | d3d11 | likely | yes | off (UE range starts at 4.16) | Movies, controller input, startup IME; leave MSAA at its game default |
| Vader Immortal II / `vader-immortal-episode-ii` | d3d11 | likely | yes | off (UE range starts at 4.16) | Movies, controller input, startup IME; leave MSAA at its game default |
| Vader Immortal III / `vader-immortal-episode-iii` | d3d11 | likely | yes | off (UE range starts at 4.16) | Movies, controller input, startup IME; leave MSAA at its game default |
| Wilson's Heart / `wilsons-heart` | d3d11 | untested | yes | off | Custom-engine startup and Bink cutscenes |
## Exact maintainer device checks (not executed here)
Only run one FEX game at a time: they share the Wine prefix and wineserver. The following uses the existing CLI;
stream A/B may add a direct login/install path at integration. Set `FRAMEPORT_HOME` to the development data folder
with the paired Frame configuration, then keep using that folder. The example `.home` is isolated from normal app
data and needs a paired Frame first. Never set `FRAMEPORT_WINDOWS_DATA`.
1. On the development PC, upload the integrated helper/extensions/profiles and verify setup:
```bash
export FRAMEPORT_HOME="$PWD/.home"
export FRAMEPORT_EXPERIMENTAL_FEX=1
uv run frameport fex setup
uv run frameport fex status
```
Wait for setup to finish. Expect `proton`, `prefix` and `fex` true; `apps` lists Meta canonical names. No token or
sign-in URL is needed in the output. If importing from an already signed-in PC Wine prefix, use the exact app
name from its Meta manifest filename (replace both example values):
```bash
app='actual-meta-canonical-name'
prefix='/path/to/signed-in/wine-prefix'
uv run frameport fex import-login "$prefix" --app "$app"
uv run frameport fex install "$app"
```
For a matching likely profile, expect `verified: false`, `checks.profile_status: likely`, a profile ID and
`checks.profile_warnings`; no `--force-unverified` should be needed. If the downloaded build differs from the
surveyed basename+size, expect refusal and review its own survey before forcing. An explicitly blocked profile
must still refuse with `--force-unverified`. An untested game needs that switch. The PC reporter also warns
that the game has not been verified on the Frame.
2. On the Frame, wear the headset once after boot and wait for tracking. Launch from the Steam shortcut. For these
checks in a Frame terminal, replace `app` with the same canonical name:
```bash
app='actual-meta-canonical-name'
pkg="rift.${app//-/_}"
anchor="$HOME/Applications/quest-frame/$pkg"
python3 - "$anchor/deployment.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1]))
for key in ('profile', 'profile_status', 'profile_warnings', 'graphics', 'fp_mem', 'exe_32bit', 'wow64', 'vkd3d_dlls'):
if key in d.get('checks', {}):
print(key, d['checks'][key])
PY
rg 'FramePort FEX: graphics=' "$anchor/launch.log"
rg 'PROTON_USE_WINED3D|PROTON_NO_D3D12|DXVK_CONFIG_FILE|export FP_MEM' "$anchor/launch.sh"
```
Expect the profile route. Candidate caches must have no `export FP_MEM=1`. For Rick and Morty also run
`rg 'taskset.*proton' "$anchor/launch.sh"`: the command must invoke the game directly with no ReviveInjector.
A graphics route marker proves selection of launcher settings, not successful rendering. Check both eyes,
tracking/controllers, sound and a movie in the headset before changing a profile to verified.
3. For Robo Recall, `checks.ime.file` should name `RoboRecall-Core-Win64-Shipping.dll` and `fixes.ime_patch` should be
`patched` on first install and `already` on repeat. On the Frame, verify the original backup exists and the
constructor immediate is zero (only the installed copy is read):
```bash
python3 - "$anchor/deployment.json" <<'PY'
import importlib.util, json, os, sys
d = json.load(open(sys.argv[1]))
path = os.path.join(os.path.dirname(d['exe']), d['checks']['ime']['file'])
helper = os.path.expanduser('~/.local/share/frameport/fexrift/artifacts/fexrift.py')
spec = importlib.util.spec_from_file_location('fx', helper)
fx = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fx)
b = open(path, 'rb').read()
p, reason = fx.find_ime_patch(b)
assert p and b[fx.pe_offset(b, p['rva']):fx.pe_offset(b, p['rva']) + len(bytes.fromhex(p['new']))] == bytes.fromhex(p['new']), reason
assert os.path.isfile(path + '.orig')
print('Core IME default zero; original backup present')
PY
```
4. For Lone Echo II (untested), install with `--force-unverified`. In a Frame terminal inspect only GE's files and
script; no network fetch is needed:
```bash
r="$HOME/.local/share/frameport/fexrift"
rg --files "$r/ge/files" | rg '/vkd3d-proton/.*/?d3d12(core)?\.dll$|/vkd3d-proton/d3d12(core)?\.dll$'
rg -n 'PROTON_USE_WINED3D|PROTON_NO_D3D12|vkd3d-proton|dxvk' "$r/ge/proton"
```
Expect bundled vkd3d-proton and script selection when wined3d/no-D3D12 are unset. `checks.vkd3d_dlls` should name
the installed layout. A vkd3d initialization failure is triaged `fex-vkd3d-init`; a successful Vulkan device plus
frames in both eyes is the first actual evidence of this route. If the file layout differs, update discovery
candidates without copying DLLs into the game. For GL, inspect the active **guest** renderer; an installed host
Mesa library or the Vulkan thunk does not establish guest GL acceleration.
5. Exercise each triage signature offline on the PC with
`uv run pytest -q tests/test_fexrift_compat.py -k triage`. On-device expected strings are `Missing entitlement`,
`OVRServer ... install_available`, SteamVR's IMU-fallback message, vkd3d/wined3d initialization failure, or a
ReviveInjector failure. Do not dump entire Meta log files: they may carry sign-in data. A Librarian completion
line alone must not diagnose a hang. After completion, confirm persistence using `pgrep -f '[O]VRLibrarian.exe'`;
only if it remains alive, record the safe diagnostic `OVRLibrarian still running` alongside the completion
marker. The launcher now emits the fixed combined marker itself if Librarian persists after cleanup and
completion is present; it never mirrors the log. The combined trace matches `fex-librarian-stuck`. Stop only that process after completion with
`pkill -9 -f '[O]VRLibrarian.exe'`; the normal launcher already does this. For an unowned title, accept Meta's
Missing entitlement result and stop that game test.
Undo: exit the game in Steam before touching files. Remove the selected profile from the device copy of
`artifacts/fexrift_games.json` and rerun install with `--force-unverified` to regenerate the default D3D11/Revive
launcher. For an OpenVR-only game, retain `revive: false` in an untested profile when comparing graphics routes.
Remove the anchor's `dxvk.conf` when no longer used. To undo the IME fix, restore **only the installed binary**
from its `.orig` copy after stopping the game; for example, on the Frame:
```bash
python3 - "$anchor/deployment.json" <<'PY'
import json, os, shutil, sys
record = json.load(open(sys.argv[1]))
path = os.path.join(os.path.dirname(record['exe']), record['checks']['ime']['file'])
shutil.copy2(path + '.orig', path)
print('Installed IME binary restored')
PY
```
Do not delete the shared prefix to undo a profile: it holds Meta's runtime and the owner's login/saves. Game dumps
are never modified. Re-running install reapplies the anchored IME fix; to compare launches, restore after install
and before Play.
## Validation in this worktree
- Offline survey completed for all 19 folders with no per-game errors. Every surveyed executable matched exactly
its intended committed profile through the compatibility hook. Ten profiles are likely, nine untested; the
separate First Contact profile stays verified. No selected or alternate candidate exe was 32-bit. No static
anti-cheat marker was found; this does not rule out runtime-loaded middleware.
- Focused FEX/survey/triage tests: **96 passed, 1 skipped**. Ruff passed for the new extension, survey and their tests.
- `uv run python scripts/patch_docs.py` was run; `--check` passes and generated patch docs needed no committed change.
- Final whole-suite run: **1,646 passed, 43 skipped, 11 failed, 16 setup errors**. All 27 unsuccessful cases failed
at local `socket()` creation with `PermissionError: [Errno 1] Operation not permitted`. They are existing local
HTTP/pairing/stream tests in `test_deeplink`, `test_devkit`, `test_install_links_extra`, `test_livestream`,
`test_setup_url`, and `test_ui_state`. They need a runner allowing loopback sockets; no application or test code
was changed to hide this restriction. Re-run the full suite there before integration.
- The prebuilt virtual environment was used with `UV_CACHE_DIR=/tmp/frameport-rift-uv UV_NO_SYNC=1` because the default
uv cache is read-only and offline metadata resolution cannot install hatchling. For example:
`UV_CACHE_DIR=/tmp/frameport-rift-uv UV_NO_SYNC=1 uv run pytest -q`.
- No device or external network access was attempted. D3D12, guest OpenGL acceleration, WoW64 and gameplay remain
device questions; the steps above specify the evidence needed. The GE script and Unreal source-history checkout
were unavailable locally; Robo Recall's actual Core DLL supplies direct evidence for the IME fix instead.
-228
View File
@@ -1,228 +0,0 @@
# Stream B: unchanged local Rift copies and Meta library registration
Implemented on `rift/install`. Device validation is pending: this workspace cannot reach the Frame or create local
network sockets. No entitlement, Platform SDK, runtime signature check, sign-in data or repack crack is changed by
this work. A Meta **Missing entitlement** response remains a failure to report to the owner.
## Implementation
`frameport fex install --from-library rift.<slug>` takes the Rift entry's `game_dir`, selected `exe`, title and
`launch_args` (also supported in `analysis.extra`). `--folder DIR [--title T]` uses the existing Rift analyzer to pick
the exe; ambiguous choices must first be resolved in the library. Optional positional `APP` overrides the generated
canonical name. Otherwise use the analysis's `canonical_name`, then a lowercase title slug. Local unverified games
require `--force-unverified` **before** any upload. Existing prefix-game installs still work without either option.
`src/frameport/fexinstall.py` stats the folder and reuses `installer.transfer_link()` and `upload_files()` unchanged:
fast link, SFTP `.part` append, tar batches, progress and Reporter cancellation all follow the existing install path.
Finished files are skipped by source size/mtime plus remote size; changed sources discard old completed/partial
bytes before retry. The source is statted again after transfer. This avoids hashing all source files over NTFS;
it cannot detect an edit that deliberately preserves both size and mtime. Do not edit the source during an install.
The free-space check reserves 1 GiB in addition to all pending bytes (conservative when `.part` files already exist).
Skipped, logged and recorded: case-insensitive `*.7z`, `*.7z.0*` split volumes (including backup suffixes), `Data.bin`,
`AGRepackInstaller.exe`, `VD.bat`, and `*.AG`. Nothing is extracted or executed on the PC. Every included file's bytes
are uploaded as supplied. Existing install-time generic fixes, including the Unreal IME fix, still run on the Frame
after registration; they may change the **Frame** executable. The source folder stays unchanged. Symlinks, path
escapes, duplicate Windows filenames and collisions with Meta-managed copies are refused.
App ID precedence:
1. `[OnlineSubsystemOculus]` in unencrypted pak `Config/DefaultEngine.ini`, then loose `DefaultEngine.ini`,
`Oculus.ini` or `OculusConfig.ini`; keys `RiftAppId`, `OculusAppId`, `AppId` in that order. Also checks only the
known JSON names `OculusConfig.json` / `oculus-platform-config.json` for `RiftAppId`, `OculusAppId`, `AppId`,
`app_id`. IDs must be positive numbers. No binary-string guessing or archive decryption.
2. Already cached OculusDB data: `details.store_url` (`fetch_details()` retains the ID in this URL, not an explicit
Rift-ID field). No lookup/network request is introduced. A Quest-linked details record can name its Quest store
product: check this fallback manually before testing a game with no config ID.
3. `--app-id ID`, used only if no earlier source supplies one.
`app_id_source` records the selected origin. `store_app_id` independently retains the cached store ID when present,
so a game ID such as First Contact's `1184903171584429` is not lost to store product `1217155751659625`. Manifest
`appId` uses the selected ID; device tests must establish whether Meta instead requires the store product ID for
particular builds. The version comes from a version-like folder name, then the exe's PE `.rsrc` FileVersion, else
`0.0.0`; versionCode is 1. The shared reader moved to `analysis/unreal_pak.py`; the survey re-exports it via imports
so its existing callers and tests keep working. Stream C should keep these imports when merging its survey edits.
`agent/fexrift_install.py` registers `prepare_local`, `register_local`, `local_info`, `unregister_local` and
`runtime_state`. Reservations/metadata live in `fexrift/local-games/<app>.json`, with no login information. They also
allow interrupted pre-registration uploads to resume. Registration hashes each file **on the Frame**, writes
`<library>/Manifests/<app>.json` and `.json.mini`, and imports the library registry entry through Wine. The extension
supplies the library manifest to `manifest_launch` / `game_info`; the existing static checks, IME patch and launcher
then run normally. The install check hook marks `local_copy: true`.
Manifest JSON matches the supplied real First Contact app fixtures: property order (derived properties first),
types, CRLF, two-space indentation, backslash `files` keys, forward-slash `launchFile`, and mini containing exe
records only. App packageType `APP`, isCore false, launchFile2D null, launchParameters2D empty string,
redistributables empty; other defaults come from `MANIFEST_DEFAULTS`. Launch parameters use Windows argv quoting;
the launcher preserves the original argv list (a small shared launcher hook avoids splitting local-copy arguments
while retaining the existing profiles' shell-fragment parsing).
Each file has its actual size and whole-file SHA-256, `segmentSize: 10000000`, and one segment per **decimal 10 MB**
chunk. Each triple is `[0, chunk_sha256, len(zlib.compress(chunk))]`. The fixture's third number is compressed length,
not uncompressed size. We do not know Meta's opaque first value and use 0 as an explicit placeholder; no fabricated
CDN identifiers or download URLs are written. Empty files have zero segments. **These manifests describe local
bytes, not a working Meta CDN repair recipe. Whether Meta accepts the placeholder without scheduling repair is an
open device question.** Do not initiate an update/repair from Meta's app to validate this.
Internal games: `<PFX>/drive_c/Program Files/Meta Horizon/Software/Software/<app>`, using Meta's existing default
library registration. `--dest <mount>` must exactly match an available external mount returned by the existing
`drives` command; existing `resolve_dest()` rejects unusable filesystems. No fallback on a missing card.
External games: `<mount>/FramePort/fexrift-games/<app>`. Their Meta library root is the sibling
`<mount>/FramePort/fexrift-library`, containing `Manifests/` and a `Software` symlink to `fexrift-games/`. A stable
UUID5 from the mount path identifies the registry library. A prefix `dosdevices/volume{GUID}` links to the mount,
and the first unused D:–Y: letter links there too (an existing letter for the same mount is reused). Registry
`Path` uses `\\?\Volume{GUID}\FramePort\fexrift-library`, `OriginalPath` uses the letter. The default library stays
default. Mount-path changes require uninstall/reinstall; moving these games through the general Move action has
not been implemented by this stream. Wine volume discovery and external-library scans need device validation.
Deployment kind stays `frame_fex`, with `source: local_copy`, `app_id`, `app_id_source`, `store_app_id`, `skipped`,
`dest`, and the existing launcher/check fields. Local-copy uninstall removes its files and both manifests. The last
game on an external library also removes that library's registry key; the shared default key, shared prefix, saves,
login and reusable drive/volume links remain. Imported Meta-managed games still keep their files on uninstall.
There is no agent-version bump; integration must bump it so updated agent commands reach existing devices.
The only other shared-agent helper change sends helper JSON on stdin, avoiding Linux's single-argument size limit
for large inventories. The extension files are already included by `artifact_files()` and need no packaging change.
## Runtime probe
`--runtime-check` calls the separate bounded `fex_runtime_state` command after install (helper `runtime_state`). It
reuses an existing OVRServer or starts it with the shared prefix's Wine environment. It examines only newly appended
Service/OVRServer log text, returning `runtime_state: ready`, `install_available` or `timeout` plus `reused_server`.
It never returns raw runtime log lines. If it started the server, it kills OVRLibrarian after a fresh invocation
completion and stops its Wine server at exit; a reused runtime is left running. The polling budget is 95 seconds,
with bounded process start/probe/cleanup, and the agent imposes a 120-second limit. A reused idle runtime may emit no
new state line and return `timeout`; that result is inconclusive. The probe does not start the game or prove account
ownership. The actual log naming/state-line format remains a device question.
## Offline validation
Use a writable UV cache in this sandbox (the default cache is read-only):
```sh
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline --no-sync pytest -q
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline --no-sync pytest -q \
tests/test_fex_install.py tests/test_fexrift.py tests/test_fexrift_ext.py tests/test_rift_fex_survey.py
```
The full run reached 1,654 passed, 43 skipped; 11 failures + 16 setup errors all tried to create network sockets
for existing localhost HTTP/streaming/pairing tests, which this sandbox forbids (`PermissionError: Operation not
permitted`). Rerun the whole suite without that sandbox restriction at integration. No socket tests were changed
to conceal this limitation. Triage/patch catalog files were not touched, so `patch_docs.py --check` is not required.
Final follow-up: 1,658 passed, 43 skipped, 27 deselected when excluding precisely those socket-dependent tests.
The final install/FEX/survey run (including an additional split-volume suffix case) passed 68 tests, 1 skipped.
Ruff passed for the new modules/tests and the survey; `git diff --check` passed.
## Exact maintainer device test
Run these only on the maintainer's connected PC. Keep `FRAMEPORT_HOME` pointing to this worktree's `.home`, with
its paired Frame target and Rift library entries. Do not point at the Windows FramePort data directory. Ensure the
maintainer's integration agent version includes this branch. Wear the headset once after boot; stop any running
FEX game before the runtime probe (all use one prefix).
```sh
export FRAMEPORT_HOME="$PWD/.home"
export FRAMEPORT_EXPERIMENTAL_FEX=1
uv run frameport fex setup
uv run frameport fex status
uv run frameport list
```
Setup uploads this extension and binaries; it may fetch the signed Meta runtime on the device. Use the login stream
to sign in with the owner's account first. `status` should show prefix/meta installed and `login: true` without
printing any session content. Do not copy session files, CoreData or sign-in URL queries into a report.
Pick a library ID the account owns; example (substitute the exact ID from `frameport list`):
```sh
uv run frameport fex install --from-library rift.robo_recall --force-unverified --runtime-check
```
Expect `Skipped repack leftover: ...` entries, `Meta app ID ... (config:...)` or the cached/CLI fallback, upload
progress, `Hash and register the game on the Frame`, then generic checks/Steam registration. Final JSON should
have `checks.local_copy: true`, with `checks.runtime_state: ready` if Meta emitted the state line. Check
`app_id_source` and both IDs in deployment with the filtered command below. `install_available` means registration
did not take; stop and report the IDs, canonical name and manifest shape. `timeout` requires inspecting the log
format **locally on the device**, keeping any account data private.
A folder install uses the same flow:
```sh
uv run frameport fex install --folder '/path/to/a/game copy' --title 'My Rift Game' \
--app-id 1234567890123456 --force-unverified --runtime-check
```
Replace the example ID with the game's actual ID; the option is a fallback and does not override a config ID.
Do not try registering over First Contact already imported by the login tar: the collision refusal is deliberate.
Inspect deployment fields and launch using the paired connection (edit the package below once):
```sh
uv run python - <<'PY'
import json
from frameport.cli import _fex_target
frame = _fex_target(None).frame
pkg = 'rift.robo_recall'
try:
games = frame.agent('list_installed', package=pkg, details=True)['games']
for game in games:
print(json.dumps({k: game.get(k) for k in
('package', 'kind', 'source', 'app_id', 'app_id_source', 'store_app_id', 'skipped', 'dest')}, indent=1))
print(frame.agent('launch', package=pkg))
finally:
frame.close()
PY
```
Expect `kind: frame_fex`, `source: local_copy`, IDs/provenance, and a Steam launch. In the headset check both eyes,
controllers, audio and reaching a scene. Look locally for runtime `state: ready`, launcher `FramePort: starting
Meta's runtime` / `FramePort: starting <title>`, and the game log. **Missing entitlement** is a valid ownership
failure to report, never a reason to modify the copy or checks. Robo Recall may lack the generic IME patch site;
report a hang without assuming the registration failed.
Resume: interrupt the upload with Ctrl-C, then repeat the identical install command. Expect completed files to be
skipped and big `.part` files to continue. Compare a few **non-patched** files' SHA-256 locally on source/Frame;
manifests should list actual sizes/hashes. No archive, installer, `.AG` file or `VD.bat` should have been uploaded.
External drive: first uninstall the test copy using the rollback below, then:
```sh
uv run frameport frame drives
uv run frameport fex install --from-library rift.robo_recall --force-unverified \
--dest /run/media/steamos/REPLACE_WITH_MOUNT --runtime-check
```
Use an actual `usable: true` mount. Expect physical files in `FramePort/fexrift-games/<canonical>`, sibling
`fexrift-library/Manifests`, a `Software` symlink, a separate registry library, and `runtime_state: ready`. With the
card removed, reinstall/uninstall must fail explicitly rather than writing/deleting internal storage. Reinsert at
the same mount path before rollback. Repeat with two games to confirm uninstalling one leaves the second library
registered; removing the last should remove its registry key.
## Undo
For an installed local copy, end the game in Steam first, then run (substitute its package):
```sh
uv run python - <<'PY'
from frameport.cli import _fex_target
frame = _fex_target(None).frame
try:
print(frame.agent('uninstall', package='rift.robo_recall', remove_shortcut=True, keep_data=True))
finally:
frame.close()
PY
```
Expect `removed: true`; game folder, both manifests, deployment and shortcut disappear. Shared prefix, login, saves
and unrelated games remain. For a cancelled upload that never produced a deployment, remove only its reservation
and uploaded copy through the helper on the Frame (replace canonical/package; stop shared-prefix games first):
```sh
python3 -I ~/.local/share/frameport/fexrift/artifacts/fexrift.py unregister_local \
'{"app":"robo-recall","package":"rift.robo_recall"}'
```
Reusable drive links and the empty external library scaffolding can remain for later installs; they contain no
game/login data. Do not delete the shared prefix to undo one local installation.
-178
View File
@@ -1,178 +0,0 @@
# Stream A: Meta sign-in on the Frame
Implemented on `rift/login`. No Frame or network access was used. The PE helper has **not** been compiled here
(llvm-mingw is unavailable); the browser portal and pipe framing remain device acceptance checks.
## What was built
`frameport fex login [--start-now] [--timeout 900] [--via-pc]` signs in through Meta's own Client.exe, running in the
existing shared FEX prefix. The default creates a temporary, flat Steam entry named **Meta sign-in (FramePort)**
using the existing shortcut installer. `--start-now` instead starts a detached user unit without restarting Steam.
`fex login --stop` repairs interrupted cleanup. All commands require `FRAMEPORT_EXPERIMENTAL_FEX=1`.
`agent/fexrift_login.py` registers `login_start`, `login_status`, `login_stop` and private broker/callback commands.
`agent/frameport_agent.py` has one separate `fex_login*` block; it passes login messages to the extension over stdin,
never JSON argv. No agent version bump or changes to other streams' hook points were needed.
The launch script imports Steam's display variables, disables gamescope WSI and preloads, starts the existing Meta
runtime, waits for OVRLibrarian's completion and kills its stuck process, then starts Client.exe with Proton. Its
stdout/stderr and Proton logging are disabled because Electron can print authentication URLs. A lock prevents a
second Client.exe launcher. A private broker must be alive before the launcher can run. Cancellation signals the
launcher (PID plus kernel start tick, to reject a reused PID), stops Wine, then restores the handler settings. This
also prevents an interrupted runtime warm-up from starting Client.exe after cleanup.
The prefix's WineBrowser `Browsers` setting temporarily points to `login/fp-open-url`. That helper sends the URL to
an owner-only Unix socket broker. The broker records only `page_opened_at`, `callback_received_at` and the fixed
query-free page URL in `login/state.json`. It opens the real URL with host xdg-open, with output discarded. The
temporary host `frameport-oculus.desktop` invokes `fp-oculus-callback`, which sends the callback to the same broker.
The broker passes it to `proton run fp_pipesend.exe` **through stdin**. Neither agent forwarding nor Wine invocation
puts the callback into argv. The desktop protocol invocation itself necessarily supplies `%u` to its short-lived
handler; do not collect process-command-line diagnostics during sign-in.
`native/fexwine/pipesend.c` sends a NUL-terminated UTF-8 callback to `\\.\pipe\oculus`. It retries a missing or busy pipe
for about 20 seconds and prints nothing. Exit codes: 0 written, 2 invalid input, 3 pipe unavailable, 4 write failed.
Only Meta's running client receives the link; a second Client.exe is never started to deliver it.
The extension snapshots the previous WineBrowser value/type, previous host scheme owner, desktop file and mimeapps
files before registration. `login/restore.json` contains **registration settings only**. A failed restoration leaves
this record for `--stop` to retry. Normal success, timeout, errors and Ctrl-C all clean up; a broker deadline also
restores the Frame settings if the PC disconnects (requested timeout plus 180 seconds for Steam shortcut setup).
An OS kill/reboot can interrupt this cleanup; rerun `--stop` after reconnecting. The temporary shortcut is removed
by the PC's cancel request, asynchronously through the existing shortcut worker. A disconnected PC cannot remove
that shortcut until it reconnects, but the launcher refuses to run without its broker.
## PC browser fallback
`--via-pc` keeps the full auth URL **only in broker memory**, draining it once through the agent's SSH status reply
when the PC explicitly requests `take_url`. Ordinary `fex_login_status` replies never contain the URL. The PC opens
the page in its default browser and temporarily borrows the `oculus` scheme. The handler POSTs directly to a loopback
server with a random endpoint; it never uses the normal install-link `links/*.link` inbox. HTTP logging is disabled.
WSL registers a Windows handler which invokes the WSL Python callback, and opens the sign-in page in Windows.
Windows/WSL restoration exports and restores the **entire** HKCU `Software\Classes\oculus` tree, including arbitrary
subkeys and value types, or removes it if absent before login. The non-secret export is deleted after restoration;
if importing it fails, a recovery copy is retained as `<FRAMEPORT_HOME>/oculus-handler-restore.reg` and the error
names it. Linux restores the exact previous desktop/mimeapps bytes, including an absent default. macOS fallback
is explicitly unsupported. These temporary registrations are separate from the permanent FramePort install-link
settings. The PC context restores registration even when sign-in, SSH forwarding or Frame cleanup raises.
Saved login state in `sessions/` and CoreData stays in the prefix. Status only checks whether a non-empty session
file exists; it does not read its contents, prove the session is unexpired, or imply entitlement to any game. This
change does not replace Platform SDK DLLs, alter entitlement checks, or access repack archives. A game reporting
**Missing entitlement** must remain an entitlement failure.
## Offline verification
Run from this worktree, keeping app data isolated in its existing `FRAMEPORT_HOME`:
```sh
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline pytest -q tests/test_fex_login.py tests/test_fexrift.py tests/test_fexrift_ext.py
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline ruff check agent/fexrift_login.py src/frameport/fexlogin.py src/frameport/urlhandler.py src/frameport/cli.py tests/test_fex_login.py
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline pytest -q
```
The focused suite passed (56 passed, 1 skipped); lint passed. The full suite rerun completed: **1,651 passed, 43 skipped,
11 failed, 16 errors**. Every failure/error was `PermissionError: [Errno 1] Operation not permitted` from existing
local HTTP/pairing/live-stream socket tests: this sandbox prohibits socket creation/binding. No other stream's files
or tests were changed to hide those failures. Run the whole suite on a host permitting loopback sockets before
integration. No triage/patch definitions were changed, so patch-doc regeneration is not required.
## Exact maintainer device acceptance steps
Use the maintainer's paired Frame configuration; do not copy credentials or configuration into this branch.
Close any Rift game first: sign-in uses the same Wine prefix and stopping it ends that prefix's processes.
1. Build the PE with llvm-mingw on an x86_64 host (or run the existing full `build_pe_dlls.sh` build):
```sh
x86_64-w64-mingw32-clang -O2 -s -Wl,--no-insert-timestamp -o artifacts/fexrift/fp_pipesend.exe native/fexwine/pipesend.c
uv run python - <<'PY'
import hashlib
from pathlib import Path
root = Path("artifacts/fexrift")
sums = root / "SHA256SUMS"
lines = [s for s in sums.read_text().splitlines() if s.strip() and s.split()[-1].lstrip("*") != "fp_pipesend.exe"]
lines.append(hashlib.sha256((root / "fp_pipesend.exe").read_bytes()).hexdigest() + " fp_pipesend.exe")
sums.write_text("\n".join(lines) + "\n")
PY
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex setup
```
Setup uploads the extension automatically alongside the existing FEX artifacts. Without the exe, login must fail
with `fp_pipesend.exe missing: build native/fexwine/pipesend.c and upload it with fex setup`.
2. Record the Frame's current scheme owner (substitute its paired SSH destination for `FRAME`):
```sh
ssh steamos@FRAME 'xdg-mime query default x-scheme-handler/oculus'
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --timeout 900
```
Expect `Put on the headset: open 'Meta sign-in (FramePort)' in your Steam library.` Open that entry. Allow about
two minutes for the runtime warm-up. Confirm Meta's app is a flat window, not another VR game.
3. Choose Meta's sign-in action. Confirm Chromium opens **on the Frame**. The PC should print `Sign-in page opened
on the Frame.` Complete the real Meta sign-in. When Chromium asks to open an external app, accept it. This is the
unproven Flatpak boundary: OpenURI through xdg-desktop-portal must resolve the host's temporary `oculus` handler.
Expect `Sign-in response reached Meta's app on the Frame.` followed by `Signed in.` The CLI closes the app/runtime,
restores handlers and requests removal of the Steam entry. Check the Steam entry disappears after the shortcut
worker finishes; Steam may restart. The saved login must remain visible as `"login": true` in:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex status
ssh steamos@FRAME 'xdg-mime query default x-scheme-handler/oculus'
```
The second command must return the original owner (including no owner, if originally unset). Do not dump Meta
logs, sessions, CoreData, process argv or the full browser URL for debugging.
4. On an unsigned-in test prefix, or before completing the first sign-in, test the alternate launch route:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --start-now --timeout 900
```
Expect `Meta's app is starting on the Frame.` There should be no Steam restart and no new shortcut. After a
successful login already exists, this command can immediately report `Signed in.` and clean up; that does not
exercise a fresh browser exchange. Do not delete the owner's session files just to force this test.
5. If the portal never delivers the callback, cancel with Ctrl-C and use:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --start-now --via-pc --timeout 900
```
Click sign-in in the Frame's Meta window; the page must open in the PC browser. Expect `Sign-in page opened in
the PC browser.`, then the response/success messages above. On Windows/WSL, verify Meta's previous
`HKCU\Software\Classes\oculus` registration is restored; on Linux verify the original xdg default. This also
needs a real Windows default-protocol check: OS UserChoice policy can override a Classes registration.
6. To inspect progress without exposing URLs, use the ordinary agent status command from a second terminal:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run python - <<'PY'
import json
from frameport.cli import _fex_target
frame = _fex_target(None).frame
print(json.dumps(frame.agent("fex_login_status"), indent=2))
PY
```
Expected keys: `runtime_running`, `client_running`, `page_opened_at`, `callback_received_at`, `signed_in`. Runtime
should become true before client; timestamps should appear in that order; signed_in should become true only
after a non-empty session file exists. If callback_received_at appears but signed_in never becomes true on a
fresh sign-in, the **pipe framing remains unverified**: this implementation uses UTF-8 plus a terminating NUL.
Compare against the maintainer's successful spike sender's bytes without printing the URL. Do not retry by
starting a second Client.exe, altering entitlement checks, or exposing tokens in diagnostics.
7. Test cancellation during runtime warm-up, timeout with `--timeout 10`, and repeatable repair/undo:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --stop
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --stop
```
Expect `Meta sign-in stopped. Your saved login stays on the Frame.` both times. No delayed Client.exe should
appear after waiting two minutes. Status should show client/runtime false, the previous protocol owner should
be restored, and the session files should remain. If SSH was lost, the broker cleans up the Frame by its deadline;
reconnect and run `--stop` to remove a leftover shortcut or retry an interrupted restoration.
-276
View File
@@ -1,276 +0,0 @@
# Rift on Frame: performance stream
Implemented offline on `rift/perf`, from `98786ab`. No Frame measurements were made. Existing research measurements
are in `native/fexwine/README.md`; the commands below are for the maintainer to run on the paired Frame.
## What changed
`agent/fexrift_perf.py` registers `settings_get`, `settings_set`, `perf_prepare` and `bench`. Setup's existing `revive`
step also builds three Revive folders. The PC's existing artifact discovery uploads the extension automatically.
The only launcher template changes select the core list, Revive folder and motion-smoothing JSON from variables.
The agent and CLI have separate settings/bench blocks; the agent version is unchanged.
Settings live in `<ROOT>/settings/<Meta-app>.json`, separately from the game catalog. Defaults come from the game's
`perf` object, with the existing `env.FP_MEM` / `env.FP_BIGCACHE_MB` as backward-compatible defaults. Overrides take
precedence. `null` removes an override. Preparation runs on every launch, writes `<app>.dxvk.conf`, and exports
validated values before Wine starts. Updating a setting requires no reinstall after the new launcher is installed.
| Setting | Default | Accepted values / effect |
| --- | --- | --- |
| `dxvk_disable_msaa` | `false` | Boolean; `d3d11.disableMsaa` |
| `dxgi_sync_interval` | `-1` | Integer -1..4; `dxgi.syncInterval` |
| `dxgi_max_frame_latency` | `0` | Integer 0..16; `dxgi.maxFrameLatency` |
| `eye_scale` | `1.5` | Divisor 1.0 / 1.25 / 1.5 (100 / 80 / 67 percent nominal eye size) |
| `motion_smoothing` | `2` | 0 = default, 1 = force on, 2 = force off; SteamVR `motionSmoothingOverride` |
| `cores` | `4-7` | taskset CPU list within 0..7; e.g. `4-7` or `0-3,7` |
| `ntsync` | `true` | Off sets `PROTON_NO_NTSYNC=1`; on unsets it |
| `fp_mem` | per-game opt-in | Boolean; guest preload enabled only when true |
| `bigcache_mb` | `256` | Cache minimum block size, 1..6144 MiB (not the total cache budget) |
| `fp_mem_zero` | `false` | Boolean; `FP_MEM_ZERO=1` opts into lazy zero pages |
| `wine_large_address_aware` | `true` | Boolean; `WINE_LARGE_ADDRESS_AWARE=1/0` |
| `fex` | `{}` | JSON map of whitelisted keys with 0/1 values |
FEX keys: `FEX_TSOENABLED`, `FEX_VECTORTSOENABLED`, `FEX_MEMCPYSETTSOENABLED`, `FEX_MULTIBLOCK`,
`FEX_X87REDUCEDPRECISION`. The first three retain the launcher's default 0, MULTIBLOCK defaults to 1, X87 to 0.
Unknown keys, arbitrary environment variables, shell fragments and invalid paths are refused. The commands do not
inspect login files, print process command lines, or change Platform SDK/entitlement checks.
### Revive variants
The checked-in PC `REVIVE_PATCHES` contains the six visibility patches but **does not contain the research eye-size
redirect described in the brief**. Verified locally against the installed DLL's pinned upstream hash:
- Stock `LibRevive64.dll`: SHA-256 `ef9ffd5342bb4afad9b1c0f4fee1ca3bf32f9d3159d49dd841cc9e22f02663e4`.
- After the six PC patches: `eda2a449d230832c95734a03e8c83eeb531668ce676693f636e19c315765af4e`.
- RVA `0x12eab` (file `0x122ab`) is `movss xmm4,[rip+0x4bb15]`, loading a shared 1.0 constant.
- The research redirect loads the existing 1.5 at **RVA** `0x4eaa4` (file `0x4d4a4`). It is not file offset `0x4eaa4`.
The extension accepts the pinned six-patch upload, optionally with exactly that research redirect. It redirects
this one load into verified alignment padding at RVA `0x12e9c`, after the preceding function's `ret`. Each copy
gets its own divisor there. It leaves shared constants untouched. `revive-scales/{1,1.25,1.5}/` hard-links all other
files to `revive/`; the DLL is unlinked before writing, so variants and the base never modify one another. The
injector is launched from the selected folder, which is where it finds `LibRevive64.dll`.
Unexpected hashes, instructions or occupied padding fail explicitly. No Oculus binaries are patched here.
### fp_mem v3
`FP_MEM_ZERO=1` calls `madvise(MADV_DONTNEED)` on exactly the reused part before returning it: the requested prefix
for short/equal reuse, the cached prefix for a longer allocation. The fresh tail needs no advice. Failed advice
evicts the cache entry and falls through to real mmap, rather than returning stale contents. Without ZERO, v2's
unzeroed behavior remains. Debug output counts advice calls, discarded bytes and failures.
The fake-syscall host harness in `tests/test_fex_perf.py` checks equal, short and long reuse, advice failure,
unzeroed compatibility, and `FP_MEM_ZERO=0`. It skips only the C test when no host C compiler is installed.
The guest artifact has **not** been rebuilt in this stream. On an x86_64 glibc 2.34-compatible build host, from the
repository root, the maintainer must run:
```sh
gcc -O2 -shared -fPIC -o artifacts/fexrift/fp_mem.so native/fexwine/fp_mem.c -ldl -lpthread
python3 - <<'PY'
import hashlib
from pathlib import Path
root = Path('artifacts/fexrift')
manifest = root / 'SHA256SUMS'
lines = manifest.read_text().splitlines()
hash_ = hashlib.sha256((root / 'fp_mem.so').read_bytes()).hexdigest()
lines = [f'{hash_} ./fp_mem.so' if line.endswith(' ./fp_mem.so') else line for line in lines]
manifest.write_text('\n'.join(lines) + '\n')
PY
```
This is an **x86_64 guest** shared library, even though wineserver is native aarch64. Commit the rebuilt artifact
and checksum at integration. ZERO experiments with the old artifact would silently measure v2 instead.
## Benchmark behavior and limits
`frameport fex bench APP --seconds N` and `scripts/rift_fex_bench.py` each request exactly one run. N is an integer
1..120; it includes launcher/runtime startup, not just game sampling. The Frame enforces the deadline independently
of the PC connection. A bench lock excludes another bench. The agent first rejects active Lepton/FramePort games;
the helper rejects Wine/Proton/FEX processes, other Steam reapers, and Lepton container supervisors. It excludes
SteamVR's own AppId 250820 reaper. An open Meta login session also blocks the benchmark.
The helper requires `IVRSystem_022::GetTrackedDeviceActivityLevel(HMD)` to report **Standby (3)**. All other values,
including unknown, idle, recently interacting and interacting, are refused. A write to Steam's `logs/controller.txt`
within the last 60 seconds also blocks it (conservative: reconnection is enough). The same owner-activity checks run
while sampling; interaction stops the run. This does not claim to detect every desktop keyboard event; do not use
this headless tool while someone is using the Frame. A native non-Steam app outside Steam's reaper may also evade
the process guard. Do not run simultaneous Play/login/install operations against the shared prefix.
Before launch, read a positive finite `power/turnOffScreensTimeout`, set `power/pauseCompositorOnStandby=false`
through the existing `vrsetting` helper, and temporarily set the screen timeout to N+10. Start `launch.sh` in its
own process group. Finally, stop the shared-prefix wineserver (5-second limit), terminate/kill the launcher group,
set `pauseCompositorOnStandby=true`, and restore the original screen timeout. Each restoration is attempted even
when a preceding cleanup fails. SIGTERM and ordinary errors run this cleanup; SIGKILL, power loss or a dead SteamVR
service cannot execute Python's finally. The temporary screen timeout is finite even in those cases.
Every 0.5 seconds, read up to 128 compositor records via pinned `IVRCompositor_022::GetFrameTimings`. Deduplicate by
frame index, retain updated present counts, exclude the initial ring, and count only while scene focus belongs to
the game's PID. A hitch is one unique frame presented at least three times. GPU activity uses the actual game
process's DRM fdinfo engine-nanosecond deltas, deduplicating shared DRM client IDs; no debugfs permissions needed.
Thread wait states are histogrammed from the game's `/proc/<pid>/task/*/wchan` files. No shell commands or logs
containing account data enter the summary.
Successful stdout is one JSON line: effective settings, elapsed time, unique frames, `valid`, frame span, fps,
hitches (also per 20 seconds), average render GPU time and client frame interval, game GPU busy percent, and sampled
thread wait states. GPU busy is the sum of available engines and may exceed 100 percent on devices with independent
engines. `null` means unavailable, not zero. Client frame interval is **not CPU ApplicationTime**. `valid=false`,
zero frames or a short sample span means the launch produced insufficient data; do not treat it as a fast run.
Use equivalent spans and a stable scene when comparing results. A launcher exiting early is an error.
## Exact device checks
The maintainer runs these commands; this stream did not access the network or the Frame. Use the account owner's
normal sign-in workflow from the login stream. A missing entitlement is a failed run to report, never bypass.
1. Build/checksum the guest artifact above. From this worktree on the PC:
```sh
export FRAMEPORT_HOME="$PWD/.home"
export FRAMEPORT_EXPERIMENTAL_FEX=1
uv run frameport fex setup
uv run frameport fex install oculus-first-contact
uv run frameport fex settings oculus-first-contact
```
Setup should complete the `revive` step and create all three scale folders. Install once to get the new launcher.
Settings should show fp_mem on, threshold 256, eye divisor 1.5, motion smoothing 2, cores 4-7 and ntsync on.
Run the Frame helper with `python3 -I` as usual; no additional pip packages are needed there.
2. Wear the headset once after boot, then remove it and let it reach standby. End every game and the Meta client;
wait at least 60 seconds after controller input. A worn headset or a running game must make bench refuse **before
changing display settings**. Do not work around a refusal by disabling the checks.
3. Establish a baseline, then run exactly one bounded experiment per command pair below. Each line is independent;
restore the previous changed key with `null` before moving to the next experiment.
```sh
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=false dxgi_sync_interval=-1 dxgi_max_frame_latency=0 eye_scale=1.5 motion_smoothing=2 cores=4-7 ntsync=true fp_mem=true bigcache_mb=256 fp_mem_zero=false 'fex={}' wine_large_address_aware=true
uv run frameport fex bench oculus-first-contact --seconds 120
```
Expected: one summary JSON, `valid=true`, nonzero frames, finite fps/GPU timings; DRM busy may be null if fdinfo
is unavailable. After it returns, the game/runtime should be gone and the headset should sleep normally.
`launch.log` in the game's anchor should contain `FramePort: starting Meta's runtime` and
`FramePort: starting Oculus First Contact`. No rendering with `r.MobileMSAA=2` was proven; do not use that knob.
4. Run these candidate experiments separately, returning to the baseline between them:
```sh
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=true
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=null
uv run frameport fex settings oculus-first-contact dxgi_max_frame_latency=1
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact dxgi_max_frame_latency=null
uv run frameport fex settings oculus-first-contact eye_scale=1.25
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact eye_scale=null
uv run frameport fex settings oculus-first-contact 'fex={"FEX_X87REDUCEDPRECISION":1}'
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact fex=null
uv run frameport fex settings oculus-first-contact wine_large_address_aware=false
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact wine_large_address_aware=null
uv run frameport fex settings oculus-first-contact ntsync=false
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact ntsync=null
uv run frameport fex settings oculus-first-contact fp_mem_zero=true
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact fp_mem_zero=null
```
The baseline covers eye divisor 1.5, ntsync on, and ZERO off. MSAA off previously improved GPU load but reduced
edge quality. Compare hitches, frame span, GPU time and thread wait distributions; this stream makes no claim
that X87 or large-address-awareness helps. GE may ignore the latter for a 64-bit game. Test image quality later
in an ordinary worn-headset Play session; the headless bench intentionally refuses that session.
Script alternative for a single run (do not run this in addition unless another run is intended):
```sh
uv run python scripts/rift_fex_bench.py oculus-first-contact --seconds 120
```
5. Interrupt a run by sending SIGTERM to the `python3 -I .../fexrift.py bench` helper **on the Frame**, after checking
its PID with `pgrep -af '[f]exrift.py bench'`. Use `kill -TERM <that-pid>` (never a broad pkill). Expected: interrupted
result, game stopped, compositor standby enabled and original screen timeout restored. Also check refusal while
the headset is worn and a deliberately invalid setting, e.g. `eye_scale=1.4`, without launching anything.
On the Frame, this reads the two settings without printing any account data:
```sh
python3 -I - <<'PY'
import ctypes as C, importlib.util, os
path = os.path.expanduser('~/.local/share/frameport/fexrift/artifacts/fexrift.py')
spec = importlib.util.spec_from_file_location('fx', path)
fx = importlib.util.module_from_spec(spec); spec.loader.exec_module(fx)
core, method, settings = fx.vr_settings()
try:
for key, idx, typ in [('pauseCompositorOnStandby', 5, C.c_bool), ('turnOffScreensTimeout', 7, C.c_float)]:
err = C.c_int()
value = method(settings, idx, typ, C.c_char_p, C.c_char_p, C.POINTER(C.c_int))(
b'power', key.encode(), C.byref(err))
print(key, value, 'error', err.value)
finally:
method(core, 1, None)()
PY
```
Record these values before the test. Afterwards expect `pauseCompositorOnStandby True error 0` and the original
positive timeout with error 0. Confirm the physical display sleeps. With guest `FP_MEM_DEBUG=1`, ZERO reuse logs
should show `fp_mem: zero calls ..., bytes ..., failures 0`. This debug variable can be set manually in a test
launcher for one run; remove that line afterwards (it is deliberately outside the user environment whitelist).
## Undo and remaining device questions
Reset every override (no login or game files removed):
```sh
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=null dxgi_sync_interval=null dxgi_max_frame_latency=null eye_scale=null motion_smoothing=null cores=null ntsync=null fp_mem=null bigcache_mb=null fp_mem_zero=null fex=null wine_large_address_aware=null
```
To remove this experiment entirely, restore the integration's previous launcher/module and guest artifact, then
remove only `settings/<app>.json`, `settings/<app>.dxvk.conf` and `revive-scales/` after stopping all FEX games.
Do not remove `compat/pfx`; it holds the owner's login and installed games. For emergency display restoration on the
Frame (replace 300 with the previously recorded timeout):
```sh
R="$HOME/.local/share/frameport/fexrift"
python3 -I "$R/artifacts/fexrift.py" vrsetting '{"section":"power","key":"pauseCompositorOnStandby","kind":"b","value":true}'
python3 -I "$R/artifacts/fexrift.py" vrsetting '{"section":"power","key":"turnOffScreensTimeout","kind":"f","value":300}'
```
Unverified: SteamVR's availability of the pinned historical compositor/system interfaces; whether scene focus PID
matches the FEX game's host PID; whether the HMD reports Standby while compositor rendering is forced; how many
usable game frames remain after runtime startup within 120 seconds; fdinfo visibility on this OS; the cost of ZERO
on the device; all visual/entitlement behavior for other games. Failures must stay visible, not be replaced by fake
performance numbers. If startup consumes the window, report `valid=false` and adjust startup in the owning stream
before drawing conclusions; do not silently extend the bounded run.
## Offline validation and integration
Run `uv run pytest -q` in a normal environment and `uv run python scripts/patch_docs.py --check`. In this sandbox,
use a writable UV cache and the already installed environment:
```sh
UV_CACHE_DIR=/tmp/frameport-perf-uv uv run --offline --no-sync pytest -q
UV_CACHE_DIR=/tmp/frameport-perf-uv uv run --offline --no-sync pytest -q tests/test_fex_perf.py tests/test_fexrift.py tests/test_fexrift_ext.py
```
The original worktree's Git common directory is mounted read-only. Commits are therefore in the local, writable
repository `/tmp/frameport-rift-perf.git` (same base and `rift/perf` ref) and exported as
`/tmp/frameport-rift-perf.bundle`. The worktree contains the complete edits. A maintainer with writable original
Git metadata can fetch that bundle and fast-forward/cherry-pick the commits; do not discard the worktree edits
until integration is confirmed. Local-only instruction files and `.home` are excluded from every commit.
Validation result in this environment: 80 focused tests passed, 1 skipped; Ruff passed for the three new Python
files; `scripts/patch_docs.py --check` passed; `git diff --check` passed. The full suite ran: **1676 passed,
43 skipped, 11 failed, 16 errors**. Every remaining failure/error raised `PermissionError: [Errno 1] Operation not
permitted` when existing pairing/download/live-stream tests attempted to create sockets. This sandbox forbids
sockets, including loopback; these tests were not disabled or modified. A clean full-suite pass remains an
integration check in a normal environment. The complete short traceback log is
`/tmp/frameport-rift-perf-pytest.log`.
-54
View File
@@ -1,54 +0,0 @@
# Rift through FEX: what RiftLift and xrizer teach this branch
Reviewed 2026-10-17: [Villagers654/RiftLift](https://github.com/Villagers654/RiftLift) at `20a91ff` (0.11.1.2, MIT;
a Revive-derived Oculus runtime + Meta sign-in/downloads, Windows and Linux/GE-Proton) and
[Supreeeme/xrizer](https://github.com/Supreeeme/xrizer) at `63fc7eb` (OpenVR implemented on OpenXR, Rust,
**GPL-3.0**: ideas only, no code copied). RiftLift lists Lone Echo, Lone Echo 2, Stormland, First Contact and Vader
Immortal I as rendering on Linux (desktop GPUs, x86_64; not under FEX, not on a Frame).
## Adopted on this branch
| From | What | Where |
|---|---|---|
| RiftLift `detection.py` | LibOVR / Platform SDK / OpenVR / Unity facts from the game's files + delay imports | `fexrift_compat.oculus_facts` |
| RiftLift `_select_runtime_backend` | Route by capabilities, never a title list: OpenVR builds without the Platform SDK skip Revive *and* Meta's runtime (no OVRServer/OVRLibrarian under FEX) | `vr_route`, launch.sh `FP_META_RUNTIME` |
| RiftLift `oculus_launch_arguments` | Engine VR switch when the arguments don't choose one (Unreal `-vr`; Unity `-vrmode`, here `OpenVR` on the direct route) | `vr_args` (unverified games only) |
| RiftLift `DEBUG_WINE_CHANNELS` | One opt-in Wine debug profile (loader, wintrust/chain, openxr/vrclient) instead of ad-hoc WINEDEBUG edits | `<anchor>/debug-wine` |
Details and limits: [compat.md](compat.md#route-and-vr-arguments-from-the-builds-files). None of it is
headset-verified yet; First Contact's verified launch is unchanged.
## Not adopted (FramePort rules)
- **RiftLift's Platform SDK shim** (`compat/riftlift-platform-shim.c`) replaces `LibOVRPlatformImpl64_1.dll` and
answers `ovr_Entitlement`, login and user-proof requests locally (fixed user id). RiftLift gates *downloads* on
ownership, but at run time this is an entitlement bypass. FramePort never changes entitlement or Platform SDK
answers: this branch keeps Meta's own runtime answering them (and "Missing entitlement" stays a correct result).
- **Making the redirected runtime load past the Oculus signature check.** RiftLift's runtime patches the game exe's
import table (`PatchMainImport`: `LoadLibrary*`, `GetModuleHandle*`, `OpenEventW`) because Detours on kernel32
alone may miss calls that Wine binds straight to kernelbase. That would explain our 2026-10-17 local finding
("Revive's LoadLibrary hooks don't take effect even on x86_64 Wine"; untested). Combined with
`GetModuleHandle("LibOVRRT64_1.dll")` returning the Revive module, the static LibOVR shim can end up using a
runtime that never passed its Authenticode check, which CLAUDE.md rules out.
The branch doesn't need it: Meta's signed `LibOVRRT64_1.dll` (on PATH) loads normally while OVRServer runs.
An IAT-patched `LoadLibrary`/`OpenEventW` *without* the GetModuleHandle part would be a pure runtime substitution
(like `pcvr.libovr_redirect` on main) and is worth a separate owner decision for main's Proton-arm64 path.
## Worth doing next (owner decisions)
1. **Meta sign-in and owned games without the Electron app** (RiftLift `meta_auth.py`, `entitlements.py`): Meta's
native-SSO flow (`auth.meta.com/native_sso/confirm` → `meta.graph.meta.com`) on the PC, then
`graph.oculus.com/graphql` (`active_entitlements`, PC items) lists owned Rift apps. FramePort could offer a
"your Meta library" list and install owned games from Meta's CDN with `meta_fetch_app` (segment + file SHA-256 are
already checked). The runtime in the Frame prefix still needs its own signed-in session for the Platform SDK, so
this replaces the *library and download* half of `fex login`, not the runtime sign-in.
2. **An OpenXR route for OVRPlugin builds** (RiftLift `openxr-layer`, xrizer's design): newer Unity/Unreal Oculus
integrations talk OpenXR and refuse runtimes not named "Oculus"; RiftLift's layer reports `runtimeName` "Oculus"
to clients named "Oculus VR Plugin". On the Frame this also needs the x86_64 build of FramePort's timefix layer
(SteamVR accepts only OpenXR 1.0) and a fix for wineopenxr's `openxr_vulkan_instance_extensions` error.
3. **DXVK fence fix** (RiftLift `components/dxvk/monotonic-fence-signals.patch`): skips non-increasing timeline
semaphore signals from shared D3D11 fences. Only relevant if a Revive-composited game shows VK device-lost or
fence validation errors; GE's DXVK is unpatched.
4. **xrizer** itself doesn't fit the Frame: SteamVR is the native OpenVR runtime there, and xrizer would only
add a translation (OpenVR → OpenXR → SteamVR). Its input layer (action manifests, legacy input, per-controller
profiles) is a good reference if Revive's Touch bindings need work on the Frame controllers.
-60
View File
@@ -1,60 +0,0 @@
# x86_64 Wine under FEX: Rift games with Meta's runtime on the Frame (experimental)
Sources of `artifacts/fexrift/` (prebuilt, with `SHA256SUMS`) for the experimental mode `frameport fex ...`
(FRAMEPORT_EXPERIMENTAL_FEX=1; PC side `src/frameport/fexrift.py`, Frame side `agent/fexrift.py`). Research notes:
CLAUDE.md, "Rift via x86_64 Wine under FEX". Rebuild order: `prep_ge_wine.sh` (GE's exact Wine source) ->
`build_pe_dlls.sh` (x86_64 host, llvm-mingw) + `build_wineserver.sh` (aarch64 host, e.g. the Frame; then `strip`) +
fp_mem.so (command below).
| File | What |
|---|---|
| `pipesend.c` | `fp_pipesend.exe`, built by `build_pe_dlls.sh` with llvm-mingw. Sends a browser's `oculus://link/frl_login` callback into the running Meta app's `\\.\pipe\oculus`; reads UTF-8 from stdin so SSH forwarding never puts credentials in argv. Retries a busy/missing pipe for 20 seconds. Does not print the link. Add the rebuilt exe to `artifacts/fexrift/SHA256SUMS`. Pipe framing still needs the device check in `docs/rift-fex/login.md`. |
| `prep_ge_wine.sh` | Recreates the exact Wine source of a GE-Proton release (its Wine and wine-staging submodules plus GE's patches) by running only the WINE section of GE's `protonprep-valve-staging.sh`. |
| `build_wineserver.sh` | Builds a **native aarch64 wineserver** from that tree on an aarch64 host (the Frame has gcc, make, flex and bison). It speaks the same protocol as GE's x86_64 server (GE-Proton11-7: protocol 938, 321 requests; plain Valve Wine at the same commit lacks 15 of GE's requests). `-DFP_EMULATED_X86_64` gives it the x86_64 machine model, because its clients are x86_64 processes under FEX. Use it by having the `wineserver` wrapper exec it instead of the FEX-run x86_64 server. |
| `build_pe_dlls.sh` + `patches/` | The four Wine DLLs FramePort replaces in GE-Proton, built from GE's tree + only these patches: `crypt32-chain-newest-issuer` (Windows' newest-issuer rule between equal chains: Meta's OculusAppFramework signer check needs the 4-certificate chain), `sechost-realtime-trace-consumer` (OpenTraceW real-time sessions: the runtime's ETW USB tracing), `dnsapi-dnsservice-functions` (DnsService* from Wine 11.19: Air Link mDNS, OVRServer quits without them), `devenum-devicewatcher-handlers` (DeviceWatcher Updated/Removed handler lists). Exports equal GE's (+8 DnsService*). Also builds `windows.devices.wifi.dll` from `wifi_stub.c`: a Windows.Devices.WiFi.WiFiAdapter class (GetDeviceSelector matches nothing) that the logged-in runtime needs. |
| `fp_mem.c` | x86_64 `LD_PRELOAD` for the guest. `FP_BIGCACHE_MB=<n>` keeps released anonymous regions of at least n MB (up to 12, 6 GB in total) and returns them when the same start address is mapped again; a shorter request releases the rest, a longer one maps only the extra part fresh. In the headset First Contact allocated 0.5-1.6 GB blocks several times at once, which the first, single-block version missed. `FP_MEM_ZERO=1` (v3) lazily zeroes only the reused range with `MADV_DONTNEED` before returning it; unset keeps v2 behavior. Debug counters report advice calls/bytes/failures. `FP_THP=1` sets `MADV_HUGEPAGE` on large writable regions. From the repo root on the build host, build with `gcc -O2 -shared -fPIC -o artifacts/fexrift/fp_mem.so native/fexwine/fp_mem.c -ldl -lpthread` on an x86_64 host (needs glibc 2.34). **Under FEX, pass it as `FEX_ENV=LD_PRELOAD=<path>`**: Valve's `fex-compat-tool` deletes `LD_PRELOAD`. |
## Measurements: Oculus First Contact, headless, dev Frame, 2026-10-10
SteamVR compositor frame timings were read through `IVRCompositor::GetFrameTimings`.
| Setup | Hitches per 20 s | Frames timed out | Game CPU per frame |
|---|---|---|---|
| FEX-run x86_64 wineserver, server sync | 17 | 40 % | 10.4 ms |
| Native wineserver, server sync | 9 | 32 % | 10.4 ms |
| Native wineserver + ntsync | 0-4 | 9-10 % | 6.2 ms |
| Native wineserver + ntsync + `FP_BIGCACHE_MB=256` | **0** (3 of 3 runs) | 5.4-5.9 % | 5.3 ms |
Each remaining hitch (one app frame shown about 9 times) was Unreal's large-block allocator:
1. It calls VirtualAlloc for 514 MB (First Contact's exe RVA 0x1a188e) every 1-8 s.
2. A game task fills the block with a single `rep stos`/`rep movs` while the game thread waits for it.
3. Another thread then frees the block.
Under FEX every 4 KiB page of it faults in and gets zeroed and charged by the kernel: about 130k faults and 110-140 ms per hitch.
Huge pages work in isolation (514 MB in 22 ms instead of 212 ms), but fail in practice. On a Frame that has been up for a while, memory is fragmented, so allocations fall back to 4 KiB pages (`thp_fault_fallback` far above `thp_fault_alloc`). The kernel's `defrag=madvise` setting also lets those attempts stall in compaction.
The block cache returns the region with stale contents instead of zeroed pages. That is only safe for games that overwrite the whole block, so it has to stay a per-game setting.
## Launch-time experiments and bounded measurements
The First Contact numbers above are research measurements, not new results from the perf extension. Subsequent
owner tests found the remaining bottleneck to be GPU work: about 55 percent game GPU busy at 36 fps, about
20 percent for the compositor, and 5–10 ms CPU ApplicationTime. With per-app motion smoothing off, it reached
72 fps with occasional misses. DXVK `d3d11.disableMsaa=True` reduced measured game GPU busy from 91 to 69 percent;
the owner reported much better performance and rougher edges. `r.MobileMSAA=2` prevented rendering.
`agent/fexrift_perf.py` adds validated per-game settings read at every launch, including MSAA, frame latency,
Revive eye-size divisors, core affinity, ntsync, guest cache options and a small FEX environment whitelist.
`FP_MEM_ZERO=1` restores zero-page semantics for cache reuse, with the cost of page faults on later touches.
When advice fails the region is evicted and mapped fresh. ZERO is opt-in; the default cache remains unzeroed.
The host test uses fake mmap/munmap/madvise to check full, short and long reuse and advice-failure fallback.
The real x86_64 guest artifact and its checksum must be rebuilt by the maintainer before ZERO experiments.
`frameport fex bench APP --seconds 120` requests one headless run with a total launch/sampling window of at most
120 seconds, then stops Wine and the launcher and restores compositor standby and the screen timeout. It refuses
an active game/login or a headset outside standby. It reports deduplicated compositor frame timings, hitches
(frames presented at least three times), game DRM fdinfo GPU deltas and sampled thread wait states. These new
paths have only offline tests; the pinned OpenVR interfaces and process attribution need device validation.
See [the perf stream notes](../../docs/rift-fex/perf.md) for exact build, baseline, experiment and undo commands.
-41
View File
@@ -1,41 +0,0 @@
#!/bin/bash
# Build the four patched Wine PE DLLs FramePort adds to GE-Proton for the Meta runtime (see README.md), from GE's
# exact Wine source (prep_ge_wine.sh) + patches/*.patch, on an x86_64 Linux host with llvm-mingw on PATH.
# Only these DLLs are built: generated headers they don't use (Vulkan thunks) are empty stand-ins, the syscall
# tables come from Wine's own tools/make_specfiles.
# usage: build_pe_dlls.sh <patched GE wine dir (prep_ge_wine.sh)> <work dir> <out dir>
set -e
SRC=$(cd "$1" && pwd); W=$2; OUT=$3
HERE=$(cd "$(dirname "$0")" && pwd)
[ -n "$OUT" ] || { echo "usage: $0 <wine dir> <work dir> <out dir>"; exit 2; }
command -v x86_64-w64-mingw32-clang >/dev/null || { echo "llvm-mingw (x86_64-w64-mingw32-clang) must be on PATH"; exit 2; }
mkdir -p "$W" "$OUT"; W=$(cd "$W" && pwd); OUT=$(cd "$OUT" && pwd)
if [ ! -d "$W/wine" ]; then
cp -a "$SRC" "$W/wine"
for p in "$HERE"/patches/*.patch; do patch -d "$W/wine" -p1 -s < "$p"; echo "applied $(basename "$p")"; done
(cd "$W/wine" && perl tools/make_specfiles >/dev/null)
for f in include/wine/vulkan.h dlls/winevulkan/loader_thunks.c dlls/winevulkan/loader_thunks.h \
dlls/winevulkan/vulkan_thunks.c dlls/winevulkan/vulkan_thunks.h dlls/winevulkan/winevulkan.json; do
[ -e "$W/wine/$f" ] || : > "$W/wine/$f"
done
fi
mkdir -p "$W/obj"
if [ ! -f "$W/obj/Makefile" ]; then
# no debug info and relative source paths: the DLLs are committed (no local paths may end up in them)
(cd "$W/obj" && CROSSCFLAGS="-O2 -ffile-prefix-map=$W/wine=wine -ffile-prefix-map=$W/obj=obj" \
"$W/wine/configure" --enable-archs=x86_64 --disable-tests --without-x --without-freetype \
--without-wayland --without-gstreamer --without-pulse --without-alsa --without-oss --without-cups --without-dbus \
--without-gnutls --without-krb5 --without-netapi --without-opencl --without-pcap --without-sane --without-udev \
--without-usb --without-v4l2 --without-vulkan --without-sdl --without-capi --without-gphoto --without-fontconfig \
--without-coreaudio --without-opengl --without-inotify --without-unwind --without-ffmpeg > configure.log 2>&1)
fi
DLLS="crypt32 sechost dnsapi windows.devices.enumeration"
cd "$W/obj"
make -j"$(nproc)" $(for d in $DLLS; do echo "dlls/$d/x86_64-windows/$d.dll"; done) > make.log 2>&1 || { tail -20 make.log; exit 1; }
for d in $DLLS; do cp "dlls/$d/x86_64-windows/$d.dll" "$OUT/"; done
# Wi-Fi WinRT stand-in (not a Wine DLL: goes into the prefix's system32 + its activation class registry key)
x86_64-w64-mingw32-clang -O2 -shared -s -Wl,--no-insert-timestamp -o "$OUT/windows.devices.wifi.dll" \
"$HERE/wifi_stub.c" "$HERE/wifi_stub.def" -lole32 -lwindowsapp
# Meta's single-instance pipe, used by browser sign-in (no entitlement or Platform SDK changes).
x86_64-w64-mingw32-clang -O2 -s -Wl,--no-insert-timestamp -o "$OUT/fp_pipesend.exe" "$HERE/pipesend.c"
ls -la "$OUT"
-42
View File
@@ -1,42 +0,0 @@
#!/bin/bash
# Build a native aarch64 wineserver from a patched GE Wine tree (prep_ge_wine.sh), for x86_64 Wine under FEX.
# Run it ON an aarch64 Linux host (e.g. the Frame: gcc, make, flex, bison, autoconf are in SteamOS).
# - Wine's configure insists on a PE cross compiler for aarch64 and on generated headers this tree lacks; the server
# needs neither, so configure only produces include/config.h here and the server sources are compiled directly.
# - -DFP_EMULATED_X86_64: the server takes the x86_64 branch of init_supported_machines (native machine AMD64), as
# the clients are x86_64 processes under FEX; otherwise it would advertise ARM64 and refuse/misplace x86_64 images.
# The result talks the same protocol as GE's x86_64 wineserver (check: SERVER_PROTOCOL_VERSION and the request list).
# usage: build_wineserver.sh <patched wine dir> <build dir> → <build dir>/ws/wineserver
set -e
SRC=$(cd "$1" && pwd); B=$2
[ -n "$B" ] || { echo "usage: $0 <wine dir> <build dir>"; exit 2; }
[ "$(uname -m)" = aarch64 ] || { echo "run this on aarch64"; exit 2; }
mkdir -p "$B/obj" "$B/ws"; B=$(cd "$B" && pwd)
grep -q FP_EMULATED_X86_64 "$SRC/server/registry.c" || \
sed -i 's/^#elif defined(__x86_64__)$/#elif defined(__x86_64__) || (defined(__aarch64__) \&\& defined(FP_EMULATED_X86_64))/' "$SRC/server/registry.c"
grep -q FP_EMULATED_X86_64 "$SRC/server/registry.c" || { echo "registry.c layout changed"; exit 1; }
if [ ! -f "$B/obj/include/config.h" ]; then
cp "$SRC/configure" "$B/configure.fp"
sed -i 's/as_fn_error $? "PE cross-compilation is required/echo "(ignored) PE cross-compilation is required/' "$B/configure.fp"
# configure.fp must run from the source dir's point of view: copy it in, run, remove
cp "$B/configure.fp" "$SRC/configure.fp"
(cd "$B/obj" && "$SRC/configure.fp" --srcdir="$SRC" --without-mingw --without-x --without-wayland --without-freetype \
--without-gstreamer --without-vulkan --without-opengl --without-pulse --without-alsa --without-sdl --without-udev \
--without-usb --without-gnutls --without-cups --without-dbus --without-krb5 --without-netapi --without-pcap \
--without-sane --without-v4l2 --without-gphoto --without-unwind --without-ffmpeg --disable-tests > configure.log 2>&1 || true)
rm -f "$SRC/configure.fp"
[ -f "$B/obj/include/config.h" ] || { echo "configure did not produce include/config.h (see $B/obj/configure.log)"; exit 1; }
fi
cd "$B/ws"
# -ffile-prefix-map: the artifact is committed to a public repo, keep the build folders out of its assert paths
CF="-c -O2 -g -pipe -fno-strict-aliasing -D__WINESRC__ -D_GNU_SOURCE -DFP_EMULATED_X86_64 -ffile-prefix-map=$SRC=wine -ffile-prefix-map=$B=build -I. -I$B/obj/include -I$SRC/include -I$SRC/server"
for s in $(grep -oE "^\s+[a-z_0-9]+\.c" "$SRC/server/Makefile.in" | tr -d "\t "); do
extra=()
case $s in
unicode.c) extra=('-DBINDIR="/usr/bin"' '-DDATADIR="/usr/share"') ;; # nls dir = <bin>/../share/wine/nls
user.c) extra=(-include stdarg.h) ;;
esac
gcc $CF "${extra[@]}" -o "${s%.c}.o" "$SRC/server/$s"
done
gcc -o wineserver ./*.o -lrt -lm
echo "built $B/ws/wineserver (protocol $(grep -oE "SERVER_PROTOCOL_VERSION [0-9]+" "$SRC/include/wine/server_protocol.h" | awk '{print $2}'))"
-209
View File
@@ -1,209 +0,0 @@
/* fp_mem.so: x86_64 LD_PRELOAD for Wine under FEX (give it to the guest with FEX_ENV=LD_PRELOAD=..., the FEX
* compat tool strips LD_PRELOAD).
*
* FP_BIGCACHE_MB=<n>: keep the pages of released anonymous regions of >= n MB (up to FP_BIGCACHE_SLOTS regions,
* default 12, and FP_BIGCACHE_MAX_MB in total, default 6144) and hand them back when Wine maps memory at the
* same start address again. Unreal's large-block allocator gives blocks above its cache limit straight back to
* the OS, and some games (Oculus First Contact: 0.5-1.4 GB every few seconds while playing) fill such blocks
* completely each time: under FEX every 4 KB page then faults and is zeroed by the kernel (~130k faults, ~110 ms)
* and releasing them costs about as much again, on a game task the game thread waits for.
* Same start, other size: shorter = the rest is released; longer = only the extra part is mapped fresh.
* Reused memory is NOT zeroed (Windows guarantees zeroed commits), so this is only for games that overwrite
* the whole block; any other use of a kept range drops it first (fresh zero pages).
* Kept regions keep their protection (they are not touched while kept), so keeping and reusing is nearly free.
* FP_MEM_ZERO=1: MADV_DONTNEED the reused part before returning it (lazy kernel zero-fill). Unlike the default
* unzeroed cache this preserves anonymous zero-page semantics; it trades the saved page faults for correctness.
* FP_THP=1: MADV_HUGEPAGE on large writable anonymous regions (only helps while 2 MB pages are free).
* FP_MEM_DEBUG=1: log to stderr. */
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#define MAX_SLOTS 16
static size_t cache_min, cache_max = (size_t)6144 << 20, thp_min = (size_t)32 << 20;
static int debug, thp, zero, slots = 12;
static int (*real_mprotect)(void *, size_t, int);
static int (*real_munmap)(void *, size_t);
static void *(*real_mmap)(void *, size_t, int, int, int, off_t);
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct entry { char *addr; size_t len; int prot, via_munmap, used; };
static struct entry cache[MAX_SLOTS];
static size_t kept_total;
static unsigned long hits, partial, stores, drops, zero_calls, zero_failures;
static size_t zero_bytes;
static void resolve(void)
{
if (!real_mmap) real_mmap = dlsym(RTLD_NEXT, "mmap");
if (!real_munmap) real_munmap = dlsym(RTLD_NEXT, "munmap");
if (!real_mprotect) real_mprotect = dlsym(RTLD_NEXT, "mprotect");
}
__attribute__((constructor)) static void fp_mem_init(void)
{
const char *e;
resolve();
debug = getenv("FP_MEM_DEBUG") != NULL;
thp = getenv("FP_THP") != NULL;
zero = (e = getenv("FP_MEM_ZERO")) && !strcmp(e, "1");
if ((e = getenv("FP_BIGCACHE_MB")) && atol(e) > 0) cache_min = (size_t)atol(e) << 20;
if ((e = getenv("FP_BIGCACHE_MAX_MB")) && atol(e) > 0) cache_max = (size_t)atol(e) << 20;
if ((e = getenv("FP_BIGCACHE_SLOTS")) && atoi(e) > 0) slots = atoi(e) > MAX_SLOTS ? MAX_SLOTS : atoi(e);
}
static void advise(void *addr, size_t len)
{
uintptr_t s = ((uintptr_t)addr + 0x1fffff) & ~(uintptr_t)0x1fffff;
uintptr_t e = ((uintptr_t)addr + len) & ~(uintptr_t)0x1fffff;
if (e > s) madvise((void *)s, e - s, MADV_HUGEPAGE);
}
/* lock held: give part of a kept range up the way the program asked for it originally */
static void release_range(const struct entry *c, char *addr, size_t len)
{
if (c->via_munmap) real_munmap(addr, len);
else real_mmap(addr, len, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_NORESERVE, -1, 0);
}
static void drop(struct entry *c, const char *why)
{
if (debug) fprintf(stderr, "fp_mem: drop %p+%zx (%s)\n", c->addr, c->len, why);
release_range(c, c->addr, c->len);
kept_total -= c->len; c->used = 0; drops++;
}
/* lock held: drop every kept range overlapping [addr, len) */
static void drop_overlaps(const void *addr, size_t len, const char *why)
{
for (int i = 0; i < slots; i++)
if (cache[i].used && (const char *)addr < cache[i].addr + cache[i].len && cache[i].addr < (const char *)addr + len)
drop(&cache[i], why);
}
static int any_kept(void)
{
for (int i = 0; i < slots; i++) if (cache[i].used) return 1;
return 0;
}
/* lock held: keep [addr, len) instead of releasing it (its pages and protection stay as they are) */
static int store(void *addr, size_t len, int via_munmap, int prot)
{
int free_slot = -1;
if (kept_total + len > cache_max) return 0;
for (int i = 0; i < slots; i++) {
if (!cache[i].used) { if (free_slot < 0) free_slot = i; continue; }
if ((char *)addr < cache[i].addr + cache[i].len && cache[i].addr < (char *)addr + len) return 0;
}
if (free_slot < 0) return 0;
cache[free_slot] = (struct entry){ addr, len, prot, via_munmap, 1 };
kept_total += len; stores++;
if (debug) fprintf(stderr, "fp_mem: keep %p+%zx (%s, kept %zu MB in total; stores %lu, hits %lu, partial %lu, drops %lu; "
"zero calls %lu, bytes %zu, failures %lu)\n",
addr, len, via_munmap ? "munmap" : "release", kept_total >> 20, stores, hits, partial, drops,
zero_calls, zero_bytes, zero_failures);
return 1;
}
/* lock held: discard only the part about to be reused, including a short request's kept prefix. On failure the
* caller falls through to overlap eviction + a real mmap: ZERO must never hand stale contents to the guest. */
static int zero_reused(void *addr, size_t len)
{
if (!zero) return 0;
zero_calls++;
int r = madvise(addr, len, MADV_DONTNEED);
if (r) zero_failures++;
else zero_bytes += len;
if (debug) fprintf(stderr, "fp_mem: zero calls %lu, bytes %zu, failures %lu\n",
zero_calls, zero_bytes, zero_failures);
return r;
}
/* protection of a region before it is released: unknown here, so assume read/write (Wine's committed views) */
#define KEPT_PROT (PROT_READ | PROT_WRITE)
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off)
{
resolve();
if (cache_min && len >= cache_min / 4 && any_kept()) {
pthread_mutex_lock(&lock);
for (int i = 0; i < slots; i++) {
struct entry *c = &cache[i];
if (!c->used || (char *)addr != c->addr || fd != -1 || !(flags & MAP_ANONYMOUS) || !(prot & PROT_WRITE)) continue;
if (len <= c->len) {
if (prot != c->prot && real_mprotect(addr, len, prot)) break;
if (zero_reused(addr, len)) break;
if (len < c->len) { release_range(c, c->addr + len, c->len - len); partial++; }
kept_total -= c->len; c->used = 0; hits++;
if (debug) fprintf(stderr, "fp_mem: reuse %p+%zx of %zx\n", addr, len, c->len);
pthread_mutex_unlock(&lock);
return addr;
}
/* longer: map the extra part fresh behind the kept one */
void *t = real_mmap(c->addr + c->len, len - c->len, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
if (t == (void *)(c->addr + c->len)) {
int protect_failed = prot != c->prot && real_mprotect(c->addr, c->len, prot);
if ((zero && protect_failed) || zero_reused(c->addr, c->len)) {
real_munmap(t, len - c->len);
break;
}
kept_total -= c->len; c->used = 0; hits++; partial++;
if (debug) fprintf(stderr, "fp_mem: reuse %p+%zx of %zx (+ fresh tail)\n", addr, len, c->len);
pthread_mutex_unlock(&lock);
if (thp && len - c->len >= thp_min) advise(t, len - c->len);
return addr;
}
if (t != MAP_FAILED) real_munmap(t, len - c->len);
break;
}
pthread_mutex_unlock(&lock);
}
if (cache_min && len >= cache_min && (flags & MAP_ANONYMOUS) && (flags & MAP_FIXED) && prot == PROT_NONE && fd == -1) {
/* Wine releasing (part of) a view inside its reserved areas */
pthread_mutex_lock(&lock);
int ok = store(addr, len, 0, KEPT_PROT);
pthread_mutex_unlock(&lock);
if (ok) return addr;
}
if (any_kept()) {
pthread_mutex_lock(&lock);
drop_overlaps(addr, len, "mmap overlap");
pthread_mutex_unlock(&lock);
}
void *r = real_mmap(addr, len, prot, flags, fd, off);
if (thp && r != MAP_FAILED && (flags & MAP_ANONYMOUS) && (prot & PROT_WRITE) && len >= thp_min) advise(r, len);
return r;
}
void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off_t off) __attribute__((alias("mmap")));
int munmap(void *addr, size_t len)
{
resolve();
if (cache_min && (len >= cache_min || any_kept())) {
pthread_mutex_lock(&lock);
drop_overlaps(addr, len, "munmap overlap");
if (len >= cache_min && store(addr, len, 1, KEPT_PROT)) { pthread_mutex_unlock(&lock); return 0; }
pthread_mutex_unlock(&lock);
}
return real_munmap(addr, len);
}
int mprotect(void *addr, size_t len, int prot)
{
resolve();
if (any_kept()) {
pthread_mutex_lock(&lock);
drop_overlaps(addr, len, "mprotect overlap");
pthread_mutex_unlock(&lock);
}
int r = real_mprotect(addr, len, prot);
if (thp && !r && (prot & PROT_WRITE) && len >= thp_min) advise(addr, len);
return r;
}
@@ -1,54 +0,0 @@
diff --git a/dlls/crypt32/chain.c b/dlls/crypt32/chain.c
--- a/dlls/crypt32/chain.c
+++ b/dlls/crypt32/chain.c
@@ -2578,6 +2578,36 @@
return quality;
}
+/* Between two chains of equal quality, Windows prefers the one whose issuer is
+ * the most recent certificate (latest NotBefore) where the chains first
+ * differ, e.g. a cross-signed root shipped with a signature (2022) over an
+ * older self-signed copy of the same root (2013). Returns TRUE if alternate
+ * should be preferred over chain.
+ */
+static BOOL CRYPT_AlternateHasNewerIssuer(const CertificateChain *chain,
+ const CertificateChain *alternate)
+{
+ DWORD i, j;
+
+ for (i = 0; i < chain->context.cChain && i < alternate->context.cChain; i++)
+ {
+ const CERT_SIMPLE_CHAIN *a = chain->context.rgpChain[i];
+ const CERT_SIMPLE_CHAIN *b = alternate->context.rgpChain[i];
+
+ for (j = 0; j < a->cElement && j < b->cElement; j++)
+ {
+ PCCERT_CONTEXT ca = a->rgpElement[j]->pCertContext;
+ PCCERT_CONTEXT cb = b->rgpElement[j]->pCertContext;
+
+ if (!CertCompareCertificate(X509_ASN_ENCODING, ca->pCertInfo,
+ cb->pCertInfo))
+ return CompareFileTime(&cb->pCertInfo->NotBefore,
+ &ca->pCertInfo->NotBefore) > 0;
+ }
+ }
+ return FALSE;
+}
+
/* Chooses the highest quality chain among chain and its "lower quality"
* alternate chains. Returns the highest quality chain, with all other
* chains as lower quality chains of it.
@@ -2598,7 +2628,12 @@
CertificateChain *alternate =
(CertificateChain*)chain->context.rgpLowerQualityChainContext[i];
- if (CRYPT_ChainQuality(alternate) > CRYPT_ChainQuality(chain))
+ DWORD alternateQuality = CRYPT_ChainQuality(alternate);
+ DWORD chainQuality = CRYPT_ChainQuality(chain);
+
+ if (alternateQuality > chainQuality ||
+ (alternateQuality == chainQuality &&
+ CRYPT_AlternateHasNewerIssuer(chain, alternate)))
{
alternate->context.cLowerQualityChainContext =
chain->context.cLowerQualityChainContext;
@@ -1,70 +0,0 @@
diff --git a/dlls/windows.devices.enumeration/main.c b/dlls/windows.devices.enumeration/main.c
--- a/dlls/windows.devices.enumeration/main.c
+++ b/dlls/windows.devices.enumeration/main.c
@@ -118,6 +118,8 @@
struct weak_reference_source weak_reference_source;
struct list added_handlers;
+ struct list updated_handlers;
+ struct list removed_handlers;
struct list enumerated_handlers;
struct list stopped_handlers;
IUnknown *query_params;
@@ -177,6 +179,8 @@
if (!ref)
{
typed_event_handlers_clear( &impl->added_handlers );
+ typed_event_handlers_clear( &impl->updated_handlers );
+ typed_event_handlers_clear( &impl->removed_handlers );
typed_event_handlers_clear( &impl->enumerated_handlers );
typed_event_handlers_clear( &impl->stopped_handlers );
IUnknown_Release( impl->query_params );
@@ -225,27 +229,31 @@
static HRESULT WINAPI device_watcher_add_Updated( IDeviceWatcher *iface, ITypedEventHandler_DeviceWatcher_DeviceInformationUpdate *handler,
EventRegistrationToken *token )
{
- FIXME( "iface %p, handler %p, token %p stub!\n", iface, handler, token );
- return S_OK;
+ struct device_watcher *impl = impl_from_IDeviceWatcher( iface );
+ TRACE( "iface %p, handler %p, token %p\n", iface, handler, token );
+ return typed_event_handlers_append( &impl->updated_handlers, (ITypedEventHandler_IInspectable_IInspectable *)handler, token );
}
static HRESULT WINAPI device_watcher_remove_Updated( IDeviceWatcher *iface, EventRegistrationToken token )
{
- FIXME( "iface %p, token %#I64x stub!\n", iface, token.value );
- return E_NOTIMPL;
+ struct device_watcher *impl = impl_from_IDeviceWatcher( iface );
+ TRACE( "iface %p, token %#I64x.\n", iface, token.value );
+ return typed_event_handlers_remove( &impl->updated_handlers, &token );
}
static HRESULT WINAPI device_watcher_add_Removed( IDeviceWatcher *iface, ITypedEventHandler_DeviceWatcher_DeviceInformationUpdate *handler,
EventRegistrationToken *token )
{
- FIXME( "iface %p, handler %p, token %p stub!\n", iface, handler, token );
- return E_NOTIMPL;
+ struct device_watcher *impl = impl_from_IDeviceWatcher( iface );
+ TRACE( "iface %p, handler %p, token %p\n", iface, handler, token );
+ return typed_event_handlers_append( &impl->removed_handlers, (ITypedEventHandler_IInspectable_IInspectable *)handler, token );
}
static HRESULT WINAPI device_watcher_remove_Removed( IDeviceWatcher *iface, EventRegistrationToken token )
{
- FIXME( "iface %p, token %#I64x stub!\n", iface, token.value );
- return E_NOTIMPL;
+ struct device_watcher *impl = impl_from_IDeviceWatcher( iface );
+ TRACE( "iface %p, token %#I64x.\n", iface, token.value );
+ return typed_event_handlers_remove( &impl->removed_handlers, &token );
}
static HRESULT WINAPI device_watcher_add_EnumerationCompleted( IDeviceWatcher *iface, ITypedEventHandler_DeviceWatcher_IInspectable *handler,
@@ -592,6 +600,8 @@
if (FAILED(hr = devquery_params_create( type, expr, prop_keys, prop_keys_len, &impl->query_params ))) goto failed;
list_init( &impl->added_handlers );
+ list_init( &impl->updated_handlers );
+ list_init( &impl->removed_handlers );
list_init( &impl->enumerated_handlers );
list_init( &impl->stopped_handlers );
@@ -1,282 +0,0 @@
diff --git a/dlls/dnsapi/dnsapi.spec b/dlls/dnsapi/dnsapi.spec
--- a/dlls/dnsapi/dnsapi.spec
+++ b/dlls/dnsapi/dnsapi.spec
@@ -104,12 +104,20 @@
@ stdcall DnsReplaceRecordSetW(ptr long ptr ptr ptr)
@ stub DnsReplaceRecordSet_W
@ stdcall DnsServiceBrowse(ptr ptr)
+@ stdcall DnsServiceBrowseCancel(ptr)
+@ stdcall DnsServiceConstructInstance(wstr wstr ptr ptr long long long long ptr ptr)
+@ stdcall DnsServiceDeRegister(ptr ptr)
+@ stdcall DnsServiceFreeInstance(ptr)
@ stub DnsServiceNotificationDeregister_A
@ stub DnsServiceNotificationDeregister_UTF8
@ stub DnsServiceNotificationDeregister_W
@ stub DnsServiceNotificationRegister_A
@ stub DnsServiceNotificationRegister_UTF8
@ stub DnsServiceNotificationRegister_W
+@ stdcall DnsServiceRegister(ptr ptr)
+@ stdcall DnsServiceRegisterCancel(ptr)
+@ stdcall DnsServiceResolve(ptr ptr)
+@ stdcall DnsServiceResolveCancel(ptr)
@ stub DnsSetMaxNumberOfAddressesToRegister
@ stub DnsStatusString
@ stub DnsStringCopyAllocateEx
diff --git a/dlls/dnsapi/main.c b/dlls/dnsapi/main.c
--- a/dlls/dnsapi/main.c
+++ b/dlls/dnsapi/main.c
@@ -243,3 +243,135 @@
FIXME( "(%p, %p) stub\n", request, cancel );
return ERROR_SUCCESS;
}
+
+/******************************************************************************
+ * DnsServiceConstructInstance [DNSAPI.@]
+ *
+ */
+DNS_SERVICE_INSTANCE * WINAPI DnsServiceConstructInstance( const WCHAR *name, const WCHAR *host,
+ IP4_ADDRESS *ip4, IP6_ADDRESS *ip6, WORD port, WORD priority, WORD weight,
+ DWORD count, const WCHAR **keys, const WCHAR **values )
+{
+ DNS_SERVICE_INSTANCE *instance;
+ DWORD i;
+
+ TRACE( "(%s, %s, %p, %p, %u, %u, %u, %lu, %p, %p)\n", debugstr_w(name), debugstr_w(host),
+ ip4, ip6, port, priority, weight, count, keys, values );
+
+ if (!(instance = calloc( 1, sizeof(*instance) ))) return NULL;
+
+ if (name) instance->pszInstanceName = wcsdup( name );
+ if (host) instance->pszHostName = wcsdup( host );
+ if (ip4 && (instance->ip4Address = malloc( sizeof(*ip4) ))) *instance->ip4Address = *ip4;
+ if (ip6 && (instance->ip6Address = malloc( sizeof(*ip6) ))) *instance->ip6Address = *ip6;
+ instance->wPort = port;
+ instance->wPriority = priority;
+ instance->wWeight = weight;
+ instance->dwPropertyCount = count;
+
+ if (count && (instance->keys = calloc( count, sizeof(*keys) )))
+ for (i = 0; i < count; i++) instance->keys[i] = wcsdup( keys[i] );
+ if (count && (instance->values = calloc( count, sizeof(*values) )))
+ for (i = 0; i < count; i++) instance->values[i] = wcsdup( values[i] );
+
+ return instance;
+}
+
+/******************************************************************************
+ * DnsServiceFreeInstance [DNSAPI.@]
+ *
+ */
+void WINAPI DnsServiceFreeInstance( DNS_SERVICE_INSTANCE *instance )
+{
+ DWORD i;
+
+ TRACE( "(%p)\n", instance );
+
+ if (!instance) return;
+
+ free( instance->pszInstanceName );
+ free( instance->pszHostName );
+ free( instance->ip4Address );
+ free( instance->ip6Address );
+ for (i = 0; i < instance->dwPropertyCount; i++)
+ {
+ if (instance->keys) free( instance->keys[i] );
+ if (instance->values) free( instance->values[i] );
+ }
+ free( instance->keys );
+ free( instance->values );
+ free( instance );
+}
+
+/******************************************************************************
+ * DnsServiceRegister [DNSAPI.@]
+ *
+ */
+DNS_STATUS WINAPI DnsServiceRegister( DNS_SERVICE_REGISTER_REQUEST *request, DNS_SERVICE_CANCEL *cancel )
+{
+ FIXME( "(%p, %p) stub\n", request, cancel );
+
+ if (!request) return ERROR_INVALID_PARAMETER;
+
+ /* Registration needs mDNS support, which is not implemented. Fail
+ * synchronously: the completion callback must only run when this returns
+ * DNS_REQUEST_PENDING, and calling it inline would re-enter the caller
+ * while it still believes the operation is outstanding. */
+ return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+/******************************************************************************
+ * DnsServiceDeRegister [DNSAPI.@]
+ *
+ */
+DNS_STATUS WINAPI DnsServiceDeRegister( DNS_SERVICE_REGISTER_REQUEST *request, DNS_SERVICE_CANCEL *cancel )
+{
+ FIXME( "(%p, %p) stub\n", request, cancel );
+
+ if (!request) return ERROR_INVALID_PARAMETER;
+
+ return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+/******************************************************************************
+ * DnsServiceRegisterCancel [DNSAPI.@]
+ *
+ */
+DNS_STATUS WINAPI DnsServiceRegisterCancel( DNS_SERVICE_CANCEL *cancel )
+{
+ FIXME( "(%p) stub\n", cancel );
+ return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+/******************************************************************************
+ * DnsServiceResolve [DNSAPI.@]
+ *
+ */
+DNS_STATUS WINAPI DnsServiceResolve( DNS_SERVICE_RESOLVE_REQUEST *request, DNS_SERVICE_CANCEL *cancel )
+{
+ FIXME( "(%p, %p) stub\n", request, cancel );
+
+ if (!request) return ERROR_INVALID_PARAMETER;
+
+ return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+/******************************************************************************
+ * DnsServiceResolveCancel [DNSAPI.@]
+ *
+ */
+DNS_STATUS WINAPI DnsServiceResolveCancel( DNS_SERVICE_CANCEL *cancel )
+{
+ FIXME( "(%p) stub\n", cancel );
+ return ERROR_CALL_NOT_IMPLEMENTED;
+}
+
+/******************************************************************************
+ * DnsServiceBrowseCancel [DNSAPI.@]
+ *
+ */
+DNS_STATUS WINAPI DnsServiceBrowseCancel( DNS_SERVICE_CANCEL *cancel )
+{
+ FIXME( "(%p) stub\n", cancel );
+ return ERROR_CALL_NOT_IMPLEMENTED;
+}
diff --git a/include/windns.h b/include/windns.h
--- a/include/windns.h
+++ b/include/windns.h
@@ -106,7 +106,8 @@
#define DNS_QUERY_APPEND_MULTILABEL 0x00800000
#define DNS_QUERY_DNSSEC_OK 0x01000000
#define DNS_QUERY_DNSSEC_CHECKING_DISABLED 0x02000000
-#define DNS_QUERY_RESERVED 0xff000000
+#define DNS_QUERY_DNSSEC_REQUIRED 0x04000000
+#define DNS_QUERY_RESERVED 0xf0000000
#define INLINE_WORD_FLIP(out, in) { WORD _in = (in); (out) = (_in << 8) | (_in >> 8); }
#define INLINE_HTONS(out, in) INLINE_WORD_FLIP(out, in)
@@ -781,6 +782,73 @@
void *reserved;
} DNS_SERVICE_CANCEL, *PDNS_SERVICE_CANCEL;
+typedef struct _DNS_SERVICE_INSTANCE
+{
+ LPWSTR pszInstanceName;
+ LPWSTR pszHostName;
+ IP4_ADDRESS *ip4Address;
+ IP6_ADDRESS *ip6Address;
+ WORD wPort;
+ WORD wPriority;
+ WORD wWeight;
+ DWORD dwPropertyCount;
+ PWSTR *keys;
+ PWSTR *values;
+ DWORD dwInterfaceIndex;
+} DNS_SERVICE_INSTANCE, *PDNS_SERVICE_INSTANCE;
+
+typedef void WINAPI DNS_SERVICE_REGISTER_COMPLETE(DWORD, void *, PDNS_SERVICE_INSTANCE);
+typedef DNS_SERVICE_REGISTER_COMPLETE *PDNS_SERVICE_REGISTER_COMPLETE;
+
+typedef struct _DNS_SERVICE_REGISTER_REQUEST
+{
+ ULONG Version;
+ ULONG InterfaceIndex;
+ PDNS_SERVICE_INSTANCE pServiceInstance;
+ PDNS_SERVICE_REGISTER_COMPLETE pRegisterCompletionCallback;
+ PVOID pQueryContext;
+ HANDLE hCredentials;
+ BOOL unicastEnabled;
+} DNS_SERVICE_REGISTER_REQUEST, *PDNS_SERVICE_REGISTER_REQUEST;
+
+typedef void WINAPI DNS_SERVICE_RESOLVE_COMPLETE(DWORD, void *, PDNS_SERVICE_INSTANCE);
+typedef DNS_SERVICE_RESOLVE_COMPLETE *PDNS_SERVICE_RESOLVE_COMPLETE;
+
+typedef struct _DNS_SERVICE_RESOLVE_REQUEST
+{
+ ULONG Version;
+ ULONG InterfaceIndex;
+ LPWSTR QueryName;
+ PDNS_SERVICE_RESOLVE_COMPLETE pResolveCompletionCallback;
+ PVOID pQueryContext;
+} DNS_SERVICE_RESOLVE_REQUEST, *PDNS_SERVICE_RESOLVE_REQUEST;
+
+typedef struct _MDNS_QUERY_HANDLE
+{
+ WCHAR nameBuf[DNS_MAX_NAME_BUFFER_LENGTH];
+ WORD wType;
+ PVOID pSubscription;
+ PVOID pWnfCallbackParams;
+ ULONG stateNameData[2];
+} MDNS_QUERY_HANDLE, *PMDNS_QUERY_HANDLE;
+
+typedef void WINAPI MDNS_QUERY_CALLBACK(PVOID,PMDNS_QUERY_HANDLE,PDNS_QUERY_RESULT);
+typedef MDNS_QUERY_CALLBACK *PMDNS_QUERY_CALLBACK;
+
+typedef struct _MDNS_QUERY_REQUEST
+{
+ ULONG Version;
+ ULONG ulRefCount;
+ PCWSTR Query;
+ WORD QueryType;
+ ULONG64 QueryOptions;
+ ULONG InterfaceIndex;
+ PMDNS_QUERY_CALLBACK pQueryCallback;
+ PVOID pQueryContext;
+ BOOL fAnswerReceived;
+ ULONG ulResendCount;
+} MDNS_QUERY_REQUEST, *PMDNS_QUERY_REQUEST;
+
DNS_STATUS WINAPI DnsAcquireContextHandle_A(DWORD,PVOID,PHANDLE);
DNS_STATUS WINAPI DnsAcquireContextHandle_W(DWORD,PVOID,PHANDLE);
#define DnsAcquireContextHandle WINELIB_NAME_AW(DnsAcquireContextHandle_)
@@ -800,6 +868,7 @@
#define DnsQuery WINELIB_NAME_AW(DnsQuery_)
DNS_STATUS WINAPI DnsQueryEx(DNS_QUERY_REQUEST*,DNS_QUERY_RESULT*,DNS_QUERY_CANCEL*);
DNS_STATUS WINAPI DnsCancelQuery(DNS_QUERY_CANCEL*);
+BOOL WINAPI DnsGetCacheDataTable(PDNS_CACHE_ENTRY*);
DNS_STATUS WINAPI DnsQueryConfig(DNS_CONFIG_TYPE,DWORD,PCWSTR,PVOID,PVOID,PDWORD);
BOOL WINAPI DnsRecordCompare(PDNS_RECORD,PDNS_RECORD);
PDNS_RECORD WINAPI DnsRecordCopyEx(PDNS_RECORD,DNS_CHARSET,DNS_CHARSET);
@@ -813,13 +882,22 @@
DNS_STATUS WINAPI DnsReplaceRecordSetUTF8(PDNS_RECORDA,DWORD,HANDLE,PVOID,PVOID);
#define DnsReplaceRecordSet WINELIB_NAME_AW(DnsReplaceRecordSet)
DNS_STATUS WINAPI DnsServiceBrowse(PDNS_SERVICE_BROWSE_REQUEST, PDNS_SERVICE_CANCEL);
+DNS_STATUS WINAPI DnsServiceBrowseCancel(PDNS_SERVICE_CANCEL);
+PDNS_SERVICE_INSTANCE WINAPI DnsServiceConstructInstance(PCWSTR,PCWSTR,PIP4_ADDRESS,PIP6_ADDRESS,WORD,WORD,WORD,DWORD,PCWSTR*,PCWSTR*);
+DNS_STATUS WINAPI DnsServiceDeRegister(PDNS_SERVICE_REGISTER_REQUEST,PDNS_SERVICE_CANCEL);
+VOID WINAPI DnsServiceFreeInstance(PDNS_SERVICE_INSTANCE);
+DNS_STATUS WINAPI DnsServiceRegister(PDNS_SERVICE_REGISTER_REQUEST,PDNS_SERVICE_CANCEL);
+DNS_STATUS WINAPI DnsServiceRegisterCancel(PDNS_SERVICE_CANCEL);
+DNS_STATUS WINAPI DnsServiceResolve(PDNS_SERVICE_RESOLVE_REQUEST,PDNS_SERVICE_CANCEL);
+DNS_STATUS WINAPI DnsServiceResolveCancel(PDNS_SERVICE_CANCEL);
+DNS_STATUS WINAPI DnsStartMulticastQuery(PMDNS_QUERY_REQUEST,PMDNS_QUERY_HANDLE);
+DNS_STATUS WINAPI DnsStopMulticastQuery(PMDNS_QUERY_HANDLE);
DNS_STATUS WINAPI DnsValidateName_A(PCSTR,DNS_NAME_FORMAT);
DNS_STATUS WINAPI DnsValidateName_W(PCWSTR, DNS_NAME_FORMAT);
DNS_STATUS WINAPI DnsValidateName_UTF8(PCSTR,DNS_NAME_FORMAT);
#define DnsValidateName WINELIB_NAME_AW(DnsValidateName_)
BOOL WINAPI DnsWriteQuestionToBuffer_W(PDNS_MESSAGE_BUFFER,PDWORD,PCWSTR,WORD,WORD,BOOL);
BOOL WINAPI DnsWriteQuestionToBuffer_UTF8(PDNS_MESSAGE_BUFFER,PDWORD,PCSTR,WORD,WORD,BOOL);
-BOOL WINAPI DnsGetCacheDataTable(PDNS_CACHE_ENTRY*);
#ifdef __cplusplus
}
@@ -1,118 +0,0 @@
diff --git a/dlls/sechost/trace.c b/dlls/sechost/trace.c
--- a/dlls/sechost/trace.c
+++ b/dlls/sechost/trace.c
@@ -28,6 +28,7 @@
#include "evntrace.h"
#include "wine/debug.h"
+#include "wine/exception.h"
WINE_DEFAULT_DEBUG_CHANNEL(eventlog);
@@ -116,14 +117,63 @@
return ERROR_SUCCESS;
}
+/* A real-time consumer of a session. No ETW providers exist under Wine, so the
+ * consumer never receives events: ProcessTrace() waits until CloseTrace(). */
+#define REALTIME_CONSUMER_MAGIC 0x52544345 /* "ECTR" */
+#ifndef PROCESS_TRACE_MODE_REAL_TIME
+#define PROCESS_TRACE_MODE_REAL_TIME 0x00000100 /* shares LogFileMode in Wine's header */
+#endif
+
+struct realtime_consumer
+{
+ DWORD magic;
+ HANDLE closed;
+};
+
+static struct realtime_consumer *get_realtime_consumer( TRACEHANDLE handle )
+{
+ struct realtime_consumer *consumer = (struct realtime_consumer *)(ULONG_PTR)handle;
+
+ if (!handle || handle == INVALID_PROCESSTRACE_HANDLE) return NULL;
+ __TRY
+ {
+ if (consumer->magic != REALTIME_CONSUMER_MAGIC) consumer = NULL;
+ }
+ __EXCEPT_PAGE_FAULT
+ {
+ consumer = NULL;
+ }
+ __ENDTRY
+ return consumer;
+}
+
/******************************************************************************
* OpenTraceW (sechost.@)
*/
TRACEHANDLE WINAPI OpenTraceW( EVENT_TRACE_LOGFILEW *logfile )
{
static int once;
+ struct realtime_consumer *consumer;
- if (!once++) FIXME("%p: stub\n", logfile);
+ /* a session name without a log file can only be consumed in real time */
+ if (logfile && logfile->LoggerName &&
+ ((logfile->LogFileMode & PROCESS_TRACE_MODE_REAL_TIME) || !logfile->LogFileName))
+ {
+ FIXME("%p (%s): real-time consumer without events\n", logfile, debugstr_w(logfile->LoggerName));
+ if (!(consumer = HeapAlloc( GetProcessHeap(), 0, sizeof(*consumer) )))
+ {
+ SetLastError(ERROR_NOT_ENOUGH_MEMORY);
+ return INVALID_PROCESSTRACE_HANDLE;
+ }
+ consumer->magic = REALTIME_CONSUMER_MAGIC;
+ consumer->closed = CreateEventW( NULL, TRUE, FALSE, NULL );
+ return (TRACEHANDLE)(ULONG_PTR)consumer;
+ }
+
+ if (!once++) FIXME("%p: stub (logfile %s, logger %s, mode %#lx)\n", logfile,
+ logfile ? debugstr_w(logfile->LogFileName) : "-",
+ logfile ? debugstr_w(logfile->LoggerName) : "-",
+ logfile ? logfile->LogFileMode : 0);
SetLastError(ERROR_ACCESS_DENIED);
return INVALID_PROCESSTRACE_HANDLE;
}
@@ -133,6 +183,25 @@
*/
ULONG WINAPI ProcessTrace( TRACEHANDLE *handles, ULONG count, FILETIME *start_time, FILETIME *end_time )
{
+ HANDLE events[MAXIMUM_WAIT_OBJECTS];
+ ULONG i;
+
+ if (handles && count && count <= MAXIMUM_WAIT_OBJECTS)
+ {
+ for (i = 0; i < count; i++)
+ {
+ struct realtime_consumer *consumer = get_realtime_consumer( handles[i] );
+ if (!consumer) break;
+ events[i] = consumer->closed;
+ }
+ if (i == count)
+ {
+ TRACE("%p %lu: waiting for CloseTrace\n", handles, count);
+ WaitForMultipleObjects( count, events, TRUE, INFINITE );
+ return ERROR_SUCCESS;
+ }
+ }
+
FIXME("%p %lu %p %p: stub\n", handles, count, start_time, end_time);
return ERROR_CALL_NOT_IMPLEMENTED;
}
@@ -142,6 +211,15 @@
*/
ULONG WINAPI CloseTrace( TRACEHANDLE handle )
{
+ struct realtime_consumer *consumer = get_realtime_consumer( handle );
+
+ if (consumer)
+ {
+ /* the handle stays allocated: ProcessTrace() may still be waiting on it */
+ SetEvent( consumer->closed );
+ return ERROR_SUCCESS;
+ }
+
FIXME("%s: stub\n", wine_dbgstr_longlong(handle));
return ERROR_INVALID_HANDLE;
}
-39
View File
@@ -1,39 +0,0 @@
/* Deliver a protocol callback to the RUNNING Meta client; never start a second Client.exe.
* UTF-8 stdin is preferred (no credentials in process argv). argv[1] is useful for non-secret device probes.
* Uses a NUL-terminated UTF-8 link. Device verification of the Oculus pipe's framing is still required.
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char link[65537];
size_t len;
HANDLE pipe = INVALID_HANDLE_VALUE;
DWORD written;
if (argc == 2) {
len = strlen(argv[1]);
if (len >= sizeof(link)) return 2;
memcpy(link, argv[1], len);
} else if (argc == 1) {
len = fread(link, 1, sizeof(link), stdin);
if (ferror(stdin) || len >= sizeof(link)) return 2;
} else return 2;
if (len < 24 || strncmp(link, "oculus://link/frl_login?", 24) || memchr(link, 0, len)) return 2;
link[len] = 0;
for (int i = 0; i < 100; ++i) {
pipe = CreateFileW(L"\\\\.\\pipe\\oculus", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (pipe != INVALID_HANDLE_VALUE) break;
DWORD err = GetLastError();
if (err != ERROR_PIPE_BUSY && err != ERROR_FILE_NOT_FOUND) return 3;
if (err == ERROR_PIPE_BUSY) WaitNamedPipeW(L"\\\\.\\pipe\\oculus", 200);
else Sleep(200);
}
if (pipe == INVALID_HANDLE_VALUE) return 3;
BOOL ok = WriteFile(pipe, link, (DWORD)len + 1, &written, NULL);
CloseHandle(pipe);
SecureZeroMemory(link, sizeof(link));
return ok && written == len + 1 ? 0 : 4;
}
-26
View File
@@ -1,26 +0,0 @@
#!/bin/bash
# Reproduce the exact Wine source of a GE-Proton release (Wine submodule + wine-staging + GE's own patches): the WINE
# section of GE's patches/protonprep-valve-staging.sh, without the DXVK/vkd3d/protonfixes steps.
# usage: prep_ge_wine.sh <work dir> [tag=GE-Proton11-7] → <work dir>/src/wine
# Needs git, patch, python3, autoconf/autoreconf (the WINE section ends with autoreconf + tools/make_requests).
set -e
W=$1; TAG=${2:-GE-Proton11-7}
[ -n "$W" ] || { echo "usage: $0 <work dir> [tag]"; exit 2; }
mkdir -p "$W" && cd "$W"
[ -d src ] || git clone -q --depth 1 --branch "$TAG" https://github.com/GloriousEggroll/proton-ge-custom src
cd src
git submodule update --init --depth 1 wine wine-staging
P=patches/protonprep-valve-staging.sh
start=$(grep -n "^### (2) WINE PATCHING ###" $P | cut -d: -f1)
end=$(grep -n "^### END WINE PATCHING ###" $P | cut -d: -f1)
fn_end=$(grep -n "^### (1) PREP SECTION ###" $P | cut -d: -f1)
[ -n "$start" ] && [ -n "$end" ] && [ -n "$fn_end" ] || { echo "unexpected layout of $P"; exit 1; }
# the WINE section reverts commits from the Wine history: fetch them into the shallow clone first
for c in $(sed -n "${start},${end}p" $P | grep -oE "git revert [^#]*" | grep -oE "[0-9a-f]{40}"); do
git -C wine fetch -q --depth 2 origin "$c"
done
{ sed -n "1,$((fn_end - 1))p" $P; sed -n "${start},${end}p" $P; } > ../wine_only.sh
bash ../wine_only.sh > ../prep.log 2>&1
grep -n "SERVER_PROTOCOL_VERSION" wine/include/wine/server_protocol.h
if find wine -name "*.rej" | grep -q .; then echo "rejected hunks, see ../prep.log"; exit 1; fi
echo "patched Wine tree: $W/src/wine"
-79
View File
@@ -1,79 +0,0 @@
/* windows.devices.wifi.dll stand-in for Wine: activation factory of Windows.Devices.WiFi.WiFiAdapter with the
* IWiFiAdapterStatics methods. Wine has no Wi-Fi WinRT class; Meta's runtime (OculusAppFramework, Air Link "Ari"
* dongle code) calls WiFiAdapter.GetDeviceSelector() after login, enumerates devices with it and only calls
* FromIdAsync for devices found. Without the class, C++/WinRT throws and the runtime fail-fasts (c0000409).
* GetDeviceSelector returns a selector that matches no device; the async methods report E_NOTIMPL (never reached
* when nothing is found). Unknown interface requests are logged to stderr.
*/
#define COBJMACROS
#include <windows.h>
#include <winstring.h>
#include <stdio.h>
typedef struct IInspectableVtbl_ { void *s[6]; } dummy_t;
static const GUID IID_IUnknown_ = {0x00000000,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
static const GUID IID_IInspectable_ = {0xaf86e2e0,0xb12d,0x4c6a,{0x9c,0x5a,0xd7,0xaa,0x65,0x10,0x1e,0x90}};
static const GUID IID_IAgileObject_ = {0x94ea2b94,0xe9cc,0x49e0,{0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90}};
static const GUID IID_IActivationFactory_ = {0x00000035,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
/* Windows.Devices.WiFi.IWiFiAdapterStatics */
static const GUID IID_IWiFiAdapterStatics = {0xda25fddd,0xd24c,0x43e3,{0xaa,0xbd,0xc4,0x65,0x9f,0x73,0x0f,0x99}};
typedef struct statics { const void **vtbl; } statics;
static HRESULT WINAPI f_QueryInterface(statics *This, REFIID iid, void **out)
{
if (IsEqualGUID(iid, &IID_IUnknown_) || IsEqualGUID(iid, &IID_IInspectable_) || IsEqualGUID(iid, &IID_IAgileObject_)
|| IsEqualGUID(iid, &IID_IActivationFactory_) || IsEqualGUID(iid, &IID_IWiFiAdapterStatics))
{
*out = This;
return S_OK;
}
fprintf(stderr, "wifi_stub: unknown interface {%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n", iid->Data1,
iid->Data2, iid->Data3, iid->Data4[0], iid->Data4[1], iid->Data4[2], iid->Data4[3], iid->Data4[4],
iid->Data4[5], iid->Data4[6], iid->Data4[7]);
*out = NULL;
return E_NOINTERFACE;
}
static ULONG WINAPI f_AddRef(statics *This) { return 2; }
static ULONG WINAPI f_Release(statics *This) { return 1; }
static HRESULT WINAPI f_GetIids(statics *This, ULONG *count, IID **iids)
{
IID *p = CoTaskMemAlloc(sizeof(IID));
if (!p) return E_OUTOFMEMORY;
*p = IID_IWiFiAdapterStatics; *count = 1; *iids = p;
return S_OK;
}
static HRESULT WINAPI f_GetRuntimeClassName(statics *This, HSTRING *name)
{
static const WCHAR n[] = L"Windows.Devices.WiFi.WiFiAdapter";
return WindowsCreateString(n, ARRAYSIZE(n) - 1, name);
}
static HRESULT WINAPI f_GetTrustLevel(statics *This, int *level) { *level = 0; return S_OK; }
/* slot 6: IWiFiAdapterStatics::FindAllAdaptersAsync (and IActivationFactory::ActivateInstance: not activatable) */
static HRESULT WINAPI f_FindAllAdaptersAsync(statics *This, void **op) { if (op) *op = NULL; return E_NOTIMPL; }
static HRESULT WINAPI f_GetDeviceSelector(statics *This, HSTRING *value)
{
/* an interface class no device has: device enumeration with it finds nothing */
static const WCHAR sel[] = L"System.Devices.InterfaceClassGuid:=\"{f0e2c0a5-7b3e-4f61-9b47-3d1c0f0e2a11}\" AND "
L"System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
fprintf(stderr, "wifi_stub: GetDeviceSelector\n");
return WindowsCreateString(sel, ARRAYSIZE(sel) - 1, value);
}
static HRESULT WINAPI f_FromIdAsync(statics *This, HSTRING id, void **op) { if (op) *op = NULL; return E_NOTIMPL; }
static HRESULT WINAPI f_RequestAccessAsync(statics *This, void **op) { if (op) *op = NULL; return E_NOTIMPL; }
static const void *vtbl[] = { f_QueryInterface, f_AddRef, f_Release, f_GetIids, f_GetRuntimeClassName,
f_GetTrustLevel, f_FindAllAdaptersAsync, f_GetDeviceSelector, f_FromIdAsync,
f_RequestAccessAsync };
static statics factory = { vtbl };
HRESULT WINAPI DllGetActivationFactory(HSTRING classid, void **out)
{
const WCHAR *s = WindowsGetStringRawBuffer(classid, NULL);
fprintf(stderr, "wifi_stub: DllGetActivationFactory %ls\n", s ? s : L"(null)");
if (!s || wcscmp(s, L"Windows.Devices.WiFi.WiFiAdapter")) { *out = NULL; return CLASS_E_CLASSNOTAVAILABLE; }
*out = &factory;
return S_OK;
}
HRESULT WINAPI DllCanUnloadNow(void) { return S_FALSE; }
-4
View File
@@ -1,4 +0,0 @@
LIBRARY windows.devices.wifi.dll
EXPORTS
DllGetActivationFactory
DllCanUnloadNow PRIVATE
+477 -38
View File
@@ -1,69 +1,508 @@
#!/usr/bin/env python3
"""Score the patch heuristics against the verified catalog: for every game dump that has a catalog recipe, suggest a
recipe with the catalog switched off and compare the recipe-relevant choices.
"""Evaluate static patch suggestions against catalog-only ground truth (no catalog-assisted suggestions).
python scripts/eval_heuristics.py "<folder with game dumps>" [--verbose]
eval_heuristics.py <dumps folder> [--verbose]
eval_heuristics.py --snapshot analyses.json --split all --json baseline.json
eval_heuristics.py --snapshot analyses.json --fit-report --out fit-report.md
Snapshots can be in progress: each read copies to a temporary file and retries incomplete JSON. The split is
stratified by analysis engine and stable for a fixed set of packages. Converted inputs are included and labelled.
Patch scores are micro-averaged across games, excluding enabled automatic defaults. Expected defaults are detected
per analysis before applying explicit catalog removals; inapplicable defaults create no removal decisions. A wrong
adapter value is both an FP and an FN. Removal decisions and alternate-build patches have their own identities
("remove:<id>", "alt:<id>").
Unsupported catalog entries and runtime-only choices are reported separately from the headline.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
import shutil
import subprocess
import sys
import tempfile
import time
from collections import Counter, defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from frameport.analysis.detect import analyze # noqa: E402
from frameport.core.library import analysis_from_dict # noqa: E402
from frameport.core.models import Recipe # noqa: E402
from frameport.patches import base # noqa: E402
from frameport.recommend import catalog, engine # noqa: E402
from frameport.sources import quest_dump # noqa: E402
RUNTIME_ONLY = [
"use_alt", "adapter.vk_shader_fix", "adapter.focus_hold", "adapter.focus_hold_ms", "adapter.sync_guard",
"adapter.scale", "adapter.layer_debug", "adapter.refresh_rate", "adapter.pose_consistency",
"lepton_env", "config_sync",
]
REPO = Path(__file__).resolve().parents[1]
DEVICE_FIELDS = {"device.files", "device.lepton_env", "device.config_sync", "device.foveation"}
def signature(recipe) -> dict:
"""The parts of a recipe that differ between games (defaults/automatic fixes are excluded)."""
def expected_defaults(analysis) -> set[str]:
"""Defaults recommended by their own detection, before recipe normalization/removals.
As in suggest's initial pass, default_on patches bypass the opt-in applies gate; their own detect() decides.
This masks e.g. LTW defaults in games without LTW, without importing any heuristic opt-in/adapter choices.
"""
return {p.id for p in base.all_patches() if p.default_on and base.for_game(p, analysis)
and (s := p.detect(analysis)) and s.recommended}
def signature(recipe: Recipe, defaults: set[str] | None = None) -> dict:
"""Recipe decisions, excluding enabled defaults but retaining explicit removal of defaults."""
pats = recipe.patches
return {
"overport": sorted(p for p in pats if base.get(p).category == "overport" and not base.get(p).default_on),
"overport_removed": sorted(p for p in (x.id for x in base.all_patches()
if x.category == "overport" and x.default_on)
if p not in pats),
"frame": sorted(p for p in pats if base.get(p).category == "frame" and not base.get(p).default_on),
rift = recipe.package.startswith("rift.")
patches = [p for p in base.all_patches() if (p.category == "pcvr") == rift]
out = {}
for category in ("overport", "frame", "pcvr"):
out[category] = sorted(p.id for p in patches if p.category == category and not p.default_on and p.id in pats)
out[category + "_removed"] = sorted(p.id for p in patches
if p.category == category and p.default_on and p.id not in pats
and (defaults is None or p.id in defaults))
out.update({
"adapter": {p.split(".", 1)[1]: v.get("value") for p, v in sorted(pats.items()) if p.startswith("adapter.")},
"device": sorted(p for p in pats if p.startswith("device.") and p not in DEVICE_FIELDS
and not base.get(p).default_on),
"device_files": sorted((pats.get("device.files") or {}).get("files", {})),
"foveation": dict(pats.get("device.foveation") or {}),
"lepton_env": dict((pats.get("device.lepton_env") or {}).get("env", {})),
"config_sync": dict((pats.get("device.config_sync") or {}).get("files", {})),
"alt": sorted(recipe.alt_patches),
"use_alt": recipe.use_alt,
"status_unsupported": recipe.status == "unsupported",
}
})
return out
def catalog_recipe(entry: catalog.CatalogEntry, defaults: set[str] | None = None, analysis=None) -> Recipe:
"""Materialize catalog choices plus expected defaults; never import heuristic opt-in choices. With the game's
analysis, the engine's structural transforms apply as in suggest(): a 32-bit game goes through the bridge (its
entry relies on that instead of listing what the bridge replaces), a 2D app keeps only its non-VR patches."""
r = Recipe(entry.package, status=entry.status, as_is=entry.as_is,
alt_patches=list(entry.alt_overport), use_alt=entry.use_alt)
rift = entry.kind == "rift" or entry.package.startswith("rift.")
r.patches = {p.id: {} for p in base.all_patches() if p.default_on and (p.category == "pcvr") == rift
and (defaults is None or p.id in defaults)}
for pid in (*entry.overport_extra, *entry.frame, *entry.device, *entry.pcvr):
r.patches[pid] = {}
for pid in (*entry.overport_remove, *entry.frame_remove, *entry.pcvr_remove):
r.patches.pop(pid, None)
for key, value in entry.adapter.items():
r.patches[f"adapter.{key}"] = {"value": value}
for pid, param, values in (("device.files", "files", entry.device_files),
("device.lepton_env", "env", entry.lepton_env),
("device.config_sync", "files", entry.config_sync)):
if values:
r.patches[pid] = {param: copy.deepcopy(values)}
if entry.foveation:
r.patches["device.foveation"] = {"mode": entry.foveation}
if entry.foveation_radius:
r.patches["device.foveation"]["radius"] = entry.foveation_radius
if entry.foveation_test:
r.patches["device.foveation"]["test"] = True
if analysis is not None:
if analysis.only_32bit and "frame.a32_bridge" not in entry.frame_remove:
r.patches.setdefault("frame.a32_bridge", {})
engine.a32_recipe(analysis, r, newly=False)
elif analysis.vr_kind == "none":
needed = {pid for pid in r.patches if not base.get(pid).needs_vr and pid != "frame.launcher"}
needed |= {"frame.launcher"} if analysis.has_info_category else set()
r.patches = {pid: v for pid, v in r.patches.items() if pid in needed}
r.alt_patches = []
return r
def catalog_signature(entry: catalog.CatalogEntry, defaults: set[str] | None = None, analysis=None) -> dict:
return signature(catalog_recipe(entry, defaults, analysis), defaults)
def engine_group(name: str) -> str:
return name if name in ("Unity", "Unreal") else "Other"
def split_packages(engines: dict[str, str]) -> dict[str, str]:
"""package -> dev/holdout; nearest 20% per engine (half rounded up), lowest sha256 first.
Only pass the intersection of catalog and analyses. This is stable under input reordering; adding packages can
change membership at a stratum's cutoff. Tiny strata may have no holdout. Unsupported entries participate too.
"""
groups = defaultdict(list)
for pkg, name in engines.items():
groups[engine_group(name)].append(pkg)
result = {}
for packages in groups.values():
ordered = sorted(packages, key=lambda p: (hashlib.sha256(p.encode()).digest(), p))
n = (len(ordered) + 2) // 5
result.update((p, "holdout" if i < n else "dev") for i, p in enumerate(ordered))
return dict(sorted(result.items()))
def _parts(sig: dict) -> tuple[dict, dict]:
headline, runtime = {}, {}
for key, value in sig.items():
if key == "adapter":
headline[key] = {k: v for k, v in value.items() if f"adapter.{k}" not in RUNTIME_ONLY}
runtime[key] = {k: v for k, v in value.items() if f"adapter.{k}" in RUNTIME_ONLY}
else:
(runtime if key in RUNTIME_ONLY else headline)[key] = value
return headline, runtime
def _decisions(sig: dict) -> dict:
"""Patch/action identities -> values. Status is a field metric, not a patch."""
out = {}
for field, value in sig.items():
if field == "status_unsupported":
continue
if field in ("adapter", "lepton_env", "config_sync"):
prefix = "adapter" if field == "adapter" else f"device.{field}"
out.update((f"{prefix}.{k}", v) for k, v in value.items())
elif field == "foveation":
if value:
out["device.foveation"] = value
elif field == "use_alt":
if value:
out["use_alt"] = value
else:
prefix = ("remove:" if field.endswith("_removed") else "alt:" if field == "alt"
else "device.files:" if field == "device_files" else "")
out.update((prefix + p, True) for p in value)
return out
def _rates(tp: int, fp: int, fn: int) -> dict:
# No positive decisions yields 0, rather than inflating scores for empty recipes/strata.
return {"tp": tp, "fp": fp, "fn": fn, "precision": tp / (tp + fp) if tp + fp else 0.0,
"recall": tp / (tp + fn) if tp + fn else 0.0,
"f1": 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0}
def score_signatures(want: dict, got: dict, gaps: frozenset | set = frozenset()) -> dict:
"""Compare one pair of signatures; value mismatches count as both missing and extra. `gaps` = decisions the
catalog entry couldn't have made (the patch didn't exist when it was verified): left out of both sides."""
result = {}
for scope, w, g in zip(("headline", "runtime"), _parts(want), _parts(got), strict=True):
wanted, actual = _decisions(w), _decisions(g)
gap = {k: actual.pop(k) for k in list(actual) if k in gaps and k not in wanted}
missing = {k: v for k, v in wanted.items() if k not in actual or actual[k] != v}
extra = {k: v for k, v in actual.items() if k not in wanted or wanted[k] != v}
per_patch = {k: _rates(int(k in wanted and k in actual and wanted[k] == actual[k]),
int(k in extra), int(k in missing)) for k in sorted(wanted.keys() | actual.keys())}
fields = {k: w.get(k) == g.get(k) for k in sorted(w.keys() | g.keys())}
exact = all(fields.values()) if not gap else not missing and not extra
result[scope] = {"exact": exact, "fields": fields, "missing": missing, "extra": extra,
"per_patch": per_patch, "gap": gap}
return result
def _aggregate(rows: list[dict], scope: str, score_key: str = "score") -> dict:
fields = defaultdict(lambda: {"matched": 0, "total": 0})
counts = defaultdict(Counter)
gaps = Counter()
for row in rows:
s = row[score_key][scope]
gaps.update(s.get("gap") or {})
for key, match in s["fields"].items():
fields[key]["matched"] += int(match)
fields[key]["total"] += 1
for key, stats in s["per_patch"].items():
counts[key].update({k: stats[k] for k in ("tp", "fp", "fn")})
per_patch = {k: _rates(**v) for k, v in sorted(counts.items())}
total = Counter()
for stats in counts.values():
total.update(stats)
exact = sum(row[score_key][scope]["exact"] for row in rows)
return {"games": len(rows), "exact": exact, "exact_ratio": exact / len(rows) if rows else 0.0,
"fields": dict(sorted(fields.items())), "per_patch": per_patch, "gaps": dict(sorted(gaps.items())),
"patches": _rates(*(total[k] for k in ("tp", "fp", "fn")))}
def score_records(records: list[dict]) -> dict:
"""Score {package, engine, status, converted, want, got, ...} records; no filesystem needed."""
rows = [{**r, "score": score_signatures(r["want"], r["got"]),
"score_dated": score_signatures(r["want"], r["got"], set(r.get("gaps") or ()))}
for r in sorted(records, key=lambda r: r["package"])]
def metrics(group):
supported = [r for r in group if r["status"] != "unsupported"]
unsupported = [r for r in group if r["status"] == "unsupported"]
return {"total_games": len(group), "converted_games": sum(bool(r.get("converted")) for r in group),
"excluded_unsupported": len(unsupported),
"headline": _aggregate(supported, "headline"), "runtime": _aggregate(supported, "runtime"),
"headline_dated": _aggregate(supported, "headline", "score_dated"),
"unsupported": {scope: _aggregate(unsupported, scope) for scope in ("headline", "runtime")}}
return {**metrics(rows), "by_engine": {name: metrics([r for r in rows if engine_group(r["engine"]) == name])
for name in ("Unity", "Unreal", "Other")}, "games": rows}
def read_snapshot(path: Path, attempts: int = 8) -> dict:
"""Copy before parsing, even on retries; never write to the source or read APK/data paths in it."""
with tempfile.TemporaryDirectory(prefix="frameport-eval-") as tmp:
dest = Path(tmp) / "snapshot.json"
for attempt in range(attempts):
shutil.copyfile(path, dest)
try:
return json.loads(dest.read_text(encoding="utf-8"))
except json.JSONDecodeError:
if attempt == attempts - 1:
raise
time.sleep(0.25 * (attempt + 1))
raise AssertionError("unreachable")
def read_dumps(path: Path) -> dict:
records = {}
for g in quest_dump.scan(path):
a = analyze(g.apk, data_bytes=g.data_bytes())
row = {"analysis": a.to_dict(), "converted": a.is_overport_output, "name": g.name}
if a.package not in records or records[a.package]["converted"] and not row["converted"]:
records[a.package] = row
return records
def gap_decisions(entry, intro_dates: dict | None) -> set[str]:
"""Decision keys for patches introduced after the entry was verified: the catalog can't be wrong about them."""
verified = str((entry.verified or {}).get("date") or "")
if not intro_dates or not verified:
return set()
return {(f"alt:{pid}" if pid.startswith("patch_remove_unreal") else pid)
for pid, date in intro_dates.items() if date and date > verified}
def inherited_decisions() -> set[str]:
"""Heuristic picks a catalog recipe keeps even when the entry doesn't name them (engine.suggest: adapter
settings and device patches other than catalog.TOGGLED_DEVICE): the verified build had them, so an "extra" one
isn't a detection error. A catalog value that differs still counts (the key is in both sides then)."""
return {p.id for p in base.all_patches()
if p.category == "adapter" or (p.category == "device" and p.id not in catalog.TOGGLED_DEVICE)}
def evaluate(snapshot: dict, entries: dict, split: str = "dev", intro_dates: dict | None = None) -> dict:
analyses = {pkg: analysis_from_dict(v["analysis"]) for pkg, v in snapshot.items() if pkg in entries}
assignments = split_packages({pkg: a.engine for pkg, a in analyses.items()})
records = []
for pkg, a in sorted(analyses.items()):
if split != "all" and assignments[pkg] != split:
continue
entry = entries[pkg]
defaults = expected_defaults(a)
records.append({"package": pkg, "title": entry.title, "engine": a.engine, "status": entry.status,
"converted": bool(snapshot[pkg].get("converted", a.is_overport_output)),
"analysis_version": snapshot[pkg].get("analysis_version"), "split": assignments[pkg],
"want": catalog_signature(entry, defaults, a),
"got": signature(engine.suggest(a, use_catalog=False), defaults),
"gaps": sorted(gap_decisions(entry, intro_dates) | inherited_decisions())})
return {"schema_version": 1, "split": split, "runtime_only": RUNTIME_ONLY, "snapshot_packages": len(snapshot),
"default_policy": "per-analysis default detection, then explicit catalog removals",
"catalog_packages": len(entries), "matched_packages": len(analyses),
"split_assignments": assignments, **score_records(records)}
def fit_candidates(analysis, entry: catalog.CatalogEntry) -> list[dict]:
"""Use suggest's final heuristic pass, including platform filtering, non-VR and a32 normalization.
Requiring a recommended detect() as well excludes dependencies and synthetic recipe additions. No engine
refactor is needed: suggest() remains untouched, and catalog data is used only for the candidate exclusion and
the hypothetical warning recipe.
"""
suggested = engine.suggest(analysis, use_catalog=False)
chosen = catalog_recipe(entry, expected_defaults(analysis), analysis)
listed = set(chosen.patches) | set(entry.alt_overport)
removed = set(entry.overport_remove) | set(entry.frame_remove) | set(entry.pcvr_remove)
result = []
for pid, params in sorted(suggested.patches.items()):
p = base.get(pid)
if (p.default_on or pid in listed or pid in removed or not base.for_game(p, analysis)
or not p.applies(analysis)):
continue
s = p.detect(analysis)
if not s or not s.recommended:
continue
trial = copy.deepcopy(chosen)
trial.patches[pid] = dict(params)
result.append({"patch": pid, "category": p.category, "experimental": p.experimental,
"strict": bool(getattr(p, "strict", False)), "reason": s.reason,
"warnings": engine.warnings(trial, analysis)})
return result
def patch_intro_dates(cache_path: Path) -> dict:
"""One local git pickaxe per uncached patch (including missing-history results); never use the network."""
try:
cached = json.loads(cache_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
cached = {}
changed = False
for p in base.all_patches():
if p.id in cached:
continue
needle = p.id.split(".", 1)[1] if p.category == "adapter" else p.id
paths = ["src/frameport/patches/settings.py"] if p.category == "adapter" else ["src/frameport"]
log = subprocess.run(["git", "log", f'-S"{needle}"', "--reverse", "--format=%ad", "--date=short", "--",
*paths], cwd=REPO, text=True, capture_output=True, check=True)
dates = log.stdout.splitlines()
cached[p.id] = dates[0] if dates else None
changed = True
if changed:
cache_path.write_text(json.dumps(cached, indent=2, sort_keys=True) + "\n", encoding="utf-8")
return cached
def entry_date(entry) -> str:
"""When the recipe was verified; `updated` only when there is no verified date (it also moves for unrelated
edits, e.g. a note, so it says nothing about which patches the verifier could pick)."""
return str(entry.verified.get("date") or "") or str(entry.updated or "")
def fit_report(snapshot: dict, entries: dict, intro_dates: dict) -> dict:
games, metadata = [], []
totals = Counter()
for pkg, entry in sorted(entries.items()):
common = {"package": pkg, "title": entry.title, "engine": entry.engine, "xr": entry.xr,
"status": entry.status, "verified_date": str(entry.verified.get("date") or ""),
"updated": str(entry.updated or ""), "entry_date": entry_date(entry)}
if pkg not in snapshot:
metadata.append(common)
continue
candidates = fit_candidates(analysis_from_dict(snapshot[pkg]["analysis"]), entry)
for c in candidates:
intro = intro_dates.get(c["patch"])
c.update(intro_date=intro,
newer_patch=bool(intro and common["entry_date"] and intro > common["entry_date"]))
totals[c["patch"]] += 1
games.append({**common, "converted": bool(snapshot[pkg].get("converted")), "candidates": candidates})
return {"games": games, "metadata_only": metadata, "totals_by_patch": dict(sorted(totals.items())),
"candidate_count": sum(totals.values()), "games_with_candidates": sum(bool(g["candidates"]) for g in games)}
def _md(value) -> str:
return str(value if value is not None else "unknown").replace("|", "\\|").replace("\n", " ")
def render_fit_report(report: dict) -> str:
lines = ["# New patch fit", "", f"{len(report['games'])} catalog games with analyses; "
f"{report['games_with_candidates']} with candidates; {report['candidate_count']} candidate additions. "
f"{len(report['metadata_only'])} metadata-only entries.", "",
"Candidates are opt-in recommended patches absent from the entry, after the heuristic engine's platform "
"and a32 rules. A listed adapter key is excluded even if its value differs. Warnings are for the full "
"catalog recipe plus that one patch; they can include pre-existing conflicts. Unknown history/date "
"does not imply a newer patch. Default-on patches are not candidates. All splits and statuses included.",
"", "## Totals by patch", "", "| Patch | Games |", "| --- | ---: |"]
lines.extend(f"| {pid} | {n} |" for pid, n in
sorted(report["totals_by_patch"].items(), key=lambda kv: (-kv[1], kv[0])))
for game in report["games"]:
lines += ["", f"## {_md(game['title'])} (`{game['package']}`)", "",
f"{game['engine']} / {game['xr']}; status: {game['status']}; "
f"entry date: {game['entry_date'] or 'unknown'}; converted: {game['converted']}.", ""]
if not game["candidates"]:
lines += ["No candidates."]
continue
lines += ["| Patch | Category | Experimental | Strict | Reason | Introduced | Newer patch | Warnings |",
"| --- | --- | --- | --- | --- | --- | --- | --- |"]
for c in game["candidates"]:
cells = [c["patch"], c["category"], c["experimental"], c["strict"], c["reason"], c["intro_date"],
c["newer_patch"], "; ".join(c["warnings"]) or "none"]
lines.append("| " + " | ".join(_md(v) for v in cells) + " |")
lines += ["", "## Catalog entries without analyses (metadata only)", "",
"| Package | Title | Engine | XR | Status | Verified | Updated | Entry date |",
"| --- | --- | --- | --- | --- | --- | --- | --- |"]
for g in report["metadata_only"]:
lines.append("| " + " | ".join(_md(g[k]) for k in
("package", "title", "engine", "xr", "status", "verified_date", "updated", "entry_date")) + " |")
return "\n".join(lines) + "\n"
def print_metrics(report: dict, verbose: bool = False) -> None:
print(f"Split: {report['split']}; catalog/analysis intersection: {report['matched_packages']}; "
f"converted: {report['converted_games']}; unsupported excluded: {report['excluded_unsupported']}")
print(f"{'Engine':10} {'Games':>5} {'Exact':>9} {'Fields':>11} {'Prec':>7} {'Recall':>7} {'F1':>7} {'Runtime':>9}")
for name, metrics in [("All", report), *report["by_engine"].items()]:
h, r = metrics["headline"], metrics["runtime"]
fields = h["fields"].values()
f = f"{sum(x['matched'] for x in fields)}/{sum(x['total'] for x in h['fields'].values())}"
p = h["patches"]
print(f"{name:10} {h['games']:5} {h['exact']:4}/{h['games']:<4} {f:>11} "
f"{p['precision']:7.1%} {p['recall']:7.1%} {p['f1']:7.1%} {r['exact']:4}/{r['games']:<4}")
print("\nDated (extras the entry couldn't have listed - patch newer than its verified date - or that catalog "
"recipes inherit anyway - adapter/device picks - are not errors):")
for name, metrics in [("All", report), *report["by_engine"].items()]:
d = metrics["headline_dated"]
p = d["patches"]
print(f"{name:10} {d['games']:5} {d['exact']:4}/{d['games']:<4} {'':>11} "
f"{p['precision']:7.1%} {p['recall']:7.1%} {p['f1']:7.1%}")
gaps = report["headline_dated"]["gaps"]
if gaps:
print("Catalog gaps by patch: " + ", ".join(f"{k}={v}" for k, v in sorted(gaps.items(), key=lambda kv: -kv[1])))
for name, metrics in [("All", report), *report["by_engine"].items()]:
print(f"\n{name}: field matches (headline / runtime)")
for scope in ("headline", "runtime"):
matches = metrics[scope]["fields"].items()
print(scope + ": " + ", ".join(f"{k}={v['matched']}/{v['total']}" for k, v in matches))
print(f"{'Scope / patch':55} {'TP':>5} {'FP':>5} {'FN':>5} {'Prec':>7} {'Recall':>7} {'F1':>7}")
for scope in ("headline", "runtime"):
for pid, p in metrics[scope]["per_patch"].items():
print(f"{scope + ' / ' + pid:55} {p['tp']:5} {p['fp']:5} {p['fn']:5} "
f"{p['precision']:7.1%} {p['recall']:7.1%} {p['f1']:7.1%}")
u = report["unsupported"]["headline"]
print(f"\nUnsupported (excluded): {u['exact']}/{u['games']} exact; patch F1={u['patches']['f1']:.1%}")
for game in report["games"]:
s = game["score"]
if verbose or not s["headline"]["exact"] or not s["runtime"]["exact"] or game["status"] == "unsupported":
print(f"\n{game['package']} [{game['engine']}, {game['status']}, {game['split']}"
+ (", converted" if game["converted"] else "") + "]")
for scope in ("headline", "runtime"):
for diff in ("missing", "extra"):
if s[scope][diff]:
print(f" {scope} {diff}: {json.dumps(s[scope][diff], sort_keys=True)}")
if not s[scope]["fields"].get("status_unsupported", True):
print(f" {scope} status_unsupported: catalog={game['want']['status_unsupported']} "
f"heuristics={game['got']['status_unsupported']}")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("dumps", type=Path)
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("dumps", type=Path, nargs="?")
ap.add_argument("--snapshot", type=Path)
ap.add_argument("--split", choices=("dev", "holdout", "all"), default="dev")
ap.add_argument("--json", type=Path, dest="json_out")
ap.add_argument("--verbose", action="store_true")
ap.add_argument("--fit-report", action="store_true")
ap.add_argument("--out", type=Path, help="Markdown destination for --fit-report (otherwise stdout)")
args = ap.parse_args()
games = quest_dump.scan(args.dumps)
total = matched_fields = games_ok = 0
misses = []
for g in games:
a = analyze(g.apk, data_bytes=g.data_bytes())
if not catalog.lookup(a.package):
continue
want = signature(engine.suggest(a, use_catalog=True))
want["status_unsupported"] = (catalog.lookup(a.package).status == "unsupported"
and "32-bit" in catalog.lookup(a.package).notes)
got = signature(engine.suggest(a, use_catalog=False))
diffs = {k: (want[k], got[k]) for k in want if want[k] != got[k]}
total += len(want)
matched_fields += len(want) - len(diffs)
games_ok += not diffs
if diffs:
misses.append((a.package, diffs))
if args.verbose or diffs:
print(f"{'OK ' if not diffs else 'DIFF'} {a.package}")
for k, (w, h) in diffs.items():
print(f" {k}: catalog={w} heuristics={h}")
n = games_ok + len(misses)
print(f"\n{games_ok}/{n} games reproduced exactly; {matched_fields}/{total} recipe fields match")
return 0 if not misses else 1
if not args.snapshot and not args.dumps:
ap.error("provide a dumps folder or --snapshot")
if args.out and not args.fit_report:
ap.error("--out requires --fit-report")
snapshot = read_snapshot(args.snapshot) if args.snapshot else read_dumps(args.dumps)
# Explicitly bundled entries: remote caches and personal recipes must not affect this benchmark.
entries = catalog._load_dir(REPO / "catalog/games", "bundled")
if args.fit_report:
cache = (args.snapshot.parent if args.snapshot else args.dumps) / "patch-intro-dates.json"
report = fit_report(snapshot, entries, patch_intro_dates(cache))
markdown = render_fit_report(report)
if args.out:
args.out.write_text(markdown, encoding="utf-8")
print(f"{report['candidate_count']} candidates in {report['games_with_candidates']} games -> {args.out}")
else:
print(markdown, end="")
else:
cache = (args.snapshot.parent if args.snapshot else args.dumps) / "patch-intro-dates.json"
# dated scoring reads the cache --fit-report writes; a plain run never shells out for dates
dates = json.loads(cache.read_text(encoding="utf-8")) if cache.is_file() else None
report = evaluate(snapshot, entries, args.split, dates)
print_metrics(report, args.verbose)
if args.json_out:
args.json_out.write_text(json.dumps(report, indent=2, sort_keys=True, default=str) + "\n", encoding="utf-8")
# Retain the legacy evaluator's nonzero exit for recipe differences; JSON is still written.
return 0 if args.fit_report or report["headline"]["games"] == report["headline"]["exact"] else 1
if __name__ == "__main__":
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Analyse every Quest dump below the given folders once and save the analyses as JSON, so heuristics evaluations
(`eval_heuristics.py --snapshot`) don't re-read gigabytes of APKs each run.
python scripts/heuristics_snapshot.py <out.json> <dumps folder> [<dumps folder> ...]
An original APK beats an already converted one (OVRPort output, e.g. PATCHED/ copies): converted inputs change what
the heuristics suggest, so they are only kept when no original exists and are marked `converted`. The output holds
local paths: keep it out of git.
"""
from __future__ import annotations
import argparse
import dataclasses
import json
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from frameport.analysis.detect import ANALYSIS_VERSION, analyze # noqa: E402
from frameport.sources import quest_dump # noqa: E402
def _skip(game, roots: list[Path]) -> bool:
"""Folders starting with "_" (known-good backups, test builds, keys) are not dumps."""
for root in roots:
try:
rel = game.apk.relative_to(root)
except ValueError:
continue
return any(part.startswith("_") for part in rel.parts[:-1])
return False
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("out", type=Path)
ap.add_argument("roots", type=Path, nargs="+")
args = ap.parse_args()
roots = [r.resolve() for r in args.roots]
old = json.loads(args.out.read_text()) if args.out.is_file() else {}
snap: dict[str, dict] = {}
for root in roots:
for g in quest_dump.scan(root):
if _skip(g, roots):
continue
key = str(g.apk)
cached = next((v for v in old.values() if v.get("apk") == key
and v.get("analysis_version") == ANALYSIS_VERSION
and v.get("apk_size") == g.apk.stat().st_size), None)
t = time.time()
if cached:
entry = cached
else:
try:
data_bytes = g.data_bytes()
a = analyze(g.apk, data_bytes=data_bytes)
except Exception as e: # noqa: BLE001 - one unreadable dump mustn't stop the snapshot
print(f"FAIL {g.apk}: {e}", file=sys.stderr, flush=True)
continue
entry = {"analysis": dataclasses.asdict(a), "data_bytes": data_bytes, "apk": key,
"apk_size": g.apk.stat().st_size, "name": g.name, "root": str(root),
"converted": bool(a.is_overport_output), "analysis_version": ANALYSIS_VERSION}
pkg = entry["analysis"]["package"]
have = snap.get(pkg)
# originals beat converted copies; otherwise the first root given wins
if have is None or (have["converted"] and not entry["converted"]):
snap[pkg] = entry
print(f"{'cache' if cached else f'{time.time() - t:5.1f}s'} {pkg}"
f"{' (converted)' if entry['converted'] else ''}", flush=True)
args.out.write_text(json.dumps(snap, indent=1, default=str)) # partial results survive a crash
print(f"{len(snap)} packages ({sum(v['converted'] for v in snap.values())} converted only) -> {args.out}")
return 0
if __name__ == "__main__":
sys.exit(main())
-2
View File
@@ -42,8 +42,6 @@ def stage_data():
shutil.copytree(ROOT / name, DATA / name)
# the Frame agent is uploaded as source; `flet build` turns every .py into .pyc (issue #2): keep a non-.py copy
shutil.copy2(ROOT / "agent/frameport_agent.py", DATA / "agent/frameport_agent.py.txt")
for helper in (ROOT / "agent").glob("fexrift*.py"): # experimental Rift-on-Frame helper + its extensions
shutil.copy2(helper, DATA / "agent" / f"{helper.name}.txt")
print(f"staged data in {DATA}")
-30
View File
@@ -1,30 +0,0 @@
"""One bounded Rift-on-Frame run. Uses the paired Frame and prints exactly one JSON summary on success.
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run python scripts/rift_fex_bench.py oculus-first-contact --seconds 120
Settings are changed separately with `frameport fex settings APP key=value`; this script never starts a sweep.
The Frame owns the timeout/cleanup, so closing this PC process does not leave an unbounded game running.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("app", nargs="?", default="oculus-first-contact")
p.add_argument("--seconds", type=int, default=120, choices=range(1, 121), metavar="1..120")
p.add_argument("--frame", help="paired Frame as user@host")
args = p.parse_args(argv)
# Reuse the CLI's feature gate, paired-host verification and JSON output. No second SSH implementation.
from frameport.cli import fex_bench
fex_bench(args.app, args.seconds, args.frame)
return 0
if __name__ == "__main__":
sys.exit(main())
-378
View File
@@ -1,378 +0,0 @@
"""Static compatibility survey of Rift games for the experimental Rift-on-Frame mode (x86_64 GE-Proton under FEX +
Meta's runtime + Revive, see native/fexwine/README.md). Read-only: looks at the game folders' PE files and the Unreal
config inside paks; never runs anything, never touches a repack's own Oculus Platform files (only notes them).
Engine, VR APIs and the Platform SDK come from FramePort's own Rift analysis (analysis/rift.py); on top of that:
the Unreal version (branch string, else the pak format's range), the RHI the game's config selects, the generic
Unreal IME fix site (agent/fexrift.py find_ime_patch), anti-tamper sections and other runtime needs.
usage: uv run python scripts/rift_fex_survey.py [--folder DIR ...] [--out DIR]
default input: the library's rift.* games; output: <user data>/fexrift/survey.{md,json} (holds local paths and folder
names: keep it out of the repo)
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import re
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from frameport.analysis import rift # noqa: E402
from frameport.core import library # noqa: E402
from frameport.core.paths import user_data_dir # noqa: E402
def load_fexrift():
spec = importlib.util.spec_from_file_location("fexrift_helper", ROOT / "agent" / "fexrift.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
mod.load_extensions()
return mod
FX = load_fexrift()
MAX_PE = 400 << 20
DRM_SECTIONS = {".arch": "Denuvo/Arxan-style section", ".vmp0": "VMProtect", ".vmp1": "VMProtect", ".bind": "Steam DRM",
".themida": "Themida", ".enigma1": "Enigma"}
ANTICHEAT_FILES = ("easyanticheat", "battleye", "beclient", "eac_launcher")
# Shared pak/ini reader (also used by the local-copy installer).
from frameport.analysis.unreal_pak import ( # noqa: E402, F401
CONFIG_KEYS,
PAK_MAGIC,
PAK_UE,
Reader,
encoded_entry,
entry_header_size,
legacy_entry,
pak_entries,
pak_read,
parse_engine_ini,
unreal_config,
)
RHI_NAMES = {"DefaultGraphicsRHI_DX11": "d3d11", "DefaultGraphicsRHI_DX12": "d3d12",
"DefaultGraphicsRHI_Vulkan": "vulkan"}
def unreal_rhi(cfg: dict) -> tuple[str, str]:
"""(RHI the Windows build starts with, where that came from). Unreal 4 defaults to D3D11."""
if cfg.get("DefaultGraphicsRHI") in RHI_NAMES:
return RHI_NAMES[cfg["DefaultGraphicsRHI"]], "config"
rhis = cfg.get("TargetedRHIs") or []
if rhis and not any(r.startswith("PCD3D") for r in rhis):
if any("VULKAN" in r for r in rhis):
return "vulkan", "config (no D3D shaders)"
if any(r.startswith("GLSL") for r in rhis):
return "opengl", "config (no D3D shaders)"
if rhis and all(r == "PCD3D_SM6" for r in rhis if r.startswith("PCD3D")):
return "d3d12", "config (SM6 shaders only)"
return "d3d11", "config" if rhis else "Unreal default"
# ------------------------------------------------------------------------------------------ PE checks
def pe_files(game_dir: Path, limit: int = 600):
out = []
for p in game_dir.rglob("*"):
if p.suffix.lower() in (".exe", ".dll") and p.is_file():
out.append(p)
if len(out) >= limit:
break
return out
_BRANCH = re.compile(r"\+\+[A-Za-z0-9_+.\-]{3,60}")
_VER = re.compile(r"(?<![\d.])([45])\.(\d{1,2})(?![\d])")
def unreal_version(data: bytes) -> str | None:
""""4.13" etc. from Unreal's branch name (++UE4+Release-4.13, ++unreal+4.10+UE4-Studio, ++UE4+Studio-4.27; ASCII
or UTF-16). Branches without a number (++depot+Game) give None."""
texts = [m.group(0).decode() for m in re.finditer(_BRANCH.pattern.encode(), data)]
key = "++".encode("utf-16-le")
i = data.find(key)
while i >= 0 and len(texts) < 2000:
m = _BRANCH.match(data[i:i + 128].decode("utf-16-le", "replace"))
if m:
texts.append(m.group(0))
i = data.find(key, i + 4)
for t in texts:
letters = sum(c.isalpha() for c in t)
if letters < 4 or not re.search(r"ue[45]|unreal|release", t, re.I):
continue
m = _VER.search(t)
if m:
return f"{m.group(1)}.{m.group(2)}"
return None
def sections(data: bytes) -> list[str]:
try:
return [s[0] for s in FX.pe_sections(data)]
except struct.error:
return []
def imports_of(p: Path) -> set[str]:
try:
info = rift.read_pe(p, limit=80 << 20)[0]
return set(info.imports) | set(info.delay_imports)
except (rift.PEError, OSError, struct.error, ValueError):
return set()
GRAPHICS = {"d3d11.dll": "d3d11", "d3d12.dll": "d3d12", "opengl32.dll": "opengl", "vulkan-1.dll": "vulkan",
"d3d9.dll": "d3d9"}
def survey_game(title: str, game_dir: Path, exe_rel: str | None) -> dict:
res = {"title": title, "folder": str(game_dir)}
if not game_dir.is_dir():
res["verdict"] = ("missing", "folder not found")
return res
exe = game_dir / exe_rel if exe_rel else None
if not exe or not exe.is_file():
res["verdict"] = ("unknown", "main exe not known")
return res
a = rift.analyze(game_dir, exe_rel)
files = pe_files(game_dir)
names = {p.name.lower(): p for p in files}
info, data = rift.read_pe(exe, limit=MAX_PE)
data = bytes(data)
res["exe"] = exe_rel
res["arch"] = info.machine
res["exe_32bit"] = info.machine == "x86"
res["exe_size"] = exe.stat().st_size
res["vr"] = [x for x in a.xr.split("+") if x != "?"] or ["?"]
res["platform_sdk"] = bool(a.extra.get("platform_sdk"))
res["own_platform_dll"] = any(n.startswith("libovrplatform") for n in names) # noted only, never used
imports = set(info.imports) | set(info.delay_imports)
# engine
if a.engine == "Unreal":
cores = [p for n, p in names.items() if re.search(r"-core(-win64-shipping)?\.dll$", n)]
ue = unreal_version(data) or next((v for v in map(lambda p: unreal_version(p.read_bytes()), cores) if v), None)
cfg = unreal_config(game_dir)
res.update(cfg)
pak_v = int(cfg["pak"][1:]) if re.fullmatch(r"v\d+", cfg.get("pak", "")) else None
res["ue_version"] = ue or (PAK_UE.get(pak_v) and f"{PAK_UE[pak_v]} (pak v{pak_v})") or "?"
res["engine"] = f"Unreal {res['ue_version']}"
rhi, src = unreal_rhi(cfg.get("config") or {})
res["graphics"] = [rhi]
res["graphics_from"] = src
# Unreal IME deadlock fix: exe (monolithic), else modular ApplicationCore/Slate (Core before that split).
patch, why = FX.find_ime_patch(data)
if not patch:
for n, p in sorted(names.items()):
if "applicationcore" in n or re.search(r"-(slate|core)(-win64-shipping)?\.dll$", n):
p2, why2 = FX.find_ime_patch(p.read_bytes())
if p2:
patch, why = dict(p2, module=n), None
break
if not why2.startswith("no Slate"):
why = why2
res["ime_patch"] = {"rva": hex(patch["rva"]), "module": patch.get("module", "exe")} if patch else why
lo = (res["ue_version"].split(" ")[0].split("-")[0]).split(".")
try:
major_minor = (int(lo[0]), int(lo[1]))
res["large_block_alloc"] = "FMallocBinned2 (UE>=4.18): fp_mem candidate" if major_minor >= (4, 18) \
else "FMallocBinned (older): fp_mem likely unneeded"
except (ValueError, IndexError):
res["large_block_alloc"] = "?"
else:
for p in files: # graphics imports of the game's own DLLs (Unity players, custom engines)
if p.parent == exe.parent and p.stat().st_size <= 80 << 20:
imports |= imports_of(p)
res["graphics"] = sorted({v for k, v in GRAPHICS.items() if k in imports}) or ["?"]
res["graphics_from"] = "imports"
if a.engine == "Unity":
src = names.get("unityplayer.dll")
blob = rift.read_pe(src, limit=MAX_PE)[1] if src else data
uv = re.search(rb"(20\d\d\.\d+\.\d+[fp]\d+|5\.\d\.\d+[fp]\d+)", blob)
res["engine"] = f"Unity {uv.group(1).decode() if uv else '?'} " + \
("IL2CPP" if "gameassembly.dll" in names else "Mono")
elif any(n.startswith("crysystem") for n in names) or b"CryEngine" in data or b"CRYENGINE" in data:
res["engine"] = "CryEngine"
else:
res["engine"] = "custom"
# anti-tamper / anti-cheat
drm = sorted({DRM_SECTIONS[s] for s in sections(data) if s in DRM_SECTIONS})
if any(any(x in n for x in ANTICHEAT_FILES) for n in names):
drm.append("anti-cheat files")
res["drm"] = drm
# other runtime needs
# Imports in modular engine/audio/video DLLs matter too. Reuse this for each candidate exe below; companion
# middleware is a folder-level hint, not proof that a particular movie or audio route will be exercised.
runtime_imports = set(imports)
for p in files:
if p.suffix.lower() == ".dll" and p.parent == exe.parent and p.stat().st_size <= 80 << 20:
runtime_imports |= imports_of(p)
res["runtime"] = runtime_facts(runtime_imports, names)
res["executables"] = []
for candidate in a.extra.get("exe_candidates", []):
rel = candidate["path"]
p = game_dir / rel
try:
pi = info if p == exe else rift.read_pe(p, limit=80 << 20)[0]
facts = runtime_facts(set(pi.imports) | set(pi.delay_imports), names)
g = sorted({GRAPHICS[i] for i in set(pi.imports) | set(pi.delay_imports) if i in GRAPHICS})
res["executables"].append(dict(exe=rel, arch=pi.machine, exe_32bit=pi.machine == "x86",
graphics_imports=g, **facts))
except (OSError, rift.PEError, struct.error, ValueError):
res["executables"].append({"exe": rel, "error": "PE unreadable"})
other = []
if "mscoree.dll" in imports:
other.append(".NET")
if res["runtime"]["xaudio2"]:
other.append("XAudio2")
if res["runtime"]["media_foundation"]:
other.append("Media Foundation: video playback is a Proton compatibility risk")
if res["runtime"]["bink"]:
other.append("Bink video")
winrt_re = rb"W\x00i\x00n\x00d\x00o\x00w\x00s\x00\.\x00(?:[A-Z]\x00[a-zA-Z\x00\.]{4,80})"
winrt = sorted({w.decode("utf-16-le") for w in re.findall(winrt_re, data)})[:5]
if winrt:
other.append("WinRT: " + ", ".join(winrt))
res["other"] = other
res["size_gib"] = round(sum(p.stat().st_size for p in game_dir.rglob("*") if p.is_file()) / 2**30, 1)
res["verdict"] = verdict(res)
res["suggested_graphics"] = graphics_route(res)
res["profile"] = suggested_profile(res)
return res
def runtime_facts(imports: set[str], names) -> dict:
imports = {i.lower() for i in imports}
names = {n.lower() for n in names}
return {"xaudio2": any(i.startswith("xaudio2") for i in imports),
"media_foundation": bool(imports & {"mf.dll", "mfplat.dll", "mfreadwrite.dll", "evr.dll"}),
"bink": any(n.startswith("bink") for n in names | imports),
"anti_cheat": any(any(s in n for s in ANTICHEAT_FILES) for n in names | imports)}
def graphics_route(r: dict) -> str:
g = r.get("graphics", [])
# Unreal's config already reduced its imports to the selected RHI. For custom multi-API engines prefer a
# DXVK route over GL; imports prove availability, not that the game will select that renderer at runtime.
return next((api for api in ("d3d11", "d3d12", "d3d9", "opengl", "vulkan") if api in g), "d3d11")
def suggested_profile(r: dict) -> dict:
status = {"likely OK": "likely", "blocked": "blocked"}.get(r["verdict"][0], "untested")
profile = {"title": r["title"],
"match": {"executables": [{"name": Path(r["exe"]).name, "size": r["exe_size"]}]},
"status": status, "graphics": graphics_route(r), "env": {}, "ime_patch": None,
"fp_mem": "candidate" if "candidate" in r.get("large_block_alloc", "") else "off",
"bigcache_mb": 256, "dxvk": [],
"notes": r["verdict"][1] + ("; Media Foundation videos need a playback test" if
r.get("runtime", {}).get("media_foundation") else "")}
if r.get("vr") == ["OpenVR"]:
profile["revive"] = False
if r.get("folder"):
info = {"exe": r["exe"], "game_dir": r["folder"]}
for hook in FX.GAME_INFO_HOOKS:
hook("", info)
# Keep an existing build-matched direct-OpenVR choice (e.g. Unity that also contains inert LibOVR strings)
# when generating pasteable data. Do not propagate guesses from the folder/title or a bundled crack.
if info.get("revive") is False:
profile["revive"] = False
return profile
def verdict(r: dict) -> tuple[str, str]:
"""(likely OK | needs work | blocked, why). "likely OK" = the profile First Contact has on the Frame: x64,
D3D11, Unreal with the IME fix site found (or an engine without that deadlock), a VR API Revive/SteamVR serve."""
blockers, work = [], []
if r.get("arch") not in ("x86_64", "amd64", "AMD64"):
work.append(f"{r.get('arch')} exe: needs GE's 32-bit (wow64) path under FEX (untested)")
g = r.get("graphics", [])
if "d3d11" not in g:
if "d3d12" in g:
work.append("D3D12: needs vkd3d-proton on Turnip under FEX (untested)")
elif "d3d9" in g:
work.append("D3D9: DXVK under FEX (untested)")
elif "opengl" in g:
work.append("OpenGL: no FEX GL thunk configured; rootfs GL renderer unverified")
elif "vulkan" in g:
work.append("Vulkan: Turnip through FEX's Vulkan thunk (untested with a game)")
else:
work.append(f"graphics API unclear ({', '.join(g)})")
if "anti-cheat files" in r.get("drm", []) or r.get("runtime", {}).get("anti_cheat"):
blockers.append("anti-cheat")
elif r.get("drm"):
work.append("anti-tamper section (" + ", ".join(r["drm"]) + "): heavier under FEX, may break")
if r.get("vr") == ["?"]:
work.append("VR API not detected")
if r.get("engine", "").startswith("Unreal") and isinstance(r.get("ime_patch"), str):
work.append(f"IME fix site not found ({r['ime_patch']})")
if r.get("engine") in ("custom", "CryEngine"):
work.append(f"{r['engine']} engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown")
if blockers:
return "blocked", "; ".join(blockers + work)
if work:
return "needs work", "; ".join(work)
return "likely OK", "same profile as First Contact (x64, D3D11, " + "/".join(r.get("vr", [])) + ")"
def library_games():
for g in library.games():
if not str(g.get("package", "")).startswith("rift."):
continue
extra = (g.get("analysis") or {}).get("extra") or {}
gd = g.get("game_dir") or extra.get("folder") or ""
yield g.get("title") or g["package"], Path(gd), g.get("exe") or extra.get("exe")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--folder", action="append", default=[])
ap.add_argument("--out", default=str(user_data_dir() / "fexrift"))
args = ap.parse_args()
if args.folder:
games = []
for f in args.folder:
a = rift.analyze(Path(f))
games.append((a.label, Path(f), a.extra.get("exe")))
else:
games = list(library_games())
results = []
for title, d, exe in sorted(games, key=lambda t: t[0].lower()):
try:
r = survey_game(title, d, exe)
except Exception as e: # noqa: BLE001 - one broken folder shouldn't stop the survey
r = {"title": title, "folder": str(d), "verdict": ("error", f"{type(e).__name__}: {e}")}
results.append(r)
print(f"{r['verdict'][0]:11s} {title}", flush=True)
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
(out / "survey.json").write_text(json.dumps(results, indent=1))
profiles = {re.sub(r"[^a-z0-9]+", "-", r["title"].lower()).strip("-"): r["profile"]
for r in results if r.get("profile")}
(out / "profiles.json").write_text(json.dumps(profiles, indent=2) + "\n")
lines = ["# Rift-on-Frame static survey", "",
"| Game | Verdict | Engine | Graphics | VR | Platform SDK | IME fix | AA config | Notes |",
"|---|---|---|---|---|---|---|---|---|"]
for r in results:
cfg = r.get("config") or {}
aa = ", ".join(f"{k}={v}" for k, v in cfg.items() if "MSAA" in k or "AntiAliasing" in k) or r.get("pak", "")
ime = r.get("ime_patch")
if isinstance(ime, dict):
ime = ime["rva"] + ("" if ime.get("module") == "exe" else f" ({ime['module']})")
else:
ime = str(ime)[:40] if r.get("engine", "").startswith("Unreal") else "n/a"
graphics = ", ".join(r.get("graphics", [])) + (f" ({r['graphics_from']})" if r.get("graphics_from") else "")
lines.append(f"| {r['title']} | {r['verdict'][0]} | {r.get('engine', '')} | {graphics} | "
f"{', '.join(r.get('vr', []))} | {'yes' if r.get('platform_sdk') else 'no'} | {ime} | {aa} | "
f"{r['verdict'][1]} |")
(out / "survey.md").write_text("\n".join(lines) + "\n")
print(f"report: {out / 'survey.md'}")
if __name__ == "__main__":
main()
+27 -2
View File
@@ -101,6 +101,8 @@ def main() -> int:
ap.add_argument("--viewport", default="1280x820", help="browser size, e.g. 2560x1440")
ap.add_argument("--update", action="store_true", help="pretend a new FramePort release exists (update UI: "
"changelog dialog, what's new bar + dialog, Settings changelog)")
ap.add_argument("--announcement", action="store_true", help="show the announcement pop-up (with a picture, "
"then text only); nothing is fetched")
ap.add_argument("--fake-frame", action="store_true", help="pretend a Steam Frame is connected (no device needed)")
ap.add_argument("--hover", default=None, help="x,y: move the mouse there before the Library screenshot")
ap.add_argument("--install-questions", nargs="+", metavar="PKG", default=None,
@@ -137,7 +139,8 @@ def main() -> int:
("monitor", lambda a: a.go("monitor")), ("monitor-details", open_monitor_details),
("tools", lambda a: a.go("settings")),
# the index on the left: "This PC" scrolls the page there
("settings-index", lambda a: a.page.run_task(a.settings_view.show_section, "pc"))]
("settings-index", lambda a: a.page.run_task(a.settings_view.show_section, "pc")),
("settings-installing", lambda a: a.page.run_task(a.settings_view.show_section, "installing"))]
if game:
steps.insert(1, ("game", lambda a: a.open_game(game)))
steps.insert(2, ("game-customize", lambda a: a.open_game(game, advanced=True)))
@@ -150,7 +153,8 @@ def main() -> int:
if args.fake_frame: # GitHub #90: the Move to… dialog (drives load in the background)
steps.append(("move-dialog", lambda a: (a.page.pop_dialog(), a.move_game(game))))
steps.append(("uninstall-dialog", lambda a: (a.page.pop_dialog(), a.uninstall(game))))
# last: the right-click menu stays open over whatever comes next
# last: the menus stay open over whatever comes next (the page's "…" menu, then the right-click menu)
steps.append(("game-menu", lambda a: (a.show_activity(False), a.open_game_menu(game))))
steps.append(("library-menu", lambda a: (a.show_activity(False), a.navigate(0), time.sleep(3),
a.library_view.open_menu(game))))
if args.docs:
@@ -278,6 +282,7 @@ def main() -> int:
("linux-change-program", lambda a: a.choose_exe(LINUX_FOLDER)),
("frame", lambda a: (a.page.pop_dialog(), a.navigate(1))),
("linux-move", lambda a: a.move_game(LINUX_APPIMAGE) if args.fake_frame else None),
("linux-game-menu", lambda a: (a.page.pop_dialog(), a.open_game_menu(LINUX_FOLDER))),
("linux-menu", lambda a: (a.page.pop_dialog(), a.navigate(0), time.sleep(3),
a.library_view.open_menu(LINUX_APPIMAGE)))]
if args.links:
@@ -418,6 +423,26 @@ def main() -> int:
print(f"open dialogs: {len([d for d in a.page._dialogs.controls if d.open])}, queued: {queued}", flush=True)
steps = [("library", lambda a: a.navigate(0)), ("questions", open_questions),
("after-1st-double", double_click), ("after-2nd-double", double_click), ("end", report)]
if args.announcement:
import shutil
from frameport import announcements
from frameport.core.paths import user_data_dir
text = ("---\nid: smoke\ntitle: FramePort 1.3 brings the Monitor to every Frame\ndate: 2026-10-14T12:00:00Z\n"
"---\n"
"The **Monitor** tab now shows fps, battery and temperatures for any game the Frame runs, including "
"Steam's own. Open it from the sidebar's Frame card.\n\n"
"- Install links from FrameDrop buttons open in FramePort\n"
"- Uploads over the USB cable are about **3× faster**\n\n"
"Questions? Ask in [Discussions](https://example.invalid).")
news = announcements.parse(text)
pic = user_data_dir() / "announcements" / "smoke.png"
pic.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(Path(__file__).resolve().parents[1] / "docs" / "images" / "library.png", pic)
steps = [("announcement-image", lambda a: (a.navigate(0), a.announcer.show(news, pic))),
("announcement-text", lambda a: (a.page.pop_dialog(), time.sleep(1.5), a.announcer.show(
announcements.parse(text.replace("id: smoke", "id: smoke2")))))]
if args.update:
from frameport import __version__, updates
+34 -1
View File
@@ -43,7 +43,10 @@ IL2CPP_METADATA = "assets/bin/Data/Managed/Metadata/global-metadata.dat"
# 17: headset (the Meta headset a VR app was made for: Gear VR / Go games run through frame.a32_bridge) (2026-10)
# 18: headset "quest" also for 32-bit apps that require 6DoF head tracking (Santa Cruz builds, e.g. Sports
# Scramble: Touch controllers on the a32 bridge) (2026-10)
ANALYSIS_VERSION = 19
# 19: unreal_obb_delivery also for obfuscated DownloaderActivity predicates (GitHub #159) (2026-10)
# 20: google_vr (Google Daydream / Cardboard builds: GVR or Cardboard SDK, no path to the Frame's headset,
# GitHub #335) (2026-10)
ANALYSIS_VERSION = 20
# Android versions by API level (for messages); the Frame's Lepton container runs Android 11 (API 30)
@@ -197,6 +200,32 @@ def vr_kind(libs: set[str], manifest_strings: list[str]) -> str:
return "none"
# Google VR (Daydream / Cardboard): the manifest categories of a Daydream / Cardboard app, Daydream's VR service
# (android:enableVrMode="com.google.vr.vrcore/..."), the GVR SDK's library and the Cardboard SDK's
# (github.com/googlevr/cardboard), and the GVR SDK's Java classes. Not libgvraudio.so / Unity's
# libaudioplugingvrunity.so: Google's spatial audio, which Quest games ship too (e.g. Shadow Point).
DAYDREAM_CATEGORY = "com.google.intent.category.DAYDREAM"
CARDBOARD_CATEGORY = "com.google.intent.category.CARDBOARD"
GOOGLE_VR_LIBS = {"libgvr.so", "libcardboard_api.so", "libGfxPluginCardboard.so"}
GVR_DEX_MARKERS = (b"Lcom/google/vr/ndk/base/GvrLayout;", b"Lcom/google/vr/sdk/base/GvrView;",
b"Lcom/google/vr/sdk/base/GvrActivity;", b"Lcom/google/cardboard/sdk/")
def google_vr(libs: set[str], cats: set[str], manifest_strings: list[str], gvr_java: bool = False,
boot: str = "") -> str:
"""A Google VR app: "daydream" (Daydream: needs Google's VR services, VrCore), "cardboard" (Cardboard: draws
both eyes side by side with lens distortion onto a phone screen) or "" (neither). Neither has a path to the
Frame's headset: a Lepton app only reaches it through OpenXR (VrApi / OVRPlugin games are translated to it).
`boot` = Unity's boot.config (vr-device-list=, where Unity builds list their VR devices)."""
devices = next((ln.split("=", 1)[1].lower() for ln in boot.splitlines() if ln.startswith("vr-device-list=")), "")
if (DAYDREAM_CATEGORY in cats or any(s.startswith("com.google.vr.vrcore") for s in manifest_strings)
or "daydream" in devices):
return "daydream"
if CARDBOARD_CATEGORY in cats or "cardboard" in devices or libs & GOOGLE_VR_LIBS or gvr_java:
return "cardboard"
return ""
# Kotlin's message for a failed non-null cast to ClipboardManager (Godot 4.2-4.4; 4.1 is Java, 4.5+ uses `as?`)
GODOT_CLIPBOARD_CAST = b"null cannot be cast to non-null type android.content.ClipboardManager"
@@ -249,6 +278,8 @@ def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Ana
for d in dexes)
# video through Android's decoders (frame.hw_video_decode): Java MediaCodec, ExoPlayer/Media3, or libVLC
media_codec = any(m in d for d in dexes for m in MEDIA_CODEC_MARKERS) or "libvlc.so" in libs
# Google VR's Java side (GvrLayout / GvrView, the Cardboard SDK): a Daydream / Cardboard app (google_vr)
gvr_java = any(m in d for d in dexes for m in GVR_DEX_MARKERS)
from ..patches.frame.unreal_obb_check import has_delivery_check
# Includes obfuscated DownloaderActivity predicates; CRC verification is a separate manifest switch.
@@ -372,6 +403,8 @@ def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Ana
"xr_layer_exts": sorted(layer_exts), # composition-layer extensions the game's own libraries request
"vr_kind": vr_kind(libset, manifest_strings),
"headset": headset(meta, abis, vr_kind(libset, manifest_strings), requires_6dof(manifest)),
# a Google Daydream / Cardboard build (GVR / Cardboard SDK): no path to the Frame's headset (GitHub #335)
"google_vr": google_vr(libset, cats, manifest_strings, gvr_java, boot),
# the base of a split APK set (Play "app bundle" installs): the code/libraries live in split APKs
"split_apk": bool({"isSplitRequired", "requiredSplitTypes"} & set(manifest_strings)),
# Unity (IL2CPP) text fields: they close at once on the Frame (frame.unity_text_input)
-202
View File
@@ -1,202 +0,0 @@
"""Read unencrypted Unreal paks and DefaultEngine.ini without extracting game files (stdlib only)."""
from __future__ import annotations
import struct
import zlib
from pathlib import Path
# ------------------------------------------------------------------------------------------ Unreal paks
PAK_MAGIC = 0x5A6F12E1
# pak format version -> the Unreal versions that write it (when the exe doesn't name its version)
PAK_UE = {1: "4.0-4.2", 2: "4.0-4.2", 3: "4.3-4.15", 4: "4.16-4.19", 5: "4.20", 6: "4.20", 7: "4.21",
8: "4.22-4.24", 9: "4.25", 10: "4.26", 11: "4.26-4.27"}
class Reader:
def __init__(self, buf: bytes, pos: int = 0):
self.buf, self.p = buf, pos
def take(self, fmt: str):
v = struct.unpack_from(fmt, self.buf, self.p)
self.p += struct.calcsize(fmt)
return v if len(v) > 1 else v[0]
def fstring(self) -> str:
n = self.take("<i")
if n < 0:
s = self.buf[self.p:self.p - 2 * n].decode("utf-16-le", "replace")
self.p += -2 * n
else:
s = self.buf[self.p:self.p + n].decode("latin-1")
self.p += n
return s.rstrip("\0")
def entry_header_size(ver: int, compressed: bool, nblocks: int) -> int:
"""Size of the FPakEntry copy in front of a file's data (offset, sizes, method, hash, blocks, flags, block size)."""
return 8 + 8 + 8 + 4 + 20 + (4 + 16 * nblocks if compressed else 0) + (1 + 4 if ver >= 3 else 0)
def legacy_entry(r: Reader, ver: int):
"""A full FPakEntry: (offset, compressed size, size, method, blocks, encrypted)."""
off, csize, usize = r.take("<qqq")
method = r.take("<i")
r.p += 20
blocks, enc = [], 0
if ver >= 3:
if method:
nb = r.take("<i")
blocks = [r.take("<qq") for _ in range(nb)]
enc = r.buf[r.p]
r.p += 1 + 4
return off, csize, usize, method, blocks, enc
def encoded_entry(buf: bytes, pos: int, ver: int):
"""A v10+ bit-packed entry (FPakFile::DecodePakEntry); blocks relative to the entry like v7+ full entries."""
r = Reader(buf, pos)
v = r.take("<I")
if v & 0x3f == 0x3f:
r.take("<I") # compression block size (not needed to read)
method = (v >> 23) & 0x3f
off = r.take("<I" if v & (1 << 31) else "<Q")
usize = r.take("<I" if v & (1 << 30) else "<Q")
csize = r.take("<I" if v & (1 << 29) else "<Q") if method else usize
enc = bool(v & (1 << 22))
nb = (v >> 6) & 0xffff
base = entry_header_size(ver, bool(method), nb)
blocks = []
if nb == 1 and not enc:
blocks = [(base, base + csize)]
elif nb:
o = base
for _ in range(nb):
s = r.take("<I")
blocks.append((o, o + s))
o += (s + 15) & ~15 if enc else s
return off, csize, usize, method, blocks, enc
def pak_entries(path: Path):
"""(version, mount point, {name: entry}, compression names) of an unencrypted UE4 pak, v1-v11; ValueError if the
index can't be read (encrypted, unknown footer)."""
with open(path, "rb") as f:
f.seek(0, 2)
size = f.tell()
f.seek(max(0, size - 512))
tail = f.read()
i = tail.rfind(struct.pack("<I", PAK_MAGIC), 0, len(tail) - 40)
while i >= 0 and len(tail) - i not in (44, 44 + 4 * 32, 44 + 5 * 32): # magic..end, 0/4/5 method names
i = tail.rfind(struct.pack("<I", PAK_MAGIC), 0, i)
if i < 0:
raise ValueError("no pak footer")
_, ver, ioff, isize = struct.unpack_from("<IIqq", tail, i)
if ver >= 4 and i >= 1 and tail[i - 1] == 1:
raise ValueError(f"pak v{ver}: index encrypted")
names = [tail[j:j + 32].split(b"\0")[0].decode("latin-1") for j in range(i + 44, len(tail) - 31, 32)]
if not 0 <= ioff < size or not 0 < isize <= size - ioff:
raise ValueError(f"pak v{ver}: index outside the file")
f.seek(ioff)
r = Reader(f.read(isize))
mount = r.fstring()
count = r.take("<i")
entries = {}
if ver < 10:
for _ in range(count):
name = r.fstring()
entries[name] = legacy_entry(r, ver)
return ver, mount, entries, names
r.take("<Q") # path hash seed
if r.take("<i"):
r.take("<qq")
r.p += 20 # path hash index: hashes only, no names
if not r.take("<i"):
raise ValueError(f"pak v{ver}: no full directory index (names hashed only)")
fdi_off, fdi_size = r.take("<qq")
r.p += 20
enc_size = r.take("<i")
encoded = r.buf[r.p:r.p + enc_size]
r.p += enc_size
files = [legacy_entry(r, ver) for _ in range(r.take("<i"))]
f.seek(fdi_off)
d = Reader(f.read(fdi_size))
for _ in range(d.take("<i")):
folder = d.fstring()
for _ in range(d.take("<i")):
name, loc = d.fstring(), d.take("<i")
entries[(folder + name).lstrip("/")] = encoded_entry(encoded, loc, ver) if loc >= 0 else files[-loc - 1]
return ver, mount, entries, names
def pak_read(path: Path, ver: int, entry, names: list[str] | None = None) -> bytes:
off, csize, usize, method, blocks, enc = entry
if enc:
raise ValueError("entry encrypted")
with open(path, "rb") as f:
if not method:
f.seek(off + entry_header_size(ver, False, 0))
return f.read(usize)
kind = (names[method - 1] if ver >= 8 and names and 0 < method <= len(names) else "zlib").lower()
if kind not in ("zlib", "gzip"):
raise ValueError(f"{kind}-compressed")
out = b""
for s, e in blocks:
if ver >= 7:
s, e = s + off, e + off
f.seek(s)
out += zlib.decompress(f.read(e - s), 31 if kind == "gzip" else 15)
return out
CONFIG_KEYS = ("r.MobileMSAA", "r.MSAACount", "r.DefaultFeature.AntiAliasing", "r.ForwardShading",
"r.useclusteredforward", "vr.InstancedStereo", "r.MobileHDR", "DefaultGraphicsRHI", "TargetedRHIs",
"bUseVulkan")
def parse_engine_ini(text: str) -> dict:
"""The keys survey cares about; repeated keys (+TargetedRHIs=…) become lists."""
want = {k.lower(): k for k in CONFIG_KEYS}
vals: dict = {}
for line in text.splitlines():
k, _, v = line.strip().partition("=")
key = want.get(k.lstrip("+-.!").lower())
if not key:
continue
if key == "TargetedRHIs":
vals.setdefault(key, [])
if k.startswith("-"):
vals[key] = [x for x in vals[key] if x != v]
elif v not in vals[key]:
vals[key].append(v)
else:
vals[key] = v
return vals
def unreal_config(game_dir: Path) -> dict:
"""Pak format + rendering/AA settings from the project's DefaultEngine.ini (paks, else a loose file)."""
paks = sorted(game_dir.rglob("*.pak"), key=lambda p: -p.stat().st_size)
notes, ver_seen = [], None
for pak in paks[:6]:
try:
ver, _, entries, names = pak_entries(pak)
except (ValueError, OSError, struct.error, IndexError) as e:
notes.append(f"{pak.name}: {e}")
continue
ver_seen = ver_seen or ver
name = next((n for n in entries if n.endswith("Config/DefaultEngine.ini")), None)
if not name:
continue
try:
text = pak_read(pak, ver, entries[name], names).decode("utf-8-sig", "replace")
except (ValueError, zlib.error, OSError) as e:
notes.append(f"{pak.name}: DefaultEngine.ini {e}")
continue
return {"pak": f"v{ver}", "config": parse_engine_ini(text), "pak_notes": notes}
loose = next((p for p in game_dir.rglob("DefaultEngine.ini") if p.parent.name == "Config"), None)
if loose:
text = loose.read_text("utf-8", "replace")
return {"pak": f"v{ver_seen}" if ver_seen else "", "config": parse_engine_ini(text),
"pak_notes": notes + ["config from a loose DefaultEngine.ini"]}
return {"pak": f"v{ver_seen}" if ver_seen else "unreadable", "pak_notes": notes or ["no DefaultEngine.ini found"]}
+218
View File
@@ -0,0 +1,218 @@
"""Announcements: one short message from the maintainer, shown once as a pop-up in the app.
Source of truth: `announcements/current.md` on GitHub `main` (front matter + Markdown, announcements/README.md), read
through raw.githubusercontent like the catalog (cached, every 6 h), so a push reaches users without a release.
Who sees it: only people who were already using FramePort before the announcement's `date` (a first start never
shows one, and nor does one published before FramePort was installed). Closing it in any way (the X, a click outside,
Escape, its button) dismisses that `id` for good; a new announcement = a new id. No Flet here.
"""
from __future__ import annotations
import datetime as dt
import hashlib
import logging
import os
import re
import time
from dataclasses import dataclass
from pathlib import Path
import yaml
from . import REPO_URL
from .core import cache, library
from .core.paths import user_data_dir
_log = logging.getLogger("frameport.announcements")
REPO = REPO_URL.removeprefix("https://github.com/").strip("/")
PATH = "announcements/current.md"
RAW = f"https://raw.githubusercontent.com/{REPO}/main/"
URL = RAW + PATH
CHECK_EVERY = 6 * 3600
KEEP_DISMISSED = 50 # ids remembered (oldest dropped)
IMAGE_MAX = 5 * 2**20
ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$")
# settings only an earlier GUI run writes: one of them when announcements first run = an existing user (not
# recipes.app_version: library.load() writes that on the very first load)
USED_BEFORE = ("update.last_seen_version", "update.last_check", "ui.welcome_done", "ui.window")
@dataclass(frozen=True)
class Announcement:
id: str
title: str
body: str # Markdown
date: float # unix time it was published
image: str | None = None # https URL (repo paths are resolved to raw GitHub)
image_alt: str = ""
button: str | None = None # optional action: label + url
url: str | None = None
expires: float | None = None
class AnnouncementError(ValueError):
pass
def _when(value, end_of_day: bool = False) -> float:
"""A front-matter date (YAML date/datetime or ISO text) as unix time; a bare date is UTC midnight (or the end of
that day for `expires`). Naive times are UTC."""
if isinstance(value, str):
text = value.strip().replace("Z", "+00:00")
try:
value = dt.datetime.fromisoformat(text) if "T" in text or " " in text else dt.date.fromisoformat(text)
except ValueError as exc:
raise AnnouncementError(f"not a date: {value!r}") from exc
if isinstance(value, dt.datetime):
return (value if value.tzinfo else value.replace(tzinfo=dt.timezone.utc)).timestamp()
if isinstance(value, dt.date):
day = dt.datetime(value.year, value.month, value.day, tzinfo=dt.timezone.utc)
return (day + dt.timedelta(days=1 if end_of_day else 0)).timestamp()
raise AnnouncementError(f"not a date: {value!r}")
def _link(value) -> str | None:
"""An image/button target: https URLs as they are, a repo path (announcements/x.png) → its raw GitHub URL."""
if value in (None, ""):
return None
text = str(value).strip()
if text.startswith("https://"):
return text
if "://" in text or text.startswith(("/", "..")) or ".." in text.split("/"):
raise AnnouncementError(f"use an https URL or a path in the repo: {text!r}")
return RAW + text
def parse(text: str | None) -> Announcement | None:
"""The file's announcement; None when there is none (empty file, `active: false`). Raises AnnouncementError for a
malformed one (the app then shows nothing; tests/test_announcements.py checks the committed file)."""
if not text or not text.strip():
return None
m = re.match(r"\A?---\s*\n(.*?)\n---\s*(?:\n|\Z)(.*)\Z", text, re.S)
if not m:
raise AnnouncementError("missing the --- front matter")
try:
meta = yaml.safe_load(m.group(1)) or {}
except yaml.YAMLError as exc:
raise AnnouncementError(f"front matter: {exc}") from exc
if not isinstance(meta, dict):
raise AnnouncementError("front matter must be key: value lines")
active = meta.get("active", True)
if active is False and not meta.get("id"):
return None
if not isinstance(active, bool):
raise AnnouncementError("active: true or false")
unknown = set(meta) - {"id", "title", "date", "image", "image_alt", "button", "url", "expires", "active"}
if unknown:
raise AnnouncementError(f"unknown fields: {', '.join(sorted(unknown))}")
ident, title = str(meta.get("id") or "").strip(), str(meta.get("title") or "").strip()
if not ID_RE.match(ident):
raise AnnouncementError("id: letters, digits, '.', '_' or '-' (change it to show a new announcement)")
if not title:
raise AnnouncementError("title is required")
if "date" not in meta:
raise AnnouncementError("date is required (only people using FramePort before it see the announcement)")
button, url = meta.get("button"), meta.get("url")
if bool(button) != bool(url):
raise AnnouncementError("button and url go together")
if not active: # switched off, but still checked (tests catch mistakes before it's switched on)
_check_dates(meta)
return None
return Announcement(id=ident, title=title, body=m.group(2).strip(), date=_when(meta["date"]),
image=_link(meta.get("image")), image_alt=str(meta.get("image_alt") or ""),
button=str(button).strip() if button else None, url=_link(url),
expires=_when(meta["expires"], end_of_day=True) if meta.get("expires") else None)
def _check_dates(meta: dict) -> None:
_when(meta["date"])
if meta.get("expires"):
_when(meta["expires"], end_of_day=True)
_link(meta.get("image"))
_link(meta.get("url"))
def disabled() -> bool:
return bool(os.environ.get("FRAMEPORT_NO_ANNOUNCEMENTS"))
def fetch(force: bool = False) -> Announcement | None:
"""The current announcement (cached 6 h; offline → the last copy; never raises)."""
try:
return parse(cache.cached_text("announcement.md", URL, max_age=0 if force else CHECK_EVERY, fallback=""))
except Exception as exc: # noqa: BLE001
_log.warning("announcement skipped: %s", exc)
return None
# ------------------------------------------------------------------------------------------ who sees it
def since() -> float:
"""When this user started using FramePort, as far as announcements are concerned (setting announce.since). Set
once, the first time it's asked: 0 for someone who used FramePort before announcements existed, else now (a first
start). Call it early at start, before anything records this start in the settings."""
value = library.setting("announce.since")
if isinstance(value, (int, float)):
return float(value)
value = 0.0 if any(library.setting(k) is not None for k in USED_BEFORE) or library.games() else time.time()
library.set_setting("announce.since", value)
return value
def dismissed() -> list[str]:
value = library.setting("announce.dismissed")
return [v for v in value if isinstance(v, str)] if isinstance(value, list) else []
def dismiss(ident: str) -> None:
"""Never show this announcement again (any way of closing it)."""
library.update_setting("announce.dismissed",
lambda cur: ([v for v in (cur or []) if v != ident] + [ident])[-KEEP_DISMISSED:], [])
def due(a: Announcement | None, now: float | None = None, user_since: float | None = None) -> bool:
"""Whether to show `a` now: published, not expired, not dismissed, and published after this
user started using FramePort."""
if a is None:
return False
now = time.time() if now is None else now
if a.expires is not None and now >= a.expires:
return False
if a.date > now: # scheduled for later
return False
if a.id in dismissed():
return False
return a.date > (since() if user_since is None else user_since)
def image_file(a: Announcement) -> Path | None:
"""The announcement's image, downloaded once into <data>/announcements/ and checked (Pillow); None without one or
when it can't be loaded (the pop-up then shows no image). Shown by asset URL like artwork, never as bytes."""
if not a.image:
return None
folder = user_data_dir() / "announcements"
stem = hashlib.sha256(a.image.encode()).hexdigest()[:16]
for done in folder.glob(f"{stem}.*"):
if done.suffix != ".part":
return done
try:
from PIL import Image
tmp = folder / f"{stem}.part"
cache.download(a.image, tmp)
if tmp.stat().st_size > IMAGE_MAX:
raise AnnouncementError("image larger than 5 MiB")
with Image.open(tmp) as im:
im.verify()
fmt = (im.format or "").lower()
ext = {"jpeg": ".jpg", "png": ".png", "webp": ".webp", "gif": ".gif"}.get(fmt)
if not ext:
raise AnnouncementError(f"image format {fmt or '?'} (use PNG, JPEG, WebP or GIF)")
out = folder / f"{stem}{ext}"
tmp.replace(out)
return out
except Exception as exc: # noqa: BLE001
_log.warning("announcement image skipped: %s", exc)
(folder / f"{stem}.part").unlink(missing_ok=True)
return None
+49 -132
View File
@@ -54,9 +54,6 @@ app.add_typer(tools_app, name="tools")
app.add_typer(frame_app, name="frame")
app.add_typer(pc_app, name="pc")
app.add_typer(diag_app, name="diag")
fex_app = typer.Typer(help="Experimental (FRAMEPORT_EXPERIMENTAL_FEX=1): Oculus Rift games with Meta's PC runtime on "
"the Frame alone (x86_64 GE-Proton under FEX). Verified game: Oculus First Contact.")
app.add_typer(fex_app, name="fex", hidden=True)
def _show_version(value: bool):
@@ -401,6 +398,30 @@ def rename(package: str = typer.Argument(..., help="the game (package or part of
pipeline.sync_title(pkg, _target(None, to="pc"), rep)
@app.command("new-version")
def new_version(package: str = typer.Argument(..., help="the game (package or part of its title)"),
path: Path = typer.Argument(..., exists=True, help="the newer version: an APK (Quest/Android games), "
"an AppImage/archive/folder (Linux apps) or the game folder (PC VR)")):
"""Point a game at a newer version of it (GitHub #161). Its name, artwork, tags and your own recipe stay; install
it again (frameport install) to update it on the Frame."""
[pkg] = _pkgs(package, False)
try:
res = pipeline.replace_source(pkg, path, printing_reporter(verbose=False))
except pipeline.WrongPackage as exc:
raise typer.BadParameter(f"that APK is a different app: {exc}") from None
except ValueError as exc:
raise typer.BadParameter(str(exc)) from None
g = res["entry"]
typer.echo(f"{pkg}: now {path}" + (f" (program {g.get('exe')})" if g.get("kind") in ("rift", "linux") else ""))
if res.get("older"):
typer.echo("Heads-up: that APK is an older version than the one before.", err=True)
if res.get("different"):
typer.echo(f"Heads-up: {res.get('name')} looks like a different app than {g.get('title')}.", err=True)
if g.get("kind") == "rift" and g.get("exe_confirmed") is False:
typer.echo(f"More than one program could start it; FramePort picked {g.get('exe')}. Another one: "
f"frameport recipe {pkg} --exe <program>", err=True)
@app.command()
def patches():
"""List every available patch."""
@@ -709,6 +730,31 @@ def frame_trust_key(frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
typer.echo(f"connected: {info.get('hostname') or t.host} (new key saved)")
@frame_app.command("ssh-keys")
def frame_ssh_keys(add: list[str] = typer.Option([], "--add", help="a private key file to log in with too"),
remove: list[str] = typer.Option([], "--remove", help="stop using this key file (it stays)")):
"""Private SSH key files FramePort logs in with besides its own key (Settings → Installing → SSH keys): for a
Frame that accepts only your own key. The Frame connection and OpenSSH uploads both use them. Lists them."""
from .frame.connection import KeyFileError, add_extra_key, extra_key_status, remove_extra_key
failed = False
for path in remove:
typer.echo(f"removed {path}" if remove_extra_key(path) else f"not in the list: {path}")
for path in add:
try:
typer.echo(f"added {add_extra_key(path)}")
except KeyFileError as exc:
typer.echo(f"can't use {path}: {exc}", err=True)
failed = True
status = extra_key_status()
for path, problem in status:
typer.echo(f"{path}" + (f" (not usable: {problem})" if problem else ""))
if not status:
typer.echo("no extra keys: FramePort's own key and your SSH agent's keys only")
if failed:
raise typer.Exit(1)
@frame_app.command("usb-check")
def frame_usb_check(frame: Optional[str] = typer.Option(None, help=FRAME_HELP),
no_speed: bool = typer.Option(False, help="skip the upload speed test (2 × 128 MB)")):
@@ -970,134 +1016,5 @@ def _describe(exc: BaseException) -> str:
return explain(exc)
def _fex_target(frame: Optional[str]):
from . import fexrift
try:
fexrift.require_enabled()
except RuntimeError as e:
typer.echo(str(e), err=True)
raise typer.Exit(2) from None
return _target(frame)
@fex_app.command("status")
def fex_status(frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""What's set up on the Frame: GE-Proton, Meta's runtime, the login, the games in the prefix."""
t = _fex_target(frame)
typer.echo(json.dumps(t.frame.agent("fex_status", timeout=90), indent=1))
@fex_app.command("setup")
def fex_setup(frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""Upload FramePort's files, then the Frame downloads GE-Proton (x86_64) and Meta's runtime and builds the prefix
(10-20 minutes, about 12 GiB)."""
from . import fexrift
t = _fex_target(frame)
fexrift.setup(t.frame, printing_reporter(False))
typer.echo("setup done")
@fex_app.command("import-login")
def fex_import_login(prefix: str = typer.Argument(..., help="a Wine prefix on this PC where you signed in to Meta's "
"app (and downloaded the game with it)"),
app: Optional[list[str]] = typer.Option(None, "--app", help="Meta's name of a game to copy "
"(repeatable; default: the verified games)"),
frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""Copy your Meta login and the games Meta's app downloaded into the Frame's prefix (sign-in tokens: sent over
SSH, deleted on both sides afterwards)."""
from pathlib import Path
from . import fexrift
t = _fex_target(frame)
res = fexrift.import_login(t.frame, Path(prefix).expanduser(), printing_reporter(False), apps=app or None)
typer.echo(json.dumps(res.get("imported"), indent=1))
@fex_app.command("login")
def fex_login(start_now: bool = typer.Option(False, "--start-now", help="start Meta's app now instead of using Steam"),
timeout: int = typer.Option(900, min=1, max=86400, help="seconds to wait for sign-in"),
via_pc: bool = typer.Option(False, "--via-pc", help="use the PC browser and a temporary Oculus handler"),
stop: bool = typer.Option(False, "--stop", help="end sign-in and restore link handlers; keep the login"),
frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""Sign in with your Meta account in the Frame's shared Wine prefix."""
from . import fexlogin
t = _fex_target(frame)
fexlogin.login(t.frame, start_now=start_now, timeout=timeout, via_pc=via_pc, stop=stop, emit=typer.echo)
@fex_app.command("install")
def fex_install(app_name: Optional[str] = typer.Argument(None, metavar="APP",
help="Meta's name for the game (verified: oculus-first-contact)"),
from_library: Optional[str] = typer.Option(None, "--from-library", help="Rift library ID: rift.<slug>"),
folder: Optional[Path] = typer.Option(None, "--folder", help="upload an existing game folder unchanged"),
title: Optional[str] = typer.Option(None, "--title", help="title for a local game copy"),
app_id: Optional[str] = typer.Option(None, "--app-id", help="Meta app ID if no config/cached ID exists"),
dest: Optional[str] = typer.Option(None, "--dest", help="external drive mount point on the Frame"),
runtime_check: bool = typer.Option(False, "--runtime-check", help="probe Meta's library state (<=120 s)"),
msaa: Optional[int] = typer.Option(None, help="MSAA samples for a verified game that allows it (1, 2 "
"or 4; game default 4). UNVERIFIED: with 2 the game never "
"rendered in two launches"),
no_steam: bool = typer.Option(False, "--no-steam", help="don't add it to the Steam library"),
force_unverified: bool = typer.Option(False, "--force-unverified",
help="install a game that isn't verified with this mode "
"(only the generic fixes; may not start)"),
frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""Install a prefix game or upload a local Rift copy (fixes, launcher, shortcut). Without
--force-unverified an unverified game is refused with what the Frame's static checks found."""
from . import fexrift
t = _fex_target(frame)
if from_library or folder:
from . import fexinstall
res = fexinstall.install(t.frame, printing_reporter(False), from_library=from_library, folder=folder,
title=title, app=app_name, app_id=app_id, dest=dest, runtime_check=runtime_check,
msaa=msaa, add_to_steam=not no_steam, force_unverified=force_unverified)
else:
if title or app_id or dest:
raise typer.BadParameter("--title, --app-id and --dest require --from-library or --folder")
res = fexrift.install(t.frame, printing_reporter(False), app_name or "oculus-first-contact", msaa=msaa,
add_to_steam=not no_steam, force_unverified=force_unverified)
if runtime_check:
res["checks"] = dict(res.get("checks") or {}, **t.frame.agent(
"fex_runtime_state", app=app_name or "oculus-first-contact", timeout=125))
typer.echo(json.dumps(res, indent=1))
# ---------------------------------------------------------------------- FEX launch-time settings / bounded bench
@fex_app.command("settings")
def fex_settings(app_name: str = typer.Argument(..., metavar="APP"),
values: Optional[list[str]] = typer.Argument(None, metavar="KEY=VALUE"),
frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""Read per-game performance settings, or override them for the next launch (JSON values; null resets a key)."""
updates = {}
for item in values or []:
key, sep, raw = item.partition("=")
if not sep or not key:
raise typer.BadParameter("use key=value (true/false, numbers, null, or JSON for fex)")
try:
updates[key] = raw if key == "cores" and raw != "null" else json.loads(raw)
except ValueError:
updates[key] = raw # taskset's CPU list, e.g. cores=4-7
t = _fex_target(frame)
args = {"app": app_name}
if values:
args["values"] = updates
typer.echo(json.dumps(t.frame.agent("fex_settings", **args), indent=1))
@fex_app.command("bench")
def fex_bench(app_name: str = typer.Argument("oculus-first-contact", metavar="APP"),
seconds: int = typer.Option(120, min=1, max=120, help="total launch and sampling window (seconds)"),
frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""One bounded headless performance run on an idle Frame; stops the game and restores display power settings."""
t = _fex_target(frame)
typer.echo(json.dumps(t.frame.agent("fex_bench", app=app_name, seconds=seconds, timeout=seconds + 250),
separators=(",", ":")))
if __name__ == "__main__": # pragma: no cover
main()
-34
View File
@@ -289,40 +289,6 @@ def oculus_platform_dir() -> Path | None:
return None
def meta_libraries() -> list[Path]:
"""This PC's Meta Horizon / Oculus app libraries (folders holding Software/ and Manifests/): the default one under
Program Files and the extra ones the app registered (HKCU\\Software\\Oculus VR, LLC\\Oculus\\Libraries\\{id}
OriginalPath)."""
if not available():
return []
out: list[Path] = []
roots = [env_path("ProgramFiles"), env_path("ProgramW6432")] + ([Path("/mnt/c/Program Files")] if is_wsl() else [])
for root in [r for r in roots if r]:
for sub in ("Meta Horizon/Software", "Oculus/Software"):
out.append(root / sub)
key = r"HKCU\Software\Oculus VR, LLC\Oculus\Libraries"
try:
if is_windows():
import winreg
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key.partition("\\")[2]) as k:
for i in range(winreg.QueryInfoKey(k)[0]):
with winreg.OpenKey(k, winreg.EnumKey(k, i)) as sub:
out.append(Path(str(winreg.QueryValueEx(sub, "OriginalPath")[0])))
else:
r = run_win([system32("reg.exe"), "query", key, "/s", "/v", "OriginalPath"])
for m in re.finditer(r"^\s*OriginalPath\s+REG_\w+\s+(.+?)\s*$", r.stdout, re.M):
out.append(to_local(m[1]))
except (OSError, ValueError, subprocess.SubprocessError):
pass
seen, result = set(), []
for p in out:
if p not in seen and (p / "Manifests").is_dir():
seen.add(p)
result.append(p)
return result
# ------------------------------------------------------------------------------------------ firewall (pairing)
WSL_VM_CREATOR = "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" # Hyper-V firewall id of WSL's VM
-273
View File
@@ -1,273 +0,0 @@
"""Upload an existing Rift copy and register it with Meta's real runtime; no extraction or licence changes."""
from __future__ import annotations
import json
import os
import re
import shlex
import struct
import zlib
from pathlib import Path
from . import fexrift
from .analysis import rift, unreal_pak
from .core.events import Reporter
def skipped_file(name: str) -> bool:
name = name.replace("\\", "/").rsplit("/", 1)[-1].lower()
return (name.endswith((".7z", ".ag")) or bool(re.search(r"\.7z\.0", name))
or name in ("data.bin", "agrepackinstaller.exe", "vd.bat"))
def relative_file(name: str) -> str:
name = name.replace("\\", "/")
if (not name or name.startswith("/") or any(p in ("", ".", "..") for p in name.split("/"))
or any(c in name for c in ':\x00\r\n')):
raise ValueError(f"path must stay inside the game folder: {name!r}")
return name
def inventory(folder: Path) -> tuple[dict, list[str]]:
"""Stat only: hashing happens on the Frame, avoiding a second full read from slow source drives."""
files, skipped, seen = {}, [], set()
for root, dirs, names in os.walk(folder):
for name in dirs:
if (Path(root) / name).is_symlink():
raise ValueError("game folders must not contain directory symlinks")
for name in sorted(names):
path = Path(root) / name
rel = relative_file(path.relative_to(folder).as_posix())
if skipped_file(rel):
skipped.append(rel)
continue
if path.is_symlink():
raise ValueError(f"symlink in game folder: {rel}")
if not path.is_file():
raise ValueError(f"not a regular game file: {rel}")
if rel.casefold() in seen:
raise ValueError(f"duplicate Windows filename: {rel}")
seen.add(rel.casefold())
st = path.stat()
files[rel] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
return files, sorted(skipped)
def ini_app_id(text: str) -> str | None:
section = ""
values = {}
for line in text.splitlines():
line = line.strip()
if line.startswith("[") and line.endswith("]"):
section = line[1:-1].lower()
elif section == "onlinesubsystemoculus" and not line.startswith((";", "#")):
key, _, value = line.partition("=")
value = value.split(";", 1)[0].strip().strip('"\'')
if value.isdecimal() and int(value) > 0:
values[key.strip().lower()] = value
return next((values[k] for k in ("riftappid", "oculusappid", "appid") if k in values), None)
def config_app_id(folder: Path, files: dict) -> tuple[str | None, str | None]:
# Only unencrypted config entries are read. No archive extraction, guessing from binary strings or traversal
# into repack installers. Loose configs also cover Unity/custom engines using Oculus' common config names.
for rel in sorted(files):
if not rel.lower().endswith(".pak"):
continue
try:
ver, _, entries, names = unreal_pak.pak_entries(folder / rel)
for name, ent in entries.items():
if not name.lower().endswith("config/defaultengine.ini") or ent[2] > 4 << 20:
continue
value = ini_app_id(unreal_pak.pak_read(folder / rel, ver, ent, names).decode("utf-8-sig", "replace"))
if value:
return value, f"config:{rel}:{name}"
except (ValueError, OSError, struct.error, IndexError, zlib.error):
continue
for rel in sorted(files):
path = folder / rel
name = path.name.lower()
if files[rel]["size"] > 4 << 20:
continue
if name in ("defaultengine.ini", "oculus.ini", "oculusconfig.ini"):
value = ini_app_id(path.read_text("utf-8-sig", errors="replace"))
elif name in ("oculusconfig.json", "oculus-platform-config.json"):
try:
data = json.loads(path.read_text("utf-8-sig"))
value = next((str(data[k]) for k in ("RiftAppId", "OculusAppId", "AppId", "app_id")
if str(data.get(k, "")).isdecimal() and int(data[k]) > 0), None)
except (ValueError, TypeError, KeyError):
value = None
else:
continue
if value:
return value, f"config:{rel}"
return None, None
def exe_version(path: Path) -> str | None:
"""VS_FIXEDFILEINFO from the PE resource section, without reading a large executable a second time."""
try:
with path.open("rb") as f:
head = f.read(4096)
pe = struct.unpack_from("<I", head, 0x3c)[0]
if head[:2] != b"MZ" or head[pe:pe + 4] != b"PE\0\0":
return None
count = struct.unpack_from("<H", head, pe + 6)[0]
opt_size = struct.unpack_from("<H", head, pe + 20)[0]
f.seek(pe + 24 + opt_size)
sections = f.read(min(count, 96) * 40)
for off in range(0, len(sections), 40):
if sections[off:off + 8].rstrip(b"\0") != b".rsrc":
continue
size, raw = struct.unpack_from("<II", sections, off + 16)
f.seek(raw)
data = f.read(min(size, 32 << 20))
pos = data.find(struct.pack("<II", 0xfeef04bd, 0x10000))
if pos >= 0:
ms, ls = struct.unpack_from("<II", data, pos + 8)
return ".".join(str(v) for v in (ms >> 16, ms & 0xffff, ls >> 16, ls & 0xffff))
except (OSError, ValueError, struct.error, IndexError):
pass
return None
def meta_manifest(folder: Path) -> dict | None:
"""Meta's own manifest when the folder is in a Meta app library (<library>/Software/<name> next to
<library>/Manifests/<name>.json, e.g. C:\\Program Files\\Meta Horizon\\Software): its exe, launch arguments
(Unreal games need -vr), app ID and version beat anything guessed from the files."""
path = folder.parent.parent / "Manifests" / f"{folder.name}.json"
if folder.parent.name.lower() != "software" or not path.is_file():
return None
try:
m = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
if m.get("canonicalName") != folder.name or not m.get("launchFile") or not str(m.get("appId", "")).isdigit():
return None
return m
def library_manifest(app_id: str | None, canonical: str | None, exe: str) -> dict | None:
"""The same game's manifest in one of this PC's Meta app libraries (installed with the user's own account), for its
launch arguments: only when Meta's exe has the same file name as the one being installed (same game build)."""
from .core import winhost
for lib in winhost.meta_libraries():
for path in sorted((lib / "Manifests").glob("*.json")):
try:
m = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
continue
if not (str(m.get("appId")) == str(app_id) or (canonical and m.get("canonicalName") == canonical)):
continue
if Path(str(m.get("launchFile", "")).replace("\\", "/")).name.lower() == Path(exe).name.lower():
return m
return None
def source_info(folder: Path, entry: dict | None = None, title: str | None = None,
app: str | None = None, app_id: str | None = None) -> dict:
folder = folder.expanduser().resolve()
if not folder.is_dir():
raise ValueError(f"game folder not found: {folder}")
files, skipped = inventory(folder)
entry = entry or {}
extra = (entry.get("analysis") or {}).get("extra") or {}
meta = None if entry else meta_manifest(folder)
exe = entry.get("exe") or extra.get("exe") or (meta and meta["launchFile"].replace("\\", "/"))
if not exe:
analysis = rift.analyze(folder)
if not analysis.extra.get("exe_confirmed"):
raise ValueError("several game programs found; choose one in the FramePort library first")
extra = analysis.extra
exe = extra["exe"]
exe = relative_file(str(exe))
if exe not in files:
raise ValueError("the selected game program is missing or is a skipped repack file")
title = title or entry.get("title") or folder.name
canonical = (app or extra.get("canonical_name") or (meta and meta["canonicalName"])
or re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-"))
package = fexrift.package_for(canonical) # validate before any remote mutation
store_url = (entry.get("details") or {}).get("store_url") or ""
match = re.fullmatch(r"https://(?:www\.)?meta\.com/experiences/(\d+)/?", store_url)
store_id = match[1] if match else None
found, source = (str(meta["appId"]), "meta-manifest") if meta else config_app_id(folder, files)
if not found and store_id:
found, source = store_id, "oculusdb:details.store_url"
if not found and app_id:
if not re.fullmatch(r"[1-9][0-9]*", app_id):
raise ValueError("--app-id must be a positive numeric Meta app ID")
found, source = app_id, "cli:--app-id"
if not found:
raise ValueError("no Meta app ID in the game's config or cached store details; supply --app-id")
args = entry.get("launch_args", extra.get("launch_args", [])) or (shlex.split(meta.get("launchParameters") or "")
if meta else [])
if isinstance(args, str):
args = shlex.split(args)
if not args and not meta:
# Meta launches many Rift games with arguments (Unreal: -vr); a copy installed elsewhere has none of them
lib = library_manifest(found, canonical, exe)
if lib:
args = shlex.split(lib.get("launchParameters") or "")
version = re.search(r"(?i)(?<![a-z0-9])(?:v|version[ _-]*)?(\d+(?:\.\d+)+)", folder.name)
return {"folder": folder, "app": canonical, "package": entry.get("package") or package, "title": title,
"exe": exe, "args": args, "app_id": found, "app_id_source": source, "store_app_id": store_id,
"version": (meta and meta.get("version")) or (version[1] if version else exe_version(folder / exe))
or "0.0.0",
"files": files, "skipped": skipped}
def install(frame, reporter: Reporter, *, from_library: str | None = None, folder: Path | None = None,
title: str | None = None, app: str | None = None, app_id: str | None = None, dest: str | None = None,
msaa: int | None = None, add_to_steam: bool = True, force_unverified: bool = False,
runtime_check: bool = False) -> dict:
from .core import library
from .install import installer
fexrift.require_enabled()
if bool(from_library) == bool(folder):
raise ValueError("choose exactly one of --from-library or --folder")
entry = None
if from_library:
entry = library.load().get("games", {}).get(from_library)
if not entry or entry.get("kind") != "rift":
raise ValueError("--from-library needs a Rift library entry")
folder = Path(entry["game_dir"])
reporter.stage("Inspect local game files")
info = source_info(folder, entry, title, app, app_id)
if info["app"] not in fexrift.GAMES and not force_unverified:
raise ValueError("this game is unverified; use --force-unverified to upload and install it")
for rel in info["skipped"]:
reporter.log(f"Skipped repack leftover: {rel}")
reporter.check("Meta app ID", True, f"{info['app_id']} ({info['app_id_source']})")
reporter.check_cancel()
fexrift.sync_helpers(frame, reporter)
prep = frame.agent("fex_prepare_local", app=info["app"], package=info["package"], dest=dest,
files=info["files"])
items = [(info["folder"] / rel, rel, st["size"]) for rel, st in info["files"].items()
if prep["existing"].get(rel) != st["size"]]
need = sum(size for _, _, size in items)
if need > prep["free_bytes"] - (1 << 30):
raise RuntimeError("not enough space for the game + 1 GiB headroom")
reporter.stage(f"Upload {info['title']} ({need / 2**30:.1f} GiB remaining)")
with installer.transfer_link(frame, reporter, need) as xfer:
if items:
installer.upload_files(xfer, items, prep["game_dir"], reporter, max(need, 1))
reporter.check_cancel()
if inventory(info["folder"])[0] != info["files"]:
raise RuntimeError("source files changed during upload; retry with a stable game folder")
reporter.stage("Hash and register the game on the Frame")
metadata = {k: v for k, v in info.items() if k not in ("folder", "files")}
frame.agent("fex_register_local", timeout=7200, **metadata)
reporter.stage("Install launcher and generic fixes")
result = frame.agent("fex_install", package=info["package"], app=info["app"], title=info["title"],
source="local_copy", msaa=msaa, force_unverified=force_unverified)
if add_to_steam:
installer.add_to_steam(frame, [info["package"]], reporter)
if runtime_check:
result["checks"] = dict(result.get("checks") or {},
**frame.agent("fex_runtime_state", app=info["app"], timeout=125))
reporter.check("Meta library state", result["checks"].get("runtime_state") in ("ready", "installed"),
result["checks"].get("runtime_state", "unknown"))
return result
-190
View File
@@ -1,190 +0,0 @@
"""Interactive Meta sign-in on the Frame. Credential URLs travel in memory, over SSH stdin / a private callback.
There is intentionally no Reporter or app log in this module: external programs' exception strings and Meta's
Electron output can contain login URLs. Only fixed, friendly progress text reaches the CLI.
"""
from __future__ import annotations
import os
import queue
import secrets
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse
import webbrowser
from contextlib import contextmanager, nullcontext
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from . import fexrift, urlhandler
from .core import winhost
from .core.paths import user_data_dir
TITLE = "Meta sign-in (FramePort)"
def valid_callback(url):
if not isinstance(url, str) or len(url) > 65536 or any(ord(c) < 32 for c in url):
return False
try:
u = urllib.parse.urlsplit(url)
return (u.scheme, u.netloc, u.path) == ("oculus", "link", "/frl_login")
except ValueError:
return False
def open_page(url):
try:
u = urllib.parse.urlsplit(url)
if (u.scheme, u.netloc, u.path) != ("https", "auth.meta.com", "/native_sso/confirm"):
raise ValueError
if winhost.is_wsl():
# Start-Process on Windows, without interpolating the sign-in URL into PowerShell code or argv.
subprocess.run([winhost.system32("WindowsPowerShell/v1.0/powershell.exe"), "-NoProfile",
"-NonInteractive", "-Command", "Start-Process ([Console]::In.ReadToEnd())"],
input=url, text=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=15, check=True)
elif not webbrowser.open(url):
raise ValueError
except Exception:
raise RuntimeError("couldn't open Meta's sign-in page in the PC browser") from None
@contextmanager
def pc_callback():
"""The temporary scheme script POSTs straight into this loopback server, never to links/*.link.
A random endpoint and no CORS prevent arbitrary websites from posting callbacks. Handler errors and HTTP
request lines are deliberately never logged. Both the script and registration are removed in finally blocks.
"""
inbox = queue.Queue(maxsize=4)
endpoint = "/" + secrets.token_hex(24)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_POST(self):
try:
n = int(self.headers.get("Content-Length", "0"))
if self.path != endpoint or not 0 < n <= 65536:
self.send_error(400)
return
url = self.rfile.read(n).decode("utf-8")
if not valid_callback(url):
self.send_error(400)
return
inbox.put_nowait(url)
self.send_response(204)
self.end_headers()
except (ValueError, OSError, queue.Full):
self.send_error(400)
class Server(ThreadingHTTPServer):
def handle_error(self, *args):
pass
server = Server(("127.0.0.1", 0), Handler)
server.daemon_threads = True
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
address = f"http://127.0.0.1:{server.server_address[1]}{endpoint}"
user_data_dir().mkdir(parents=True, exist_ok=True)
try:
with tempfile.TemporaryDirectory(prefix="fex-login-", dir=user_data_dir()) as tmp:
kind = urlhandler.platform_kind()
if kind == "windows":
script = Path(tmp) / "callback.ps1"
script.write_text("param([string]$Link)\n$ErrorActionPreference='SilentlyContinue'\n"
f"try {{ Invoke-WebRequest -UseBasicParsing -Uri '{address}' -Method POST "
"-Body ([Text.Encoding]::UTF8.GetBytes($Link)) | Out-Null } catch {}\n")
ps = (Path(os.environ.get("SystemRoot", r"C:\Windows")) /
"System32/WindowsPowerShell/v1.0/powershell.exe")
command = f'"{ps}" -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "{script}" "%1"'
else:
script = Path(tmp) / "callback.py"
script.write_text("import sys,urllib.request\ntry:\n"
f" r=urllib.request.Request({address!r},data=sys.argv[1].encode(),method='POST')\n"
" urllib.request.urlopen(r,timeout=10).close()\nexcept Exception:\n pass\n")
if kind == "wsl":
distro = os.environ.get("WSL_DISTRO_NAME", "")
if not distro:
raise RuntimeError("WSL_DISTRO_NAME is needed for --via-pc")
command = (f'"C:\\Windows\\System32\\wsl.exe" -d "{distro}" -e '
f'python3 -I "{script}" "%1"')
else:
# Desktop Exec syntax uses double quotes, with literal percent signs escaped.
def dq(s):
s = str(s).replace("%", "%%")
for c in ("\\", '"', "`", "$"):
s = s.replace(c, "\\" + c)
return '"' + s.replace("\\", "\\\\") + '"' # Desktop string-value layer
command = f"{dq(sys.executable)} -I {dq(script)} %u"
with urlhandler.temporary_oculus_handler(command):
yield inbox
finally:
server.shutdown()
server.server_close()
worker.join(timeout=2)
def login(frame, *, start_now=False, timeout=900, via_pc=False, stop=False, emit=print):
fexrift.require_enabled()
if stop:
frame.agent("fex_login_cancel")
emit("Meta sign-in stopped. Your saved login stays on the Frame.")
return {"stopped": True}
if not 1 <= timeout <= 86400:
raise ValueError("sign-in timeout must be between 1 and 86400 seconds")
with pc_callback() if via_pc else nullcontext(None) as inbox:
try:
started = frame.agent("fex_login", start_now=start_now, via_pc=via_pc, login_timeout=timeout)
if started.get("package"):
from .core.events import Reporter
from .install import installer
result = installer.add_to_steam(frame, [started["package"]], Reporter())
if result.get("state") != "done" or result.get("errors"):
raise RuntimeError("Steam hasn't confirmed Meta sign-in; return to Gaming Mode and retry")
emit("Meta's app is starting on the Frame." if start_now else
f"Put on the headset: open '{TITLE}' in your Steam library.")
if via_pc:
emit("Complete the Meta sign-in page in this PC's browser.")
deadline = time.monotonic() + timeout
page_seen = callback_seen = False
while time.monotonic() < deadline:
st = frame.agent("fex_login_status", take_url=via_pc)
# Pop immediately, so even the local status variable never retains a login URL after opening it.
url = st.pop("open_url", None)
if url:
open_page(url)
url = None
if st.get("page_opened_at") and not page_seen:
emit("Sign-in page opened in the PC browser." if via_pc else "Sign-in page opened on the Frame.")
page_seen = True
if inbox is not None:
try:
link = inbox.get_nowait()
except queue.Empty:
pass
else:
try:
reply = frame.agent("fex_login_callback", url=link)
if not reply.get("delivered"):
raise RuntimeError("Meta's running app didn't accept the callback; retry sign-in")
finally:
link = None
if st.get("callback_received_at") and not callback_seen:
emit("Sign-in response reached Meta's app on the Frame.")
callback_seen = True
if st.get("signed_in"):
emit("Signed in.")
return {"signed_in": True}
time.sleep(3)
raise RuntimeError("Meta sign-in timed out; if the callback didn't reach the Frame, retry with --via-pc")
finally:
# Runs on success, Ctrl-C, timeout and partial setup errors; the broker also expires if SSH is lost.
frame.agent("fex_login_cancel")
-246
View File
@@ -1,246 +0,0 @@
"""Experimental: Oculus Rift games that need Meta's PC runtime, on the Steam Frame alone.
x86_64 GE-Proton under FEX runs Meta's runtime, Revive and the game in one Wine prefix on the Frame (research and
measurements: native/fexwine/README.md, CLAUDE.md "Rift via x86_64 Wine under FEX"). CLI only, behind
FRAMEPORT_EXPERIMENTAL_FEX=1 (`frameport fex ...`); verified game: Oculus First Contact.
Steps: setup (uploads agent/fexrift.py + artifacts/fexrift + a patched Revive 3.2.0, then the Frame downloads
GE-Proton and Meta's runtime itself) -> import-login (the Meta login and the games Meta's app downloaded, from a
signed-in Wine prefix on this PC) -> install (per-game fixes, launcher, Steam shortcut).
The login archive holds sign-in tokens: it is written owner-only, sent over SSH and deleted on both sides.
"""
from __future__ import annotations
import hashlib
import os
import re
import shutil
import tarfile
import time
from pathlib import Path
from .core.events import Reporter
from .core.paths import agent_dir, artifacts_dir, user_data_dir
EXPERIMENT_ENV = "FRAMEPORT_EXPERIMENTAL_FEX"
# Revive 3.2.0's LibRevive64.dll: the visibility fixes (IsVisible / HmdMounted / HasInputFocus always true: no pauses
# on the Frame's brief focus dips) and eye textures at 67 % of the recommended size (ovr_GetFovTextureSize divides by
# 1.5: the Frame's GPU can't fill the full size at 72 Hz). (file offset, original bytes, new bytes)
REVIVE_VERSION = "3.2.0"
REVIVE_DLL_SHA256 = "ef9ffd5342bb4afad9b1c0f4fee1ca3bf32f9d3159d49dd841cc9e22f02663e4"
REVIVE_PATCHES = [
(0x1008c, "740d", "9090"),
(0x122af, "15", "f1"),
(0x122b1, "04", "03"),
(0x151f8, "ff9030010000", "b00190909090"),
(0x1563a, "0f94c0", "b00190"),
(0x15807, "ff9230010000", "b00190909090"),
]
# games verified with this mode: Meta app name (folder under Software/Software) -> FramePort package + title
GAMES = {"oculus-first-contact": {"package": "rift.oculus_first_contact", "title": "Oculus First Contact"}}
# what a signed-in prefix contributes (relative to drive_c), tar top-level name -> path
META = "Program Files/Meta Horizon"
def enabled() -> bool:
return os.environ.get(EXPERIMENT_ENV) == "1"
def require_enabled() -> None:
if not enabled():
raise RuntimeError(f"Rift games with Meta's runtime on the Frame are experimental: set {EXPERIMENT_ENV}=1")
def artifact_files() -> list[tuple[Path, str]]:
"""(local file, path under the Frame's artifacts/) for everything fexrift.py needs, except Revive."""
root = artifacts_dir() / "fexrift"
out = [(p, p.relative_to(root).as_posix()) for p in sorted(root.rglob("*")) if p.is_file()]
# fexrift.py, its extension modules (fexrift_<area>.py) and per-game data; release bundles carry .txt copies of
# the .py files (their .py files are compiled away)
names = {p.name.removesuffix(".txt") for p in agent_dir().glob("fexrift*.py*") if p.suffix in (".py", ".txt")}
names |= {p.name for p in agent_dir().glob("fexrift*.json")}
for name in sorted(names):
src = agent_dir() / name
out.append((src if src.exists() else agent_dir() / f"{name}.txt", name))
return out
def patch_revive(src: Path, dest: Path) -> Path:
"""Copy Revive's runtime files to dest with REVIVE_PATCHES applied to LibRevive64.dll (Revive 3.2.0 only)."""
from .tools import revive as revive_tool
dll = src / "LibRevive64.dll"
if not dll.is_file() or hashlib.sha256(dll.read_bytes()).hexdigest() != REVIVE_DLL_SHA256:
raise RuntimeError(f"this mode needs Revive {REVIVE_VERSION} (its LibRevive64.dll is patched byte by byte); "
f"found another build in {src}")
tmp = dest.with_name(dest.name + ".tmp")
shutil.rmtree(tmp, ignore_errors=True)
for f in revive_tool.runtime_files(src):
target = tmp / f.relative_to(src)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(f, target) # content only: a system Revive's files are read-only
data = bytearray((tmp / "LibRevive64.dll").read_bytes())
for off, old, new in REVIVE_PATCHES:
o, n = bytes.fromhex(old), bytes.fromhex(new)
if bytes(data[off:off + len(o)]) != o:
raise RuntimeError(f"Revive {REVIVE_VERSION}: unexpected bytes at {off:#x}")
data[off:off + len(n)] = n
(tmp / "LibRevive64.dll").write_bytes(bytes(data))
shutil.rmtree(dest, ignore_errors=True)
tmp.replace(dest)
return dest
def sync_helpers(frame, reporter: Reporter) -> None:
"""Re-upload fexrift.py, its extension modules and per-game data (small) before work that runs them: only setup
uploaded them, so a fixed helper on the PC never reached a Frame set up earlier."""
from .install import installer
items = [(p, rel, p.stat().st_size) for p, rel in artifact_files() if rel.startswith("fexrift")]
installer.upload_files(frame, items, frame.agent("fex_prepare")["artifacts"], reporter,
max(sum(i[2] for i in items), 1))
def setup(frame, reporter: Reporter, wait: float = 3600) -> dict:
"""Upload fexrift.py, its binaries and the patched Revive, then run the setup on the Frame and follow it."""
from .install import installer
from .tools import revive as revive_tool
require_enabled()
reporter.stage("Prepare the Frame")
prep = frame.agent("fex_prepare")
if not prep.get("fex"):
raise RuntimeError("FEX isn't installed on the Frame (Steam app 3127680, installed with Proton for x86 games)")
if prep["free_bytes"] < 12 << 30:
raise RuntimeError(f"needs about 12 GiB free on the Frame, have {prep['free_bytes'] / 2**30:.1f} GiB")
src = revive_tool.revive_dir() or revive_tool.install()
revive = patch_revive(src, user_data_dir() / "fexrift" / "revive")
items = [(p, rel, p.stat().st_size) for p, rel in artifact_files()]
items += [(p, "revive/" + p.relative_to(revive).as_posix(), p.stat().st_size)
for p in sorted(revive.rglob("*")) if p.is_file()]
total = sum(i[2] for i in items)
reporter.stage(f"Upload FramePort's files ({len(items)} files, {total / 2**20:.0f} MiB)")
installer.upload_files(frame, items, prep["artifacts"], reporter, max(total, 1))
reporter.stage("Set up GE-Proton, FEX and Meta's runtime on the Frame (10-20 minutes)")
frame.agent("fex_setup")
end = time.time() + wait
last = None
while time.time() < end:
time.sleep(10)
try:
st = frame.agent("fex_status", timeout=90)
except Exception: # noqa: BLE001 - SSH hiccups while the Frame works hard
continue
setup_st = st.get("setup") or {}
if setup_st.get("step") != last and setup_st.get("step"):
last = setup_st["step"]
reporter.log(f"setup step: {last}")
if setup_st.get("state") == "failed":
raise RuntimeError(f"setup failed: {setup_st.get('error')}")
if setup_st.get("state") == "done":
for d in setup_st.get("done", []):
reporter.check(f"setup: {d['step']}", True, str(d.get("result")))
return st
raise RuntimeError("the setup on the Frame didn't finish in time; check again with `frameport fex status`")
def find_user_dir(prefix: Path) -> Path:
users = prefix / "drive_c" / "users"
for u in sorted(users.iterdir()) if users.is_dir() else []:
sessions = u / "AppData" / "Roaming" / "Oculus" / "sessions"
# signed in = sessions/<numeric Meta user id>-<n>/ (Meta's app creates sessions/_oaf without a sign-in)
if sessions.is_dir() and any(p.is_dir() and re.fullmatch(r"\d+(-\d+)*", p.name) for p in sessions.iterdir()):
return u
raise RuntimeError(f"no Meta login in {prefix} (sign in with Meta's app in that prefix first)")
def login_archive(prefix: Path, apps: list[str], out: Path) -> dict:
"""tar of the login (sessions/, CoreData/), the app manifests and the given apps, from a signed-in prefix."""
user = find_user_dir(prefix)
meta = prefix / "drive_c" / META
trees = {"sessions": user / "AppData" / "Roaming" / "Oculus" / "sessions", "CoreData": meta / "CoreData"}
for name, path in trees.items():
if not path.is_dir() or not any(path.iterdir()):
raise RuntimeError(f"{name} missing in {prefix}: sign in with Meta's app there first")
out.parent.mkdir(parents=True, exist_ok=True)
old_umask = os.umask(0o077)
apps_found = []
try:
with tarfile.open(out, "w") as t:
for name, path in trees.items():
t.add(path, arcname=name)
manifests = meta / "Software" / "Manifests"
for app in apps:
for f in sorted(manifests.glob(f"{app}.json*")) if manifests.is_dir() else []:
t.add(f, arcname=f"Manifests/{f.name}")
game = meta / "Software" / "Software" / app
if game.is_dir():
t.add(game, arcname=f"Software/{app}")
apps_found.append(app)
finally:
os.umask(old_umask)
return {"archive": out, "apps": apps_found, "bytes": out.stat().st_size}
def import_login(frame, prefix: Path, reporter: Reporter, apps: list[str] | None = None) -> dict:
require_enabled()
apps = apps or list(GAMES)
for app in apps:
package_for(app) # Meta's names only: they are globbed and become tar paths
tmp = user_data_dir() / "fexrift" / "login.tar"
try:
reporter.stage("Pack the Meta login")
info = login_archive(prefix, apps, tmp)
missing = [a for a in apps if a not in info["apps"]]
if missing:
reporter.check("Games from the prefix", None, f"not downloaded there: {', '.join(missing)}")
prep = frame.agent("fex_prepare")
reporter.stage(f"Send the login ({info['bytes'] / 2**20:.0f} MiB)")
frame.put(tmp, prep["incoming"] + "/login.tar", None)
res = frame.agent("fex_import_login", timeout=1200)
finally:
tmp.unlink(missing_ok=True)
reporter.check("Meta login on the Frame", bool((res.get("status") or {}).get("login")))
return res
def package_for(app: str) -> str:
"""FramePort package of a Meta app name (verified games keep theirs)."""
if app in GAMES:
return GAMES[app]["package"]
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]+", app):
raise ValueError(f"bad Meta app name {app!r}")
return "rift." + app.replace("-", "_")
def install(frame, reporter: Reporter, app: str = "oculus-first-contact", msaa: int | None = None,
add_to_steam: bool = True, force_unverified: bool = False) -> dict:
"""A game from the Frame's prefix as a Steam game. Games that aren't verified (GAMES) need force_unverified:
they get only the generic fixes the Frame finds in their binaries (the agent refuses otherwise and reports
its static checks)."""
from .install import installer
require_enabled()
pkg = package_for(app)
title = GAMES.get(app, {}).get("title")
reporter.stage(f"Install {title or app}")
sync_helpers(frame, reporter)
res = frame.agent("fex_install", package=pkg, app=app, title=title, msaa=msaa,
force_unverified=force_unverified)
for k, v in (res.get("fixes") or {}).items():
if v is not None:
reporter.check(f"fix: {k}", v not in ("unknown build",), str(v))
checks = res.get("checks") or {}
if not res.get("verified"):
reporter.check("Verified on the Frame", None, f"not yet: {app} gets only the generic fixes")
if checks.get("engine") == "unreal" and isinstance(checks.get("ime"), str):
reporter.check("Unreal IME fix", None, checks["ime"])
apis = checks.get("graphics_imports") or []
if apis and not {"d3d11", "vulkan"} & set(apis):
reporter.check("Graphics API", None, f"imports only {', '.join(apis)}: untested with this mode")
if add_to_steam:
installer.add_to_steam(frame, [pkg], reporter)
return res
+100 -4
View File
@@ -1,8 +1,8 @@
"""SSH connection to a Steam Frame and the remote agent protocol.
Authentication: FramePort's own keys first (<user data>/ssh/id_ed25519, installed by the bootstrap script, and
id_rsa, registered through Valve's devkit pairing, which only takes RSA keys), then the user's SSH agent/keys, then a
password if given.
id_rsa, registered through Valve's devkit pairing, which only takes RSA keys), then key files the user added in
Settings (EXTRA_KEYS_SETTING), then the user's SSH agent/keys, then a password if given.
"""
from __future__ import annotations
@@ -163,6 +163,96 @@ def app_keys() -> list[paramiko.PKey]:
return keys
EXTRA_KEYS_SETTING = "ssh.extra_keys" # library setting: private key files the user added (Settings → Installing)
class KeyFileError(ValueError):
"""A key file the user named can't be used (missing, not a private key, protected with a passphrase)."""
def load_key_file(path) -> paramiko.PKey:
"""A private key FramePort can log in with, or KeyFileError with a sentence saying why not."""
p = Path(path).expanduser()
if not p.is_file():
raise KeyFileError(f"{p}: file not found")
try:
return paramiko.PKey.from_path(p)
except (paramiko.SSHException, ValueError, OSError, UnicodeDecodeError, TypeError) as exc:
# paramiko says so with PasswordRequiredException (PEM) or a plain SSHException (OpenSSH format)
if isinstance(exc, paramiko.PasswordRequiredException) or "password" in str(exc).lower():
raise KeyFileError(f"{p.name} is protected with a passphrase, which FramePort can't ask for: add the "
"key to your SSH agent instead (FramePort also logs in with the agent's keys)") from None
raise KeyFileError(f"{p.name} isn't a private SSH key FramePort can read "
f"(OpenSSH or PEM format; a .pub file is the public half): {exc}") from None
def extra_key_paths() -> list[Path]:
"""The key files from Settings, as stored (each may be missing or unreadable by now: see extra_keys)."""
try:
from ..core import library
stored = library.peek_setting(EXTRA_KEYS_SETTING, [])
except Exception: # noqa: BLE001 - no library yet
return []
if isinstance(stored, str):
stored = [stored]
paths: list[Path] = []
for value in stored if isinstance(stored, list) else []:
if isinstance(value, str) and value.strip():
p = Path(value.strip()).expanduser()
if p not in paths:
paths.append(p)
return paths
def add_extra_key(path) -> Path:
"""Check a key file (KeyFileError if FramePort can't use it) and add it to Settings. Returns the stored path."""
p = Path(path).expanduser()
if p.name.endswith(".pub") and p.with_name(p.name[:-4]).is_file():
raise KeyFileError(f"{p.name} is the public half: pick {p.name[:-4]} (the file without .pub) instead")
load_key_file(p)
p = p.resolve()
from ..core import library
library.update_setting(EXTRA_KEYS_SETTING, lambda old: [v for v in (old if isinstance(old, list) else [])
if Path(v).expanduser() != p] + [str(p)], [])
return p
def remove_extra_key(path) -> bool:
"""Take a key file out of Settings (the file itself stays). False if it wasn't there."""
from ..core import library
p = Path(path).expanduser()
before = extra_key_paths()
library.update_setting(EXTRA_KEYS_SETTING, lambda old: [v for v in (old if isinstance(old, list) else [])
if Path(v).expanduser() != p], [])
return p in before
def extra_key_status() -> list[tuple[Path, str]]:
"""Each key file from Settings with "" when usable, else why not (for Settings and the CLI)."""
status = []
for path in extra_key_paths():
try:
load_key_file(path)
status.append((path, ""))
except KeyFileError as exc:
status.append((path, str(exc)))
return status
def extra_keys() -> list[tuple[Path, paramiko.PKey]]:
"""The usable keys from Settings; unusable ones are logged and skipped (a login still tries the others)."""
keys = []
for path in extra_key_paths():
try:
keys.append((path, load_key_file(path)))
except KeyFileError as exc:
log.warning("SSH key from Settings skipped: %s", exc)
return keys
@dataclass
class FrameTarget:
host: str
@@ -409,6 +499,10 @@ class Frame:
_video_codec_digest: str = "" # "<manifest digest>:<on|off>" handled on this connection (incl. a failed install)
_video_codec_lock: threading.Lock = field(default_factory=threading.Lock)
home: str = ""
# how the last login worked: "app_key" (FramePort's own key), "user_key" (a key file from Settings),
# "agent" (this PC's SSH agent / ~/.ssh keys) or "password"; OpenSSH uploads follow it (native_upload)
auth: str = ""
openssh_relaxed: bool | None = None # native_upload: True once OpenSSH needed this PC's own keys/agent
# ------------------------------------------------------------------ connect
def connect(self, timeout: float = 10) -> Frame:
@@ -459,7 +553,8 @@ class Frame:
kwargs = dict(hostname=self.target.host, port=self.target.port, username=self.target.user, timeout=timeout,
banner_timeout=timeout, auth_timeout=timeout)
errors = []
attempts = [("app_key", k) for k in app_keys()] + [("agent", None), ("password", None)]
attempts = ([("app_key", k) for k in app_keys()] + [("user_key", k) for _, k in extra_keys()]
+ [("agent", None), ("password", None)])
for attempt, pkey in attempts:
if attempt == "password" and not self.password:
continue
@@ -467,7 +562,7 @@ class Frame:
client.load_host_keys(str(known))
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # trust on first use (pairing)
try:
if attempt == "app_key":
if attempt in ("app_key", "user_key"):
client.connect(pkey=pkey, allow_agent=False, look_for_keys=False, **kwargs)
elif attempt == "agent":
client.connect(allow_agent=True, look_for_keys=True, **kwargs)
@@ -492,6 +587,7 @@ class Frame:
raise
else:
raise FrameNotPaired(bool(self.password), errors)
self.auth = attempt
client.save_host_keys(str(known))
transport = client.get_transport()
transport.set_keepalive(15)
+156 -29
View File
@@ -2,10 +2,9 @@
from __future__ import annotations
import contextlib
import csv
import io
import os
import posixpath
import re
import shutil
import signal
import subprocess
@@ -13,19 +12,30 @@ import tarfile
import tempfile
import threading
import time
from pathlib import Path
from pathlib import Path, PureWindowsPath
from .connection import sh_quote, ssh_dir
from .connection import extra_keys, sh_quote, ssh_dir
def quote(value) -> str:
def quote(value, windows=False) -> str:
"""One sftp batch argument, taken literally.
Inside double quotes sftp escapes glob characters (* ? [) itself and undoes that for put's destination, so
they must NOT be escaped again: an extra backslash became part of the name (GitHub #324: "[ENG]" in a folder
name made every OpenSSH upload fail, on Linux too). Only backslash and the quote are escaped. ``windows``: a
local Windows path goes with forward slashes; Win32-OpenSSH's sftp turns every backslash of a local path into
'/', escapes included ("C:\\\\Users" → "C://Users").
"""
value = str(value)
if any(c in value for c in "\r\n\x00"):
raise ValueError("SFTP paths cannot contain newlines or NUL")
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
for char in "*?[":
escaped = escaped.replace(char, "\\" + char)
return '"' + escaped + '"'
if windows:
value = PureWindowsPath(value).as_posix()
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def quote_local(path) -> str:
return quote(path, windows=os.name == "nt")
def size_of(sftp, path):
@@ -35,27 +45,74 @@ def size_of(sftp, path):
return 0
def key_files(relaxed=False) -> list[Path]:
"""The private keys OpenSSH offers: FramePort's own (<data>/ssh) and the usable key files from Settings;
``relaxed`` also this PC's default keys (default_key_files)."""
keys = [ssh_dir() / name for name in ("id_ed25519", "id_rsa") if (ssh_dir() / name).exists()]
for path in [path for path, _ in extra_keys()] + (default_key_files() if relaxed else []):
if path not in keys:
keys.append(path)
return keys
def default_key_files() -> list[Path]:
"""This PC's own keys that Paramiko's "agent" login tries (look_for_keys: ~/.ssh/id_rsa, id_dsa, id_ecdsa,
id_ed25519; on Windows ~/ssh too), usable without a passphrase. OpenSSH needs them named: it skips its default
keys as soon as one -i is given, and Windows OpenSSH refuses a key file others can read (a private copy can't
be refused)."""
from .connection import KeyFileError, load_key_file
folders = [Path.home() / ".ssh"] + ([Path.home() / "ssh"] if os.name == "nt" else [])
found = []
for folder in folders:
for name in ("id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"):
path = folder / name
if not path.is_file():
continue
try:
load_key_file(path)
except KeyFileError:
continue # passphrase-protected or not a key: only the agent can use it
found.append(path)
return found
def current_sid() -> str:
"""This Windows account's SID. whoami prints in the console code page: read bytes, so a user name with
accents can't break decoding (only the ASCII SID is used)."""
out = subprocess.check_output(["whoami", "/user", "/fo", "csv", "/nh"], **hidden())
match = re.search(rb"S-1-[0-9]+(?:-[0-9]+)+", out)
if not match:
raise OSError("cannot find this Windows account's SID for the key copies' permissions")
return match.group().decode()
@contextlib.contextmanager
def credentials(frame, port_flag="-P"):
"""Private temporary copies avoid modifying pairing keys, including their Windows ACLs."""
key_paths = [ssh_dir() / name for name in ("id_ed25519", "id_rsa") if (ssh_dir() / name).exists()]
if not key_paths:
def credentials(frame, port_flag="-P", relaxed=False):
"""OpenSSH arguments that log in like the Frame connection and trust only the host key it pinned.
Keys are offered as private temporary copies (that avoids modifying pairing keys, including their Windows
ACLs; Windows OpenSSH refuses key files others can read). Strict (default): FramePort's keys and the key
files from Settings only (IdentitiesOnly). ``relaxed``: also this PC's default ~/.ssh keys and SSH agent, the
way Paramiko's "agent" login does (GitHub #242: a Frame that only authorizes the user's own key). Verbose
(-v), so a refused login can say which keys were offered (failure()).
"""
key_paths = key_files(relaxed)
if not key_paths and not relaxed:
raise OSError("no FramePort key available for OpenSSH")
key = frame.client.get_transport().get_remote_server_key()
with tempfile.TemporaryDirectory(prefix="frameport-upload-") as directory:
directory = Path(directory)
sid = None
if os.name == "nt":
row = next(csv.reader(io.StringIO(subprocess.check_output(
["whoami", "/user", "/fo", "csv", "/nh"], text=True, **hidden()))))
sid = row[-1]
sid = current_sid()
subprocess.run(["icacls", str(directory), "/inheritance:r", "/grant:r", f"*{sid}:(OI)(CI)F"],
check=True, stdout=subprocess.DEVNULL, **hidden())
else:
directory.chmod(0o700)
copies = []
for path in key_paths:
copy = directory / path.name
for n, path in enumerate(key_paths):
copy = directory / f"key{n}" # own names: a key from Settings may be called id_ed25519 too
shutil.copyfile(path, copy)
if sid:
subprocess.run(["icacls", str(copy), "/inheritance:r", "/remove:g", "*S-1-3-4",
@@ -66,13 +123,72 @@ def credentials(frame, port_flag="-P"):
known = directory / "known_hosts"
host = frame.target.host if frame.target.port == 22 else f"[{frame.target.host}]:{frame.target.port}"
known.write_text(f"{host} {key.get_name()} {key.get_base64()}\n")
yield ["-F", os.devnull, *copies, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
yield ["-F", os.devnull, "-v", *copies, "-o", "BatchMode=yes",
*([] if relaxed else ["-o", "IdentitiesOnly=yes"]),
"-o", "StrictHostKeyChecking=yes", "-o", f'UserKnownHostsFile="{known.as_posix()}"',
"-o", f"GlobalKnownHostsFile={os.devnull}", "-o", "ConnectTimeout=10",
"-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=3",
port_flag, str(frame.target.port)]
class OpenSSHAuthFailed(OSError):
"""OpenSSH reached the Frame but the login was refused (the keys it offered aren't authorized there)."""
AUTH_REFUSED = ("Permission denied (", "Too many authentication failures", "No more authentication methods")
# debug lines (-v) worth keeping: which keys were found, offered, refused or unreadable
AUTH_DEBUG = ("identity file", "Offering public key", "Server accepts key", "Will attempt key",
"Authentications that can continue", "Authenticated to", "Load key", "no such identity",
"Skipping", "agent", "Next authentication method")
def failure(what: str, code, stderr: bytes) -> OSError:
"""The error for a failed OpenSSH run: OpenSSH's own messages (all non-debug lines: warnings such as
"UNPROTECTED PRIVATE KEY FILE" included) plus the -v lines about keys; OpenSSHAuthFailed for a refused login."""
text = stderr.decode(errors="replace").replace("\r\n", "\n")
lines = [line for line in text.splitlines() if line.strip() and (
not line.startswith("debug") or any(k in line for k in AUTH_DEBUG))]
detail = "\n".join(lines)
if len(detail) > 4000:
detail = "…" + detail[-4000:]
refused = code == 255 and any(marker in text for marker in AUTH_REFUSED)
return (OpenSSHAuthFailed if refused else OSError)(f"{what} failed ({code}): {detail}")
def login_modes(frame) -> list[bool]:
"""How OpenSSH logs in, in order (False = FramePort's keys only, True = also this PC's keys and agent).
A Frame connection that logged in with this PC's own keys/agent (Paramiko's "agent" attempt) goes straight to
relaxed: FramePort's key isn't authorized there. Else strict first, relaxed once more after a refused login.
A mode that worked is kept for the rest of the connection. FramePort doesn't add its key to the Frame for
this: it only does that after a password login, where the user typed the Frame's password for it."""
known = getattr(frame, "openssh_relaxed", None)
if known is not None:
return [bool(known)]
if getattr(frame, "auth", "") == "agent":
return [True]
return [False, True]
def with_login_modes(frame, reporter, run):
"""run(relaxed) in each login mode until one isn't refused (see login_modes)."""
modes = login_modes(frame)
if modes == [True] and getattr(frame, "openssh_relaxed", None) is None:
reporter.log("the Frame connection logged in with this PC's own SSH keys or agent: OpenSSH uses them too")
for n, relaxed in enumerate(modes):
try:
result = run(relaxed)
except OpenSSHAuthFailed as exc:
if n == len(modes) - 1:
raise
reporter.log(f"OpenSSH login with FramePort's SSH keys was refused; trying this PC's own SSH keys and "
f"agent too. {exc}")
continue
with contextlib.suppress(AttributeError):
frame.openssh_relaxed = relaxed
return result
def hidden():
return {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}
@@ -99,6 +215,11 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
Only successful batches are promoted, after every process has exited successfully. All control operations
happen in the supervising thread, so Paramiko's SFTP client is never shared across threads.
"""
return with_login_modes(frame, reporter, lambda relaxed: _upload(
frame, items, remote_root, reporter, total, sent, workers, relaxed))
def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
executable = shutil.which("sftp")
if not executable:
raise OSError("system OpenSSH SFTP is unavailable")
@@ -111,7 +232,7 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
sizes, offsets, progress = {}, {}, {}
for path, rel, size in sorted(items, key=lambda item: item[2], reverse=True):
remote = posixpath.join(remote_root, rel)
quote(path)
quote_local(path)
quote(remote)
offset = size_of(frame.sftp, remote + ".part")
if offset > size:
@@ -127,7 +248,7 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
speed = Speed(total - sent - sum(offsets.values()))
reporter.log(f"uploading large files with OpenSSH SFTP ({len(groups)} workers)")
setup_started = time.monotonic()
with credentials(frame) as args, contextlib.ExitStack() as stack:
with credentials(frame, relaxed=relaxed) as args, contextlib.ExitStack() as stack:
monitor = stack.enter_context(frame.client.open_sftp())
monitor.get_channel().settimeout(2)
reporter.log(f"OpenSSH credentials and progress connection ready in {time.monotonic() - setup_started:.2f}s")
@@ -139,7 +260,7 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
for path, rel, _ in group:
remote = posixpath.join(remote_root, rel) + ".part"
command = "reput" if offsets[rel] else "put"
batch.write(f"{command} {quote(path)} {quote(remote)}\n".encode())
batch.write(f"{command} {quote_local(path)} {quote(remote)}\n".encode())
batch.seek(0)
errors = stack.enter_context(tempfile.TemporaryFile())
process = subprocess.Popen([executable, *args, "-b", "-",
@@ -152,8 +273,7 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
for process, errors in processes:
if process.poll() not in (None, 0):
errors.seek(0)
detail = errors.read().decode(errors="replace")[-1500:]
raise OSError(f"OpenSSH SFTP failed ({process.returncode}): {detail}")
raise failure("OpenSSH SFTP", process.returncode, errors.read())
for rel, size in sizes.items():
reporter.check_cancel()
progress[rel] = max(progress[rel], min(size, size_of(
@@ -187,11 +307,16 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
def put_tar(frame, files, remote_root, reporter, progress):
"""Stream a tar batch over paired OpenSSH; supervise writes so Cancel also stops a blocked pipe."""
return with_login_modes(frame, reporter,
lambda relaxed: _put_tar(frame, files, remote_root, reporter, progress, relaxed))
def _put_tar(frame, files, remote_root, reporter, progress, relaxed):
executable = shutil.which("ssh")
if not executable:
raise OSError("system OpenSSH SSH is unavailable")
reporter.check_cancel()
with credentials(frame, port_flag="-p") as args, tempfile.TemporaryFile() as errors:
with credentials(frame, port_flag="-p", relaxed=relaxed) as args, tempfile.TemporaryFile() as errors:
command = f"mkdir -p {sh_quote(remote_root)} && tar -xf - -C {sh_quote(remote_root)}"
process = subprocess.Popen([executable, *args, f"{frame.target.user}@{frame.target.host}", command],
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=errors,
@@ -222,12 +347,14 @@ def put_tar(frame, files, remote_root, reporter, progress):
if not writer.is_alive() and process.poll() is None:
time.sleep(0.1)
reporter.check_cancel()
if failures and process.poll() is None: # a refused login shows as a broken pipe first
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=2)
if process.poll() not in (None, 0):
errors.seek(0)
raise failure("OpenSSH tar", process.returncode, errors.read())
if failures:
raise failures[0]
if process.poll() != 0:
errors.seek(0)
raise OSError(f"OpenSSH tar failed ({process.returncode}): "
+ errors.read().decode(errors="replace")[-1500:])
finally:
stop_process(process)
writer.join()
+31 -4
View File
@@ -220,6 +220,28 @@ class PcvrPlan:
art_lookup: str | None = None # package whose store art to use
dest: str | None = None
overlay: dict | None = None # a SteamVR overlay app: the agent's overlay argument (analysis/vroverlay.py)
source_id: str | None = None # which version of the game folder (GitHub #161: a newer one was added)
changed_since: float | None = None # a newer version: game files changed after this are sent again (see below)
def changed_since(path: Path, since: float | None) -> bool:
"""A newer version of a Linux app / PC VR game (GitHub #161): uploads skip files the Frame has with the same
size, so a changed file of the same size would stay old. Files written (or unpacked: ctime) after the last
install are sent again; since=None (no newer version) never, 0 (last install unknown) always."""
if since is None:
return False
try:
st = path.stat()
except OSError:
return True
return max(st.st_mtime, st.st_ctime) > since
def _recipe_record(recipe: dict | None, source_id: str | None) -> dict | None:
"""The deployment's recipe record, with the source version it was installed from (ui.components.source_replaced)."""
if not source_id:
return recipe
return {**(recipe or {}), "source_id": source_id}
def install_pcvr(frame: Frame, plan: PcvrPlan, reporter: Reporter) -> dict:
@@ -259,7 +281,8 @@ def install_pcvr(frame: Frame, plan: PcvrPlan, reporter: Reporter) -> dict:
manifests["helpers"] = {p.name: p.stat().st_size for p in sorted(helpers.iterdir()) if p.is_file()}
sources["helpers"] = helpers
to_send = [(t, rel) for t, m in manifests.items() for rel, size in m.items()
if prep["existing"].get(t, {}).get(rel) != size]
if prep["existing"].get(t, {}).get(rel) != size
or t == "game" and changed_since(plan.game_dir / rel, plan.changed_since)]
need = sum(manifests[t][rel] for t, rel in to_send)
if need > prep["free_bytes"] - (1 << 30):
raise RuntimeError(f"not enough space on the Frame: need {need / 2**30:.1f} GiB + 1 GiB headroom, "
@@ -290,7 +313,8 @@ def install_pcvr(frame: Frame, plan: PcvrPlan, reporter: Reporter) -> dict:
game_args=game_args(plan.recipe), no_crash_reporter="pcvr.no_crash_reporter" in plan.recipe.patches,
libovr_redirect="pcvr.libovr_redirect" in plan.recipe.patches,
exe_sha256=plan.exe_sha256, revive_version=plan.revive_version, vr=not is_flat_windows(plan.package),
recipe={"patches": sorted(plan.recipe.patches), "source": plan.recipe.source}, overlay=plan.overlay,
recipe=_recipe_record({"patches": sorted(plan.recipe.patches), "source": plan.recipe.source}, plan.source_id),
overlay=plan.overlay,
)
reporter.log(f"installed at {result['base']} (Proton {result['proton']}, Steam shortcut id {result['appid']})")
log_overlay(result.get("overlay"), reporter)
@@ -325,6 +349,8 @@ class LinuxPlan:
desktop_entry: bool = True # an entry in Desktop Mode's menu and on its desktop (GitHub #84)
desktop_icon: bool = True # with it, a copy on Desktop Mode's desktop (GitHub #212)
overlay: dict | None = None # a SteamVR overlay app: the agent's overlay argument (analysis/vroverlay.py)
source_id: str | None = None # which version of the app (GitHub #161: a newer one was added)
changed_since: float | None = None # a newer version: files changed after this are sent again
def install_linux(frame: Frame, plan: LinuxPlan, reporter: Reporter) -> dict:
@@ -339,7 +365,8 @@ def install_linux(frame: Frame, plan: LinuxPlan, reporter: Reporter) -> dict:
else:
manifest = local_data_manifest(plan.root)
manifest = {k: v for k, v in manifest.items() if not k.startswith(".unpacked")}
to_send = [rel for rel, size in manifest.items() if prep["existing"].get("app", {}).get(rel) != size]
to_send = [rel for rel, size in manifest.items() if prep["existing"].get("app", {}).get(rel) != size
or changed_since(plan.root / rel, plan.changed_since)]
need = sum(manifest[rel] for rel in to_send)
if need > prep["free_bytes"] - (1 << 30):
raise RuntimeError(f"not enough space on the Frame: need {need / 2**30:.1f} GiB + 1 GiB headroom, "
@@ -358,7 +385,7 @@ def install_linux(frame: Frame, plan: LinuxPlan, reporter: Reporter) -> dict:
appimage=plan.appimage, openxr=plan.openxr, x86_64=plan.x86_64, manifests={"app": manifest},
executables=executables, tags=_tags(plan.package), dest=plan.dest,
desktop_entry=plan.desktop_entry, desktop_icon=plan.desktop_icon, overlay=plan.overlay,
timeout=900)
recipe=_recipe_record(None, plan.source_id), timeout=900)
reporter.log(f"installed at {result['base']} (Steam shortcut id {result['appid']})")
log_overlay(result.get("overlay"), reporter)
apply_app_icon(frame, plan.package, prep.get("anchor"), result, reporter)
+16
View File
@@ -94,6 +94,7 @@
"AC Nexus: no AppSW at 72 Hz": "",
"AC Nexus: no AppSW at 90 Hz": "",
"Activity": "",
"Add a key file…": "",
"Add a Linux app folder…": "",
"Add a Linux app…": "",
"Add a PC game folder…": "",
@@ -557,6 +558,7 @@
"Frame OpenXR compatibility layer": "",
"FrameBridge OpenXR adapter": "",
"FramePort": "",
"FramePort also logs in with {name} from the next connection.": "",
"FramePort can't update itself in {value} (no permission) — opening the release page to download it": "",
"FramePort changelog": "",
"FramePort checks GitHub for a new version every few hours. Update now downloads and checks it, then restarts FramePort; your games and settings stay.": "",
@@ -568,6 +570,7 @@
"FramePort isn't sure which program starts this game. Open the game and use … → Change program… to pick it.": "",
"FramePort keeps its own copies; nothing is installed system-wide": "",
"FramePort live view": "",
"FramePort logs in to the Frame with its own key. If your Frame accepts only one of your own keys, add that private key file here; fast uploads use it too. A key with a passphrase: add it to your SSH agent instead.": "",
"FramePort looked at your last session of {n} game and has something to try.": [
"",
""
@@ -664,6 +667,7 @@
"Hardware video decoding (H.264, HEVC, VP9)": "",
"Hardware video decoding on the Frame": "",
"Heads-up: that APK is an older version than the one before.": "",
"Heads-up: {name} looks like a different app than {title}.": "",
"headset found": "",
"Hi there!": "",
"Hide Android's navigation bar": "",
@@ -941,6 +945,8 @@
"New recipe applied. Click Update on Frame to install it.": "",
"Newer APK for {title}": "",
"Newer APK of {title}": "",
"Newer version for {title}": "",
"Newer version of {title}": "",
"Next": "",
"Nice, it works! FramePort receives install links. (Demo: nothing was installed.)": "",
"No": "",
@@ -1026,6 +1032,7 @@
"On your Frame": "",
"on: {names}": "",
"One PC game folder": "",
"Only FramePort's own key, and your SSH agent's keys.": "",
"Only if 360° pictures show wrongly.": "",
"Only if 360° pictures show wrongly: 1 = upside down, 2 = mirrored, 4 = turned around (add values to combine).": "",
"Only install software from sites you trust. FramePort downloads it from {host} and installs it on your Frame.": "",
@@ -1138,6 +1145,7 @@
"Pretty smooth": "",
"Prevents a start-up crash in some Unreal games.": "",
"Previous": "",
"Private SSH key file (not the .pub file)": "",
"Problems and feedback": "",
"Processes": "",
"Processor": "",
@@ -1173,6 +1181,7 @@
"Reading the file list from the Frame…": "",
"Reading the install link": "",
"Reading the new APK": "",
"Reading the new version": "",
"ready": "",
"Ready": "",
"Ready to play": "",
@@ -1412,6 +1421,7 @@
"Sound on": "",
"Source": "",
"square, 256 × 256": "",
"SSH keys": "",
"Stable (default)": "",
"Stand in for cube layers": "",
"Standard for every game": "",
@@ -1462,6 +1472,7 @@
"Stereo (3D) 360° layers: 0 = as the game sends them, 2 = flat (the left image to both eyes).": "",
"Stop": "",
"Stop objects popping in and out": "",
"Stop using this key (the file stays)": "",
"Stopped: {why}": "",
"Stops a black picture in Minecraft launchers (for example QuestCraft).": "",
"Stops a crash a few seconds after start in some Unreal games with anti-aliasing (for example Star Wars Pinball VR).": "",
@@ -1513,6 +1524,7 @@
"Test Proton on the Frame": "",
"Text and layout size": "",
"That APK is a different app, not {title}.": "",
"That key can't be used: {error}": "",
"That theme file can't be used: {error}": "",
"That's me!": "",
"The APK file is damaged or incomplete. Get the game again and rescan the folder.": "",
@@ -1597,6 +1609,7 @@
"This Frame's SSH key changed since FramePort last connected (SteamOS was reset, or another device now has its address). If it's your Frame, choose Trust the new key on the Steam Frame page.": "",
"This game can't run on the Steam Frame.": "",
"This game is marked \"Can't run\" on the Steam Frame:": "",
"This is a Google {platform} VR build. Its VR can't reach the Frame's headset, so it runs as a flat window at best, usually without working controls. An Oculus build of the game (Meta Quest, Oculus Go or Gear VR) works the normal way.": "",
"This is a website in an app: it opens in Meta's browser, which the Frame doesn't have. If nothing opens, visit the website in a browser.": "",
"This is the example button from frameport.app. Real buttons install real games.": "",
"this PC": "",
@@ -1711,6 +1724,7 @@
"Update the app only?": "",
"Update tools": "",
"Update with a newer APK…": "",
"Update with a newer version…": "",
"Updates": "",
"Updates every game marked \"Update ready\", one after another.": "",
"Updates the game, frame rate and battery every 5 seconds. Turn off to save the Frame's power.": "",
@@ -1971,6 +1985,8 @@
"{title}: name updated in Steam": "",
"{title}: newer APK added": "",
"{title}: newer APK added. Press Update on Frame to install it.": "",
"{title}: newer version added": "",
"{title}: newer version added. Press Update to install it.": "",
"{title}: ready": "",
"{title}: Steam artwork updated on the Frame": "",
"{title}: {line}": "",
@@ -112,6 +112,7 @@ class UnityOculusCheck(Patch):
return a.engine == "Unity" and "libOVRPlugin.so" in a.libs and bool((a.extra or {}).get("unity_oculus_check"))
def detect(self, a):
# not narrowed by libOculusXRPlugin.so: a verified game ships it and still needs this fix
if self.applies(a):
return Suggestion(True, "Unity with built-in Oculus support: it checks for Meta's system apps before "
"starting VR, else it runs as a 2D app (for example Accounting+, BattleSisters).")
+3 -2
View File
@@ -12,7 +12,7 @@ frame.unity_text_input).
from __future__ import annotations
from ..base import Suggestion, register
from .unity_text_input import RET_FALSE, Il2cppReturnPatch
from .unity_text_input import RET_FALSE, Il2cppReturnPatch, can_rewrite_il2cpp
RET_ZERO = RET_FALSE # mov w0, #0 ; ret
@@ -40,7 +40,8 @@ class UnityRuntimeMsaa(Il2cppReturnPatch):
return a.engine == "Unity" and "libil2cpp.so" in a.libs and not a.only_32bit
def detect(self, a):
if self.applies(a) and (a.extra or {}).get("ovr_runtime_msaa") and "GLES" in a.graphics:
if (self.applies(a) and can_rewrite_il2cpp(a)
and (a.extra or {}).get("ovr_runtime_msaa") and "GLES" in a.graphics):
return Suggestion(True, "GLES Unity game whose OVRManager turns 4x MSAA on at runtime: multisampled "
"render-to-texture can hang the Frame's GPU.")
return None
@@ -85,6 +85,19 @@ def patch_field_loads(lib: bytes, method: tuple[int, int], field_offset: int, va
ALL_TARGETS: dict[str, list[str]] = {} # every IL2CPP patch's methods: one Cpp2IL run (and cache entry) serves all
def can_rewrite_il2cpp(a) -> bool:
"""Automatic return patches need AArch64 code and metadata Cpp2IL can read.
Unity 2017's metadata is unreadable by our Cpp2IL workflow (AGENTS.md, Accounting+). Unknown versions keep the
existing fallback: apply() reads the version from the APK. This does not restrict manually selected patches.
"""
try:
major = int(str((a.extra or {}).get("unity_version") or "0").split(".")[0])
except ValueError:
major = 0
return "arm64-v8a" in a.abis and not 0 < major < 2018
class Il2cppReturnPatch(Patch):
"""Make IL2CPP methods return a constant (targets), found per game with Cpp2IL (analysis/il2cpp.py)."""
targets: dict[str, dict[str, bytes]] = {}
@@ -164,7 +177,7 @@ class UnityTextInput(Il2cppReturnPatch):
return a.engine == "Unity" and "libil2cpp.so" in a.libs and bool((a.extra or {}).get("text_fields"))
def detect(self, a):
if self.applies(a):
if self.applies(a) and can_rewrite_il2cpp(a):
kinds = " and ".join((a.extra or {}).get("text_fields"))
return Suggestion(True, f"Unity app with text fields ({kinds}): they close at once on the Frame because "
"it has no system keyboard.")
@@ -40,6 +40,13 @@ class UnityTlsKeyPool(Patch):
def detect(self, a):
heavy = heavy_native_libs(a)
if self.applies(a) and _unity_major(a) >= 6000 and heavy:
# Firebase's Firestore and Gecko both consume keys alongside Unity 6 and the Frame's graphics/XR
# runtime. This is the documented exhaustion case (AGENTS.md, #198), rather than just any Firebase
# library: keep a lone SDK as an optional diagnostic fix below.
if "libFirebaseCppFirestore.so" in heavy and "libxul.so" in heavy:
return Suggestion(True, "Unity 6 with Firebase Firestore and Gecko: these native runtimes can "
"exhaust Android's 128 thread keys alongside the Frame's graphics and XR "
"libraries. Pool Unity's keys to leave room for them.")
return Suggestion(False, f"Unity 6 with {', '.join(heavy)}: turn on if the game aborts at start with "
"\"cannot create thread specific key\" (for example Wander).")
return None
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more