Compare commits

...
14 Commits
Author SHA1 Message Date
spoopyghosty0 af791a45b4 FramePort 0.7.2 2026-10-04 20:23:58 -04:00
spoopyghosty0 11c8802b07 Remember the window position and maximized state (GitHub #32); diagnostics for Steam refusing FramePort's games (GitHub #21/#30): Play reports what Steam's log says about the launch, diagnostics include the Steam library state and Steam's launch log lines (agent v42) 2026-10-04 20:22:47 -04:00
spoopyghosty0 4e00c88949 FramePort 0.7.1 2026-10-04 19:24:49 -04:00
spoopyghosty0 1b62d643f3 Notes: language packs verified with Deadpool VR (English dialogue with the patch on) 2026-10-04 19:23:33 -04:00
spoopyghosty0 6bd4eb523f One job queue per process (Flet builds a new app per window session: an old session's job ran unseen and the same game was built twice at once in one work folder, both failed) and one build per game at a time 2026-10-04 19:23:32 -04:00
spoopyghosty0 d22123c657 Language packs: lint (line length, imports) 2026-10-04 19:23:32 -04:00
spoopyghosty0 0137cd993b Language packs: ship libfp_langpack.so (built here), drop the dispatcher's late asset-list answer once we answered after the timeout (one answer per request), per-thread skip list, and games already in a library get their packs listed after an app update 2026-10-04 19:23:32 -04:00
yzfsoldier 7b8e7c2c5d Opt-in frame.langpacks: serve <tag>.lang language packs from the game's files (PR #20)
Some Quest games ship voice-over languages as <tag>.lang files and ask the Meta Platform SDK for them; overport's
platform loader answers with nothing, so every language but the built-in one stays greyed out. libfp_langpack.so
answers the language-pack and asset-file calls from the packs already on the device (Metadata = the game's
versionName, the /storage/emulated/0 path spelling Unreal uses). Tested in the headset with Deadpool VR (German
dialogue), AC Nexus and Asgard's Wrath 2.
2026-10-04 19:23:29 -04:00
spoopyghosty0 990331e5b6 WiiCompiled VR recipe: how to add a game (upload the .wcgame to its Import folder with the Files tab) 2026-10-04 18:32:29 -04:00
spoopyghosty0 56b370f582 WiiCompiled VR recipe: works with issues (no document picker in Lepton: manual .wcgame import; right eye jitters in races, inside the game's own OpenXR path) 2026-10-04 18:29:53 -04:00
spoopyghosty0 ac628cd284 FrameBridge: per-eye diagnostics (eye_debug: submitted vs fresh eye poses, eye-to-eye relation, release timing; also logged to framebridge.log because some games end Lepton's logcat early) and release_wait (wait for the game's GPU work before an image is released; 2 = A/B after 60 s) 2026-10-04 18:24:15 -04:00
spoopyghosty0 c12b2f6992 Steam art: games whose only art is the library's generated cover/banner get the placeholder set again (they got no Steam art at all, e.g. WiiCompiled) 2026-10-04 18:19:03 -04:00
spoopyghosty0 a110e8573f QuestCraft recipe: works with issues (Java runtime missing on first start; Minecraft's graphics then fail with OpenGL error 1282) 2026-10-04 18:11:37 -04:00
spoopyghosty0 4fdeeaf829 FrameBridge emulates Android video panels (XR_KHR_android_surface_swapchain: I Am Monkey's intro, surface_emul); the launcher repairs save folders without group write (SUPERHOT quit at start, agent v41); SUPERHOT (Quest) and I Am Monkey recipes; Lucky's Tale's out-of-memory diagnosis 2026-10-04 18:07:22 -04:00
38 changed files with 2783 additions and 37 deletions

No files matched your search

+18
View File
@@ -477,9 +477,27 @@ game runs (agent v37). New default fixes in FramePort's code reach games already
`library._follow_catalog` re-derives each non-user recipe once (setting `recipes.app_version`; tests switch it off via
`library.REFRESH_ON_UPDATE`); analysis fields added later still need a re-analysis. Troubleshooting techniques: docs/PLAYBOOK.md "Debugging techniques". Unity `boot.config` "vulkan" substring mislabels GLES games as Vulkan
(I Am Cat ran GLES); OVRPlugin's "Unavailable OpenXR extension: XR_FB_scene" is routine (no longer triaged).
**Round 4 (2026-10-04):** XR_KHR_android_surface_swapchain is listed by the Frame's runtime but returns
FUNCTION_UNSUPPORTED → adapter `surface_emul` (default on, `native/adapter/surface_swapchain.c`): an ordinary runtime
swapchain is returned, the game gets a Surface from a SurfaceTexture on a worker thread (own EGL context, JavaVM from
XrInstanceCreateInfoAndroidKHR), frames are read back (glReadPixels) and uploaded in xrEndFrame (Vulkan: own command
buffer + fence per panel, never waits; GLES: glTexSubImage2D). I Am Monkey's intro works (owner-confirmed). SUPERHOT
(Quest) quit at start: its cloud save folder was mode 1700 and Lepton's app writes through the folder's group →
launch.sh `fix_perms` adds u+rwx,g+rwx (agent v41). Lucky's Tale: Unity's Loading.PreloadManager thread grows the
native heap ~1 GB/s until the OOM killer (Frame freezes); no fix. `perf` works as steamos (paranoid 2; ptrace_scope 1
blocks gdb/eu-stack/debuggerd) — see PLAYBOOK "Debugging techniques". QuestCraft downloads its JRE at first run into
`files/runtimes/JRE` (Pojlib Installer); on the Frame it was missing (unpacked by hand, unverified). WiiCompiled: its launcher shows
(lepton-show-flatscreen) but imports .wcgame files through Android's document picker (OPEN_DOCUMENT), which Lepton
lacks (ActivityNotFoundException) → imported by hand: libmain.so + game.json → internal files/game/<profile>,
DATA/ → external files/WiiCompiledOpenXRVR/DATA, MOD/ → .../RetroRewind6 (decompiled with jadx). Lepton has no
picker at all: a FramePort fix would be an injected picker activity. Generated cover/banner art used to suppress the
Steam placeholder set (no Steam art at all) → fixed in artwork/steam.py.
**Steam library failures (GitHub #21/#30, open):** on 0.7.0 some Frames have FramePort's shortcut in shortcuts.vdf (so the install skips the Steam restart) yet Steam answers Play with "Game configuration unavailable" (= `Steam_AppUpdateError_9`; console_log: `LaunchGameAction: launch error 9 <appid>`). Not reproducible on the dev Frame (same SteamOS build). Agent v42: `launch` returns `steam` = what Steam's console_log says about that launch (started / error + code / silent; the app logs it and offers Report a problem on an error) and `collect_diag` adds `steam_library` (real Steam dir behind ~/.steam, client beta, Steam start vs shortcuts.vdf write time, FramePort's entries per account) + `steam-console.txt`. Verified on the dev Frame 2026-10-04 (Play → `started` within ~1 s). The dev Frame runs Steam's **arm64 beta** client (`package/beta` = linux_arm64_beta_…): check whether reporters are on the stable client. Next: read those from a reporter's zip.
**Lepton storage (2026-09-30):** each app's /sdcard (= /storage/emulated/0 → `<base>/lepton-data/external`) has `Movies`/`Download`/`Documents` symlinked to the Frame's `~/Videos`/`~/Downloads`/`~/Documents` (liblepton/mounting.sh, only if they exist at start); agent v24 `storage_targets` reads that mapping. Android's MediaProvider canonicalises paths to /home/steamos/... and rejects every file ("doesn't appear under [/system/media...]"), `sm list-volumes` is empty: the media index never works, apps must browse folders. Lepton installs with `adb install -g` (runtime permissions granted, MANAGE_EXTERNAL_STORAGE too). Files: `install/files.py`, `frameport frame send|storage`, GUI Files tab (formerly Frame → Send files).
**SteamVR per-app settings (2026-09-30):** editing steamvr.vrsettings while SteamVR runs is lost; the web API (127.0.0.1:27062 /app/setsettings) needs `x-steamvr-secret`. `native/vrsettings` = `fp_vrsettings.exe` (freestanding, OpenVR `FnTable:IVRSettings_003` as a Utility app, loads SteamVR's bin/win64/openvr_api.dll) sets them live and SteamVR persists them: section `steam.app.<shortcut appid>`, keys `preferredRefreshRate` (float) and `motionSmoothingOverride` (0 global, 1 on, 2 off, 3 always). Steam Link (vrlink) lists the Frame's rates 72/80/90/96/108/120/144 in vrserver.txt and follows the per-app preference ("host preferred N Hz"; whether the key is honoured is unverified in-headset yet). Judder metric: vrcompositor.txt session summary dropped + "Timed out. N total" (Stormland: 0 dropped but 313 timeouts in 2 min); fpsVR (`%LOCALAPPDATA%\fpsVR\*.json`, 0.1 ms histograms) gives p99 CPU/GPU ms. `pcvr.steamvr_tuning` (default on, PC only) applies on Play: highest rate whose budget ≥ p99×1.05, at least one step down, smoothing on.
**Language packs (merged from PR #20, 2026-10-04):** overport's `libovrplatformloader.so` is a dispatcher that `dlopen`s Meta's own loader (`libovrplatformloader_meta.so` / `_meta_q1.so`, also `libpxrplatformloader.so`) and keeps its own message queue; `ovr_LanguagePack_GetCurrent/SetCurrent` are 8-byte `return 0` stubs in it, `ovr_AssetFile_GetList` forwards to Meta's loader. `frame.langpacks` (opt-in, `native/langpack`) serves `<tag>.lang` files from the game's data; `elf.hide_exports` marks the loader's exports STB_LOCAL (bionic and glibc only match GLOBAL/WEAK; verified for glibc, bionic's `is_symbol_global_and_defined` is from memory). `libfp_langpack.so` is built here (`python native/build.py --only langpack`) and committed. Owner-verified 2026-10-04: Deadpool VR with only `en.lang` and the patch on plays English dialogue and runs normally (headless launch tests show 2-6 fps while it loads: not a regression sign). A dispatcher answer that arrives after we answered the timed-out GetList is dropped (one answer per request); games already in a library get `lang_packs` filled after an app update (`library._refresh_data_fields`). The library logs to logcat under the tag `fp_langpack` (dirs looked in, packs found, every language-pack call), so it shows up in the game's `launch.log`; an `ovr_AssetFile_GetList` the dispatcher leaves unanswered for 1.5 s is answered with our packs alone. Deadpool VR (Unreal) accepts a pack only when its `Metadata` equals the game's own version string (`ULanguagePacksSubsystem` compares it with `%s.%s.%s.%s.%s` built from the build info, e.g. `1.0.40.356975.Quest` = versionName; found by disassembling `libUE4.so`): the patch writes the APK's versionName into the library (`@FPMETA@` slot, `with_metadata`), `FRAMEPORT_LANGPACK_META` overrides it. Deadpool VR (2026-10-04, headset): German became selectable with that Metadata, but dialogue stayed silent (even English once reported as a pack) while the path was spelled `/sdcard/Android/obb/<pkg>/x.lang`; with the `/storage/emulated/0/Android/obb/<pkg>/x.lang` spelling (Unreal's own, now listed first in `scan_dirs`) German dialogue plays. `FRAMEPORT_LANGPACK_SKIP=<tags>` or a file `fp_langpack_skip` in the obb folder leaves packs out of the list (experiments).
**Unresolved (as of 2026-09-28):** Arcsmith (right-eye distortion) and Time Stall (both eyes) — swap, tracking, Valve
layers, depth, pacing ruled out. Sniper Elite VR (DEVICE LOST), Espire 1 (Mesa GL upload crash), HITMAN 3 (freedreno
crash): use PC versions.
+109 -5
View File
@@ -35,7 +35,7 @@ import sys
import time
import zlib
AGENT_VERSION = 40
AGENT_VERSION = 42
HOME = os.path.expanduser("~")
STEAM = os.path.join(HOME, ".local/share/Steam")
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
@@ -1203,10 +1203,41 @@ def cmd_launch(args):
if appid is None: # Steam would only say "Game configuration unavailable"
raise AgentError(f"{NOT_IN_LIBRARY}: {dep.get('title') or pkg}")
gid = steam_gameid(appid) # the shortcut's own id (it keeps its first one when the title changes)
log = os.path.join(STEAM, "logs/console_log.txt")
start = os.path.getsize(log) if os.path.exists(log) else 0
# systemd-run: the launch request must outlive this SSH session
run(["systemd-run", "--user", "--collect", "--quiet", f"--unit=frameport-launch-{int(time.time())}",
"steam", "-ifrunning", f"steam://rungameid/{gid}"])
return {"package": pkg, "gameid": gid, "title": dep.get("title")}
return {"package": pkg, "gameid": gid, "title": dep.get("title"),
"steam": steam_launch_result(log, start, appid, wait=args.get("wait", 10))}
STEAM_LAUNCH_ERROR = re.compile(r"launch error (\d+) (\d+)(.*)")
def steam_launch_result(log, start, appid, wait=10):
"""What Steam's console log says about the launch of shortcut `appid` (lines written after byte `start`): "started"
(Steam created the process), "error" (e.g. "launch error 9 <appid>" = Steam's "Game configuration unavailable",
GitHub #21/#30), "silent" (Steam logged nothing about this app: it didn't know the shortcut) or "unknown"."""
tag, lines = f"[AppID {appid}", []
deadline = time.time() + wait
while True:
try:
with open(log, "rb") as f:
f.seek(start)
new = f.read(1 << 20).decode("utf-8", "replace").splitlines()
except OSError:
return {"result": "unknown", "lines": []}
lines = [ln for ln in new if tag in ln or "launch error" in ln or "rungameid" in ln][-40:]
err = next((m for m in map(STEAM_LAUNCH_ERROR.search, lines) if m and m.group(2) == str(appid)), None)
if err:
return {"result": "error", "code": int(err.group(1)), "detail": err.group(3).strip(), "lines": lines}
if any(tag in ln and ("CreatingProcess" in ln or "WaitingGameWindow" in ln or "Completed" in ln)
for ln in lines):
return {"result": "started", "lines": lines}
if time.time() >= deadline:
return {"result": "silent" if not any(tag in ln for ln in lines) else "unknown", "lines": lines}
time.sleep(1)
LEPTON_LINK = re.compile(r'ln -s "\$\{HOME\}/([^"/]+)" "\$\{TARGET_PATH\}/([^"/]+)"')
@@ -1392,9 +1423,11 @@ LAUNCH_SH = (r"""#!/usr/bin/env bash
set -euo pipefail
app_dir={base_q}
[[ -d "$app_dir/lepton-app" ]] || {{ echo "Game files missing at $app_dir (storage not mounted?)" >&2; exit 1; }}
# Some games (Unreal cloud saves) create folders without write/search permission inside Lepton,
# which silently breaks saving. Repair them before and during every launch.
fix_perms() {{ find "$app_dir/lepton-data/external" -type d ! -perm -u+rwx -exec chmod u+rwx {{}} + 2>/dev/null ||"""
# Some games (Unreal cloud saves, SUPERHOT's cloud/data: mode 1700) create folders without write/search permission
# for the app inside Lepton (it writes through the folder's group), which breaks saving or makes the game quit.
# Repair them before and during every launch.
fix_perms() {{ find "$app_dir/lepton-data/external" -type d \( ! -perm -u+rwx -o ! -perm -g+rwx \) """
r"""-exec chmod u+rwx,g+rwx {{}} + 2>/dev/null ||"""
r""" true; }}
# Android can't create an app's external files/cache folders inside Lepton ("Invalid mkdirs path ... not a known app
# path"): getExternalCacheDir() then returns nothing, which breaks e.g. Whirligig's video player cache. Create them"""
@@ -2346,6 +2379,71 @@ def launch_test_pcvr(dep, anchor, log, seconds):
"kind": "pcvr", "game_process": bool(game_seen)}
def steam_library_report():
"""Why a game installed by FramePort may be missing from Steam or fail with "Game configuration unavailable"
(GitHub #21/#30): where Steam really lives, Steam's client version/beta, each account's shortcuts.vdf (when it
was written vs when Steam started, FramePort's entries in it) and Steam's log lines about these shortcuts.
Accounts are numbered, not named (the PC redacts ids anyway)."""
rep = {"steam_dir": STEAM}
for link in ("~/.steam/steam", "~/.steam/root"):
path = os.path.expanduser(link)
rep[link] = os.path.realpath(path) if os.path.lexists(path) else None
pkg_dir = os.path.join(STEAM, "package")
rep["beta"] = (_tail(os.path.join(pkg_dir, "beta"), 200) or "").strip() or None
rep["client_manifests"] = sorted(n for n in os.listdir(pkg_dir) if n.endswith(".manifest"))[:10] \
if os.path.isdir(pkg_dir) else []
p = run(["pgrep", "-o", "-x", "steam"])
pid = p.stdout.split()[0] if p.returncode == 0 and p.stdout.split() else None
rep["steam_started"] = os.stat(f"/proc/{pid}").st_mtime if pid and os.path.exists(f"/proc/{pid}") else None
if pid:
try:
rep["steam_cmdline"] = open(f"/proc/{pid}/cmdline", "rb").read().replace(b"\0", b" ").decode()[:500]
except OSError:
pass
ours = {}
for dep_path in glob.glob(os.path.join(ANCHORS, "*/deployment.json")):
try:
dep = json.load(open(dep_path))
except (OSError, ValueError):
continue
ours[f'"{os.path.dirname(dep_path)}/launch.sh"'] = dep.get("package")
active = active_steam_user()
accounts, appids = [], set()
for i, user in enumerate(steam_users()):
acc = {"account": i + 1, "most_recent_login": user == active}
cfg = os.path.join(STEAM, "userdata", user, "config")
vdf = os.path.join(cfg, "shortcuts.vdf")
acc["shortcuts_vdf_written"] = os.path.getmtime(vdf) if os.path.exists(vdf) else None
acc["localconfig_written"] = os.path.getmtime(os.path.join(cfg, "localconfig.vdf")) \
if os.path.exists(os.path.join(cfg, "localconfig.vdf")) else None
acc["backups"] = len(glob.glob(vdf + ".backup-*"))
try:
root = vdf_decode(open(vdf, "rb").read()) if os.path.exists(vdf) else {}
entries = [v for v in (root.get("shortcuts") or {}).values() if isinstance(v, dict)]
acc["shortcuts"] = len(entries)
acc["frameport"] = []
for v in entries:
if v.get("Exe") in ours:
appids.add(v.get("appid", 0) & 0xFFFFFFFF)
acc["frameport"].append({"package": ours[v["Exe"]], "appid": v.get("appid", 0) & 0xFFFFFFFF,
"title": v.get("AppName", v.get("appname")),
"start_dir": v.get("StartDir"), "openvr": v.get("OpenVR"),
"options": v.get("LaunchOptions")})
acc["exe_dupes"] = len(entries) - len({v.get("Exe") for v in entries})
except Exception as exc: # noqa: BLE001
acc["error"] = f"shortcuts.vdf unreadable: {exc}"
accounts.append(acc)
rep["accounts"] = accounts
lines = []
for name in ("console_log.previous.txt", "console_log.txt"):
text = _tail(os.path.join(STEAM, "logs", name), 8 << 20) or ""
keep = [ln for ln in text.splitlines() if "launch error" in ln or "rungameid" in ln
or ("shortcut" in ln.lower() and "path_shortcut" not in ln) or any(f"[AppID {a}" in ln for a in appids)]
if keep:
lines += [f"==> {name}"] + keep[-400:]
return rep, "\n".join(lines)
def _tail(path, max_bytes):
try:
size = os.path.getsize(path)
@@ -2388,6 +2486,12 @@ def cmd_collect_diag(args):
files[name] = text
host["installed"] = [{k: g.get(k) for k in ("package", "title", "kind", "appid", "version", "agent_version")}
for g in cmd_list_installed({})["games"]]
try:
host["steam_library"], console = steam_library_report()
if console:
files["steam-console.txt"] = console[-max_bytes:]
except Exception as exc: # noqa: BLE001 (diagnostics must not fail on it)
host["steam_library"] = {"error": str(exc)}
out = {"agent_version": AGENT_VERSION, "host": host, "files": files}
pkg = args.get("package")
if not pkg:
+3 -2
View File
@@ -1,11 +1,12 @@
48a3ecad77ec0f3215b29070e994590eb9579e04d3c88a47f37f306f9aeb01d9 ./arm64-v8a/libfp_langpack.so
a5b03bb7ae5d953d7ded2bf117b0a19c57fae604f16f54310847f8e89593dde6 ./arm64-v8a/libfp_ovrp.so
6d2b9f8cea2f2cf33b8ff30d29a2f3d9c4d55549260a867168a24e44abada021 ./arm64-v8a/libfp_vk.so
8e00552d1ab90f82749db3caad4f773351fa8a28edcc5ea5cbd1b31c434ff32a ./arm64-v8a/libframe_xrshim.so
3dfcb0f2bec47857bcecc7261c58e076d872d4649718c40850f29e10c75477dd ./arm64-v8a/libglshim.so
f326df1a5bd600033661f53509f076b9b4ecbb6226e9050460b1d0cfdd70fb9d ./arm64-v8a/libopenxr_loader_generic.so
507bb1c62168da9335a5883ec264aabed2ce09d04b6524e67be504a273473f8d ./arm64-v8a/libopenxr_loader_generic.so
1feaeafad467c4cafdf2b018a4d84b0bee200c3f711697b4ce97e66a3ba256ca ./arm64-v8a/libovrplatformcompat.so
32525cd0a9ee3d9993d8871cd6905bdcf22cde4f4ba28f5db6434ce7d6554758 ./arm64-v8a/libvrapi.so
ddfd8b6c319bfd0ea8aada3b5e941981288ac10aa6443a79843a7b8c288f82fe ./armeabi-v7a/libopenxr_loader_generic.so
11b7019c6a8d3b2f0f89cf23011f84bbbcb8e907f0935978e1df675339abbb6e ./armeabi-v7a/libopenxr_loader_generic.so
1871eae093432d277da4bc751bf5f3269dfcf11f9168260b0c3caadb0dedb19d ./dex/oculusos-stubs.dex
1aa733117cf57ccff7cf23f0425dbfd73b0332a3ef1c905ceeca0ccd0449c4e0 ./linux-arm64/XR_APILAYER_FRAMEPORT_timefix.json
28c2430a02bbd8902c5bfb9562c6fd0e318654f9e05c095bfeb94b0450ab1b07 ./linux-arm64/libxr_frameport_timefix.so
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,21 @@
package: com.NewFolderGames.IAmMonkey
title: I Am Monkey
status: works
notes: Its intro video plays through FrameBridge's video panels.
details: The game plays its intro on a panel that an Android media player (ExoPlayer) draws into
(XR_KHR_android_surface_swapchain). The Frame's runtime lists that extension but refuses the call, so the panel had
no image and the game stayed black waiting for the video (GitHub issue 25). The adapter's surface_emul (on by
default) hands the player a real Android Surface and copies each video frame into an ordinary swapchain the panel
shows.
tested_version: 1.0.5
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-10-04'
issue: 25
updated: '2026-10-04'
source_hint: I Am Monkey
+5 -4
View File
@@ -1,10 +1,11 @@
package: com.playful.LuckysTale
title: Lucky's Tale
status: issues
notes: Keeps MSAA off; the game turned it on by itself and the whole Frame restarted in a menu.
details: Meta's OVRManager raises MSAA to 4x at runtime ("Switching to the recommended level"); multisampled
render-to-texture on GLES (Zink) hung the Frame's GPU (GitHub issue 9). frame.unity_runtime_msaa_off keeps it at 0;
not yet confirmed in a headset.
notes: Runs out of memory within a few minutes and freezes the Frame until the game is killed.
details: Unity's asset loading thread (Loading.PreloadManager) grows the game's native heap by about 1 GB/s
shortly after start (10+ GB plus all swap, then the kernel kills it; perf page-fault profile, 2026-10-04). The text
window and the MSAA patch aren't the cause (same with the window off); the OBB is byte-identical to the original.
The earlier "headset restarted in a menu" reports (GitHub issue 9) were most likely this. No fix yet.
tested_version: 1.0.55
engine: Unity
xr: VrApi
+21
View File
@@ -0,0 +1,21 @@
package: com.qcxr.qcxr
title: QuestCraft
status: issues
notes: The launcher runs, but Minecraft crashes while starting its graphics (OpenGL error 1282).
details: QuestCraft downloads its Java runtime (JRE.zip from QuestCraft's GitHub releases) into files/runtimes/JRE
on first start; on the Frame that step left nothing behind ("libjvm.so not found"). With the runtime unpacked there
by hand, Java, Fabric and the mods load and Minecraft 1.21.5 starts initializing, then its first texture fails with
OpenGL error 1282 in QuestCraft's GL-to-GLES layer on Zink. Leads (2026-10-04) - Android's libEGL ran out of
eglGetProcAddress slots for desktop GL functions; LWJGL and JNA natives in the APK don't match the newer files
QuestCraft downloads.
tested_version: 6.0.0-RC4
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
verified:
date: '2026-10-04'
updated: '2026-10-04'
source_hint: QuestCraft
+24
View File
@@ -0,0 +1,24 @@
package: org.wiicompiled.quest
title: WiiCompiled VR
status: issues
notes: '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/Import, then open WiiCompiled (it imports the newest
file there; one at a time). The right eye jitters during races.'
details: A native Mario Kart Wii recompilation (needs your own disc as .wcgame files built by the WiiCompiled
launcher on a computer). Lepton's Android has no document picker, so the launcher's "Import from computer" and
"select disc image" buttons fail (ActivityNotFoundException for OPEN_DOCUMENT); its Import folder is read when the
launcher opens instead. The game's libmain.so has its own OpenXR loader and talks to the Frame's runtime directly
(FrameBridge isn't in its path); the right-eye jitter in races comes from its stereo replay of the race view, so it
needs a fix in WiiCompiled itself. The launcher is a flat Android window (shown with lepton-show-flatscreen).
tested_version: 0.4.0-quest
engine: Other
xr: OpenXR
frame:
- frame.sdl_clipboard
- frame.vk_sanitize
device:
- device.text_input_window
verified:
date: '2026-10-04'
updated: '2026-10-04'
source_hint: WiiCompiled
@@ -0,0 +1,22 @@
package: unity.SUPERHOT_Team.SUPERHOT_VR_QA
title: SUPERHOT VR
status: works
notes: Quest version. Needs FramePort's launcher from agent 41 (reinstall once) so the game can write its saves.
details: Unity 2018.4 with built-in Oculus support (GLES). Its eye swapchains (GL_RGBA8, then a 16-bit format) are
created as sRGB by the adapter's swapchain_fix. The game creates its cloud save folder with mode 1700 and quits at
start when it can't write there ("Something failed to initialize. Quitting!"); the launcher now gives every folder
in the game's storage owner and group write permission.
tested_version: '1.161'
engine: Unity
xr: VrApi
frame:
- frame.unity_no_msaa
- frame.unity_oculus_check
- frame.unity_text_input
- frame.unity_runtime_msaa_off
device:
- device.text_input_window
verified:
date: '2026-10-04'
updated: '2026-10-04'
source_hint: SUPERHOT VR
+19
View File
@@ -263,6 +263,25 @@ signatures:
diagnosis: The game crashed under Wine/Proton (set the Proton debug log and check steam-<appid>.log).
suggest: [pcvr.proton_log]
- id: save-folder-permission
pattern: "(We don't have write permission to|UnauthorizedAccessException: Access to the path \"/(sdcard|storage/emulated/0)/Android/data/)"
severity: error
diagnosis: The game can't write to a folder it created in its storage (e.g. SUPERHOT's cloud/data, mode 1700, which
makes it quit at start). FramePort's launcher (agent 41 or newer) gives such folders owner and group write
permission before and during every launch; update the game on the Frame (reinstall) to get the new launcher.
suggest: []
- id: surface-swapchain-emulated
pattern: 'surface_emul: emulated Android surface swapchain'
severity: info
diagnosis: The game plays a video on a panel through an Android Surface (XR_KHR_android_surface_swapchain), which the
Frame's runtime refuses; FrameBridge emulates it (surface_emul) and copies each video frame into the panel.
suggest: []
- id: surface-swapchain-failed
pattern: 'surface_emul: (setup failed|upload failed|EGL context failed|Vulkan upload path unavailable)'
severity: warning
diagnosis: FrameBridge couldn't emulate an Android video panel (XR_KHR_android_surface_swapchain); the panel stays
empty, and a game waiting for its intro video may stay black (e.g. I Am Monkey's intro).
suggest: []
milestones: # progress markers, in order; the furthest one reached is reported
- {id: pcvr-launch, kind: pcvr, pattern: 'FramePort: launching|Launched injector with', label: Launcher started}
- {id: pcvr-oculus-hmd, kind: pcvr, pattern: 'FramePort oculushmd: OculusHMDConnected event ready', label: Oculus headset event provided}
+5 -1
View File
@@ -23,6 +23,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Espire 2 | Quest | ✅ Works | |
| Genotype | Quest | ✅ Works | |
| H.U.N.T | Quest | ✅ Works | |
| I Am Monkey | Quest | ✅ Works | |
| In Death: Unchained | Quest | ✅ Works | |
| Job Simulator | Quest | ✅ Works | |
| Keep Talking and Nobody Explodes | Quest | ✅ Works | |
@@ -42,6 +43,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Space Pirate Trainer Quest | Quest | ✅ Works | |
| Stremio | Quest | ✅ Works | |
| SUPERHOT VR | PC VR | ✅ Works | |
| SUPERHOT VR | Quest | ✅ Works | |
| The Climb 2 | Quest | ✅ Works | |
| Toy Master | Quest | ✅ Works | |
| Under Cover | Quest | ✅ Works | |
@@ -52,11 +54,13 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Arcsmith | Quest | ⚠️ Works with issues | Right eye distorts during movement (unresolved; swap, tracking, Valve layers, depth and pacing ruled out). |
| Assassin's Creed Nexus | Quest | ⚠️ Works with issues | Some launch warning text is still upside down; the rest of the UI is fixed by flip emulation. |
| I Am Cat | Quest | ⚠️ Works with issues | The view vibrates slightly, even when holding still. |
| Lucky's Tale | Quest | ⚠️ Works with issues | Keeps MSAA off; the game turned it on by itself and the whole Frame restarted in a menu. |
| Lucky's Tale | Quest | ⚠️ Works with issues | Runs out of memory within a few minutes and freezes the Frame until the game is killed. |
| 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). |
| QuestCraft | Quest | ⚠️ Works with issues | The launcher runs, but Minecraft crashes while starting its graphics (OpenGL error 1282). |
| Silhouette | Quest | ⚠️ Works with issues | Hand-tracking game; the Frame synthesizes hands from controllers, so it is janky. |
| Time Stall | Quest | ⚠️ Works with issues | Both eyes distort during movement (unresolved). |
| 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… |
| BONELAB | Quest | ❌ Doesn't run | Crashes while starting its graphics (Vulkan); no fix yet. |
| Espire 1: VR Operative (Quest Edition) | Quest | ❌ Doesn't run | Mesa GL driver crash during texture upload. |
| HITMAN 3 VR: Reloaded | Quest | ❌ Doesn't run | Vulkan driver crash (freedreno), even without Valve layers. |
+9
View File
@@ -15,6 +15,9 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|---|---|---|
| Every game suddenly fails to start: `crun: create keyring …: Disk quota exceeded`, `is not a running context` | rootless podman leaked a kernel keyring per launch; 200-key quota exhausted | `keyring = false` in `~/.config/containers/containers.conf` (FramePort agent does it), then reboot the Frame once |
| A Unity app's text field shows a caret for a moment and loses focus; no keyboard appears (e.g. Stremio VR login) | Unity's TMP_InputField/InputField wait for Android's on-screen keyboard and close themselves without one (Lepton has none); headless VR apps also have no focused Android window, so no key press reaches them | `frame.unity_text_input` (Cpp2IL finds `TouchScreenKeyboardShouldBeUsed`/`isKeyboardUsingEvents`, rewritten to false/true) + `device.text_input_window` (lepton-show-flatscreen: Steam's keyboard and Type on Frame work) |
| Black screen at start while audio/ExoPlayer runs; log `xrEndFrame: dropped N unusable layer(s)`, a quad layer with swapchain 0x0 (e.g. I Am Monkey's intro video) | The game plays video into an Android-surface swapchain (XR_KHR_android_surface_swapchain); the Frame's runtime lists the extension but returns FUNCTION_UNSUPPORTED | adapter `surface_emul` (default on): FrameBridge gives the player a SurfaceTexture-backed Surface and copies each frame into an ordinary swapchain (log `surface_emul: …`) |
| The game quits right after start: `Something failed to initialize. Quitting!` / `We don't have write permission to …/files/cloud/data` (e.g. SUPERHOT) | The game created a save folder with mode 1700; inside Lepton the app writes through the folder's group | launch.sh `fix_perms` adds owner + group write to every folder in the game's storage (agent 41); reinstall to get the new launcher |
| The whole Frame slows to a halt, then the game is killed (`Out of memory: Killed process … anon-rss:10+ GB`), e.g. Lucky's Tale | The game's own memory grows ~1 GB/s on Unity's `Loading.PreloadManager` thread (perf page-fault profile); not the flat window, not the text-input patches | none yet: mark unsupported; profile with `perf record -p <pid> -e page-faults --call-graph fp` (works as steamos, `perf_event_paranoid` 2) |
| `APP_ACTIVITY is empty`, nothing starts | Manifest has category INFO only; Lepton needs LAUNCHER | `frame.launcher` (automatic) |
| PC VR game on the Frame shows as a flat window / Revive: `Unable to load LibOVRRT DLL` / `LoaderInstance::CreateInstance chained CreateInstance call failed` | Frame SteamVR runtime rejects OpenXR apiVersion 1.1 (`XR_ERROR_API_VERSION_UNSUPPORTED`), which Proton 11's VR helper requests | `pcvr.xr_timefix` (Frame OpenXR layer, default on): retries xrCreateInstance as 1.0 |
| Unreal PC VR game on the Frame runs as a flat window although OpenXR works (no `LogHMD` OVRPlugin lines; Unreal logs nothing when it skips the Oculus plugin) / launch.log: `FramePort oculushmd: could not create the OculusHMDConnected event` | UE's OculusHMD (and LibOVR's `ovr_Detect`) only start when the Windows event `OculusHMDConnected` exists and is signalled; on a PC the Oculus service creates it. Revive hooks `OpenEventW` for it, but that relies on Detours patching Wine's (ARM64EC) kernelbase | `pcvr.oculus_unreal` (default for Unreal Rift games; PC VR counterpart of overport's `patch_oculus_unreal`): launch.sh runs the injector through `fp_oculushmd.exe`, which provides the real event until the game exits |
@@ -30,6 +33,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| `INSTALL_FAILED_NO_MATCHING_ABIS` | 32-bit-only APK; Frame has no AArch32 | None. PC/Rift version via Revive |
| `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`, e.g. `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) grey 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) |
| `ClassNotFoundException com.oculus.os.AnalyticsEvent` → abort | Quest telemetry lookup in Meta XR Audio (Unreal build) or native code | `frame.metaxr_telemetry` + `frame.oculusos` (automatic) |
| `JNI DETECTED ERROR`, `GetStringUTFChars … NULL` | CheckJNI is on because overport marks the app debuggable | `frame.nodebug` |
| Unreal game quits a few seconds after start (`System.exit`) | ForceQuit after a failed Quest platform check | alternate build with `patch_remove_unreal_force_quit` (`use_alt`) |
@@ -98,6 +102,11 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
- Which library a stale pointer belonged to: turn on the Android linker's log for one run by adding
`debug.ld.app.<pkg>=dlopen` as an extra line of `LEPTON_GFXRECON_FP_PROPS` (first line `0`) in the game's
launch.sh on the Frame (back it up, restore it after) and look for `dlclose: unloading "…"`.
- Memory runaways / busy loops: `perf` works as steamos (`perf_event_paranoid` 2, user space only; `ptrace_scope` 1
blocks eu-stack/gdb/debuggerd). `perf record -p <pid> -e page-faults -c 64 --call-graph fp` names the thread
touching new memory (`perf script -F comm,tid,ip,dso`); `-t <tid> -F 499` samples one thread. Map IL2CPP
addresses with a full Cpp2IL diffable-cs dump (method `Offset` = address − the r-xp mapping of libil2cpp.so).
Sample memory per mapping name from `/proc/<pid>/smaps` (`[anon:libc_malloc]` = native heap).
- Unity catches native crashes itself: no debuggerd backtrace in Lepton's logcat-crash.log, but a
`tombstone_00` in the game's `Android/data/<pkg>/files/` with the memory map (map pc/lr/registers to libraries).
- Focus losses: the game sees FOCUSED→VISIBLE→SYNCHRONIZED (OVRPlugin `[XR_SESSION]`, FrameBridge `focus_hold:`
+1
View File
@@ -10,6 +10,7 @@ embeds debug paths (`-g`) and the dex depends on the d8 version, so those differ
| `adapter/` | `{arm64-v8a,armeabi-v7a}/libopenxr_loader_generic.so` | **FrameBridge**: replaces overport's generic loader (which is renamed `libopenxr_loader_original.so`) and fixes Steam Frame runtime gaps. Hooks xrCreateInstance, swapchains, xrEndFrame, spaces, xrPollEvent, … everything else is forwarded by `gen_forwarders.py`-generated tail calls. `scene_emu.c` = Meta scene/spatial-entity emulation; `flip_vk.c` = Vulkan blit for VERTICAL_FLIP quads. `session_fixes.c` = per-game session fixes, all off by default and hooked only when on (`layer_debug` diagnostics, `stable_local`, `focus_hold`, aim correction `aim_pitch/aim_yaw/aim_forward`, `refresh_rate`); `layer_emul_gl.c` = `equirect_emul` (GLES sessions only): 360° equirect/equirect2 layers become one adapter projection layer, drawn by a worker thread with its own EGL context shared with the app's: each 360° image is converted to a cube map only when it changes, and the view is redrawn only after a 4° head turn (GL/EGL resolved with dlopen, so Vulkan games never load them); `layer_math.h` = their pose/face math, tested on the host by `tests/test_layer_emul.py`. `render_model.c` = XR_FB_render_model emulation (setting `controller_models`, off by default): serves `files/framebridge/controller_{left,right}.glb`, which the agent converts on the Frame from SteamVR's own Frame controller render models (never shipped by FramePort); tested on the host by `tests/test_render_model.py`. Settings: `libframe_settings.so` in the APK + `settings.conf`/`framebridge.conf` on the Frame. |
| `vrapi-bridge/` | `arm64-v8a/libvrapi.so` | VrApi → OpenXR bridge from [Android-XR-Bridge/OVRPort](https://github.com/Android-XR-Bridge/OVRPort) `native/vrapi` at 5e7df52 (GPL-3.0, `LICENSE.upstream`; unchanged upstream as of OVRPort v1.2.5, which ships the unpatched code as its opt-in `patch_vrapi_openxr` in experimental CLI builds), with our changes in `upstream-patches/`: GLES sessions + GL texture swapchains, cylinder→quad layers, GL vertical flip, UNORM↔sRGB format twins, 30 s VR-mode deadline, VALID-only recenter, loading-icon layers skipped, diagnostics behind `-DOVP_GL_DIAG`. |
| `platformcompat/` | `arm64-v8a/libovrplatformcompat.so` | Real `ovrMessageType_ToString` (same fork, `native/platform`). |
| `langpack/` | `arm64-v8a/libfp_langpack.so` | Language packs for the Meta Platform SDK (patch `frame.langpacks`, opt-in). overport's platform loader is a dispatcher in front of Meta's own loader and answers `ovr_LanguagePack_GetCurrent/SetCurrent` with `return 0` (no reply ever). This library becomes the loader's first DT_NEEDED; the loader's own exports of the 31 functions it defines are made STB_LOCAL in `.dynsym` (`elf.hide_exports`, nothing moves), so symbol lookups reach the library first. It serves `<tag>.lang` files found in the game's OBB / app files (`$FRAMEPORT_LANGPACK_DIRS` overrides the search path) through `ovr_LanguagePack_*`, `ovr_AssetFile_GetList` (the loader's list + the packs) and `ovr_AssetFile_StatusById`; its own message queue is merged into `ovr_PopMessage`, and every handle that is not ours (an address-range check) goes to the loader's original function, whose address is read at run time from the loader's in-memory `.dynsym`. Host-tested against a stand-in loader (`tests/test_langpack.py`, plain `cc`, no NDK); the bionic/headset side is unverified. |
| `glshim/` | `arm64-v8a/libglshim.so` | Mesa GLSL compatibility for GLAD engines (hooks eglGetProcAddress): comments out `#pragma` before `#extension`, enables `GL_EXT_shader_implicit_conversions`, hides GL_OVR_multiview (`gl_hide_multiview`, default 1) and logs failed shaders. `-DGLSHIM_TRACE` adds per-FBO draw/error tracing. |
| `xrlayer/` | `linux-arm64/libxr_frameport_timefix.so` + `XR_APILAYER_FRAMEPORT_timefix.json` | OpenXR API layer for Windows PC VR games under Proton on the Frame (glibc aarch64, built freestanding with the NDK's clang), on by default (patch `pcvr.xr_timefix`). Retries `xrCreateInstance` as an OpenXR 1.0 app when the runtime rejects 1.1 (the Frame's SteamVR runtime does, and Proton 11's VR helper asks for 1.1). Also emulates `xrConvertTimespecTimeToTimeKHR`/`xrConvertTimeToTimespecTimeKHR` if the runtime refuses them (the Frame's Android runtime does; its Linux runtime, used by Proton, supports them as of 2026-09-29 — so this part is only a fallback; Proton's wineopenxr needs them for `XR_KHR_win32_convert_performance_counter_time`, which Revive requires) with the adapter's xrWaitFrame-calibrated offset, and drops the extension from xrCreateInstance if the runtime rejects it. Enabled per game by the Proton launch.sh (`XR_API_LAYER_PATH`, `XR_ENABLE_API_LAYERS`). `tests/test_xrlayer.py` builds it for x86_64 and drives it via ctypes. |
| `oculushmd/` | `win-x64/fp_oculushmd.exe` | PC VR counterpart of overport's `patch_oculus_unreal` (patch `pcvr.oculus_unreal`, default for Unreal Rift games on the Frame). Unreal's OculusHMD and LibOVR's `ovr_Detect` only start when the Windows named event `OculusHMDConnected` exists and is signalled (the Oculus service creates it). `fp_oculushmd.exe <command line>` creates it (manual reset, signalled), runs the command (Revive's injector) in a job object and keeps the event until every process in the job — the game and its children — has exited (fallback without job support: 3 minutes); returns the command's exit code and logs `FramePort oculushmd: …` to stderr (launch.log). Freestanding Windows x64 console exe (no CRT, no Windows SDK): the NDK's clang + `lld-link /Brepro` with a kernel32 import library generated by `llvm-dlltool`, so it's byte-reproducible. Tested on Windows from WSL with a build whose event name is `-DEVENT_NAME=L"…"` (the Oculus service owns the real event on a PC with the Oculus app). |
+161
View File
@@ -0,0 +1,161 @@
// SPDX-License-Identifier: GPL-3.0-only
// Included by frame_adapter.c (after flip_vk.c). Per-game diagnostics for "one eye looks wrong" reports
// (eye_debug=1; everything also goes to framebridge.log in the app's external files folder):
// * every frame's projection layer: each eye's submitted pose vs. a fresh xrLocateViews at the frame's display time
// (game-side pose errors), the left/right eye relation (eye distance, relative rotation: must stay constant),
// and how long before xrEndFrame each eye's image was released (images handed over too early/late);
// summarised every 5 s, the first frames in full.
// * release_wait: before an image is released, wait for the app's GPU work on the session's queue (Vulkan) or
// glFinish (GLES), for games that release images whose rendering hasn't finished. 2 = only after the first 60 s
// of frames, so one headset session compares both (log "release_wait now ON").
#define EYE_TRACKED 16
static struct { XrSwapchain handle; int64_t released_ns; } eye_released[EYE_TRACKED];
static pthread_mutex_t eye_lock = PTHREAD_MUTEX_INITIALIZER;
static int64_t eye_first_frame_ns;
static int release_wait_active(void) {
if (release_wait == 1) return 1;
if (release_wait != 2 || !eye_first_frame_ns) return 0;
static int announced;
int on = monotonic_ns() - eye_first_frame_ns > 60000000000ll;
if (on && !announced++) LOG("eye_debug: release_wait now ON (A/B: the first 60 s ran without it)");
return on;
}
static void eye_wait_for_gpu(void) {
if (vk.device) {
static PFN_vkQueueWaitIdle wait_idle;
if (!wait_idle && vk_ready()) wait_idle = (PFN_vkQueueWaitIdle)vk.GetDeviceProcAddr(vk.device, "vkQueueWaitIdle");
if (wait_idle && vk.queue) wait_idle(vk.queue);
} else {
static void (*finish)(void);
if (!finish) finish = (void (*)(void))dlsym(RTLD_DEFAULT, "glFinish");
if (finish) finish();
}
}
static XRAPI_ATTR XrResult XRAPI_CALL eye_hook_xrReleaseSwapchainImage(XrSwapchain swapchain,
const XrSwapchainImageReleaseInfo *info) {
PFN_xrReleaseSwapchainImage fn = (PFN_xrReleaseSwapchainImage)lookup(active_instance, "xrReleaseSwapchainImage");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
if (release_wait_active()) eye_wait_for_gpu();
XrResult result = fn(swapchain, info);
if (eye_debug) {
int64_t now = monotonic_ns();
pthread_mutex_lock(&eye_lock);
int slot = -1;
for (int i = 0; i < EYE_TRACKED && slot < 0; ++i)
if (eye_released[i].handle == swapchain) slot = i;
for (int i = 0; i < EYE_TRACKED && slot < 0; ++i)
if (!eye_released[i].handle) slot = i;
if (slot < 0) slot = (int)(now % EYE_TRACKED);
eye_released[slot].handle = swapchain;
eye_released[slot].released_ns = now;
pthread_mutex_unlock(&eye_lock);
}
return result;
}
static int64_t eye_release_age_ns(XrSwapchain swapchain, int64_t now) {
int64_t age = -1;
pthread_mutex_lock(&eye_lock);
for (int i = 0; i < EYE_TRACKED; ++i)
if (eye_released[i].handle == swapchain) age = now - eye_released[i].released_ns;
pthread_mutex_unlock(&eye_lock);
return age;
}
static float eye_angle_deg(XrQuaternionf a, XrQuaternionf b) {
float d = fabsf(a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w);
return d >= 1.0f ? 0.0f : 2.0f * acosf(d) * 57.29578f;
}
static float eye_dist_mm(XrVector3f a, XrVector3f b) {
float x = a.x - b.x, y = a.y - b.y, z = a.z - b.z;
return sqrtf(x * x + y * y + z * z) * 1000.0f;
}
static void eye_debug_end_frame(XrSession session, const XrFrameEndInfo *info) {
if (!info) return;
const XrCompositionLayerProjection *proj = NULL;
for (uint32_t i = 0; i < info->layerCount && !proj; ++i)
if (info->layers[i] && info->layers[i]->type == XR_TYPE_COMPOSITION_LAYER_PROJECTION &&
((const XrCompositionLayerProjection *)info->layers[i])->viewCount == 2)
proj = (const XrCompositionLayerProjection *)info->layers[i];
if (!proj) return;
int64_t now = monotonic_ns();
if (!eye_first_frame_ns) eye_first_frame_ns = now;
static struct {
int frames, located;
float pos_err[2], rot_err[2], pos_err_max[2], rot_err_max[2]; // submitted vs. fresh, per eye
float ipd_min, ipd_max, rel_rot_max, step_max[2]; // eye relation; frame-to-frame jump per eye
float age_min[2], age_max[2]; // ms from release to xrEndFrame
int64_t window;
} st;
static XrPosef last[2];
static int have_last;
static int detailed;
if (!st.window) { st.window = now; st.ipd_min = 1e9f; st.age_min[0] = st.age_min[1] = 1e9f; }
// a fresh location of the same views at the frame's display time, in the layer's space
XrView fresh[2] = {{XR_TYPE_VIEW, NULL}, {XR_TYPE_VIEW, NULL}};
XrViewState vs = {XR_TYPE_VIEW_STATE, NULL};
uint32_t n = 0;
PFN_xrLocateViews locate = (PFN_xrLocateViews)lookup(active_instance, "xrLocateViews");
XrViewLocateInfo li = {XR_TYPE_VIEW_LOCATE_INFO, NULL, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, info->displayTime,
proj->space};
int located = locate && XR_SUCCEEDED(locate(session, &li, &vs, 2, &n, fresh)) && n == 2 &&
(vs.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT);
const XrCompositionLayerProjectionView *v = proj->views;
float ipd = eye_dist_mm(v[0].pose.position, v[1].pose.position);
float rel = eye_angle_deg(v[0].pose.orientation, v[1].pose.orientation);
++st.frames;
if (ipd < st.ipd_min) st.ipd_min = ipd;
if (ipd > st.ipd_max) st.ipd_max = ipd;
if (rel > st.rel_rot_max) st.rel_rot_max = rel;
for (int e = 0; e < 2; ++e) {
int64_t age = eye_release_age_ns(v[e].subImage.swapchain, now);
float ms = age < 0 ? -1.0f : age / 1e6f;
if (ms < st.age_min[e]) st.age_min[e] = ms;
if (ms > st.age_max[e]) st.age_max[e] = ms;
if (located) {
float pe = eye_dist_mm(v[e].pose.position, fresh[e].pose.position);
float re = eye_angle_deg(v[e].pose.orientation, fresh[e].pose.orientation);
st.pos_err[e] += pe;
st.rot_err[e] += re;
if (pe > st.pos_err_max[e]) st.pos_err_max[e] = pe;
if (re > st.rot_err_max[e]) st.rot_err_max[e] = re;
}
if (have_last) {
float step = eye_angle_deg(last[e].orientation, v[e].pose.orientation);
if (step > st.step_max[e]) st.step_max[e] = step;
}
last[e] = v[e].pose;
}
have_last = 1;
if (located) ++st.located;
if (detailed < 4) {
++detailed;
for (int e = 0; e < 2; ++e)
LOG("eye_debug: eye %d swapchain=%p rect=%d,%d %dx%d array=%u pos=%.4f,%.4f,%.4f rot=%.4f,%.4f,%.4f,%.4f "
"fov=%.3f/%.3f/%.3f/%.3f fresh pos=%.4f,%.4f,%.4f", e, (void *)(uintptr_t)v[e].subImage.swapchain,
v[e].subImage.imageRect.offset.x, v[e].subImage.imageRect.offset.y, v[e].subImage.imageRect.extent.width,
v[e].subImage.imageRect.extent.height, v[e].subImage.imageArrayIndex, v[e].pose.position.x,
v[e].pose.position.y, v[e].pose.position.z, v[e].pose.orientation.x, v[e].pose.orientation.y,
v[e].pose.orientation.z, v[e].pose.orientation.w, v[e].fov.angleLeft, v[e].fov.angleRight,
v[e].fov.angleUp, v[e].fov.angleDown, fresh[e].pose.position.x, fresh[e].pose.position.y,
fresh[e].pose.position.z);
}
if (now - st.window > 5000000000ll) {
int l = st.located ? st.located : 1;
LOG("eye_debug: %d frames | eye distance %.1f-%.1f mm, eye-to-eye rotation max %.2f deg | vs fresh pose: "
"L avg %.1f mm/%.2f deg max %.1f mm/%.2f deg, R avg %.1f mm/%.2f deg max %.1f mm/%.2f deg (%d located) | "
"largest frame step L %.2f R %.2f deg | release->end L %.1f-%.1f ms R %.1f-%.1f ms | release_wait %s",
st.frames, st.ipd_min, st.ipd_max, st.rel_rot_max, st.pos_err[0] / l, st.rot_err[0] / l, st.pos_err_max[0],
st.rot_err_max[0], st.pos_err[1] / l, st.rot_err[1] / l, st.pos_err_max[1], st.rot_err_max[1], st.located,
st.step_max[0], st.step_max[1], st.age_min[0], st.age_max[0], st.age_min[1], st.age_max[1],
release_wait_active() ? "on" : "off");
memset(&st, 0, sizeof(st));
}
}
+55 -2
View File
@@ -45,12 +45,40 @@
#include <string.h>
#define TAG "FrameBridge"
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#include <stdarg.h>
#include <time.h>
// Everything also goes to <app external files>/framebridge.log when eye_debug is on: some games end Lepton's logcat
// mirror early (WiiCompiled), so a headset session's diagnostics would otherwise be lost.
static FILE *log_file;
static void fb_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void fb_log(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
__android_log_vprint(ANDROID_LOG_INFO, TAG, fmt, args);
va_end(args);
if (!log_file) return;
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
flockfile(log_file);
fprintf(log_file, "%lld.%03ld ", (long long)now.tv_sec, now.tv_nsec / 1000000);
va_start(args, fmt);
vfprintf(log_file, fmt, args);
va_end(args);
fputc('\n', log_file);
fflush(log_file);
funlockfile(log_file);
}
#define LOG(...) fb_log(__VA_ARGS__)
static void *loader;
static PFN_xrGetInstanceProcAddr next_gipa;
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
static XrInstance active_instance = XR_NULL_HANDLE;
static void *android_vm; // JavaVM from XrInstanceCreateInfoAndroidKHR (surface_swapchain.c)
static int surface_emul = 1; // setting: emulate Android surface swapchains
static int eye_debug; // setting: per-eye diagnostics + file log (eye_debug.c)
static int release_wait; // setting: wait for the app's GPU work before releasing images (2 = after 60 s: A/B)
static void surf_on_destroy(XrSwapchain handle);
static float scale = 1.0f;
static int foveation_fix = 1;
@@ -118,6 +146,9 @@ static void read_settings(const char *path) {
if (sscanf(line, "scene_depth=%f", &value) == 1 && value > 0.5f && value < 20.0f) scene_depth = value;
if (sscanf(line, "controller_models=%f", &value) == 1) controller_models = value != 0;
if (sscanf(line, "layer_debug=%f", &value) == 1) layer_debug = value != 0;
if (sscanf(line, "surface_emul=%f", &value) == 1) surface_emul = value != 0;
if (sscanf(line, "eye_debug=%f", &value) == 1) eye_debug = value != 0;
if (sscanf(line, "release_wait=%f", &value) == 1) release_wait = (int)value;
if (sscanf(line, "profile_remap=%f", &value) == 1) profile_remap = value != 0;
if (sscanf(line, "sync_guard=%f", &value) == 1) sync_guard = value != 0;
if (sscanf(line, "stable_local=%f", &value) == 1) stable_local = value != 0;
@@ -169,6 +200,12 @@ static void initialize(void) {
}
const char *env = getenv("FRAMEBRIDGE_CONFIG");
if (env && *env) read_settings(env);
if (eye_debug && *process && !strchr(process, '/')) {
snprintf(path, sizeof(path), "/sdcard/Android/data/%s/files/framebridge.log", process);
log_file = fopen(path, "a");
}
if (eye_debug || release_wait) LOG("per-game: eye_debug=%d release_wait=%d log_file=%s", eye_debug, release_wait,
log_file ? path : "none");
if (controller_models && *process && !strchr(process, '/')) render_model_init(process);
LOG("scale=%.2f foveation_fix=%d controller_fix=%d swapchain_fix=%d layer_fix=%d mutable_fix=%d swap_eyes=%d passthrough_emul=%d respace_kick=%d flip_quads=%d controller_models=%d loader=%s",
@@ -199,7 +236,10 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info
int chained = 0, enabled = 0;
for (const XrBaseInStructure *p = (const XrBaseInStructure *)info->next; p; p = p->next)
if (p->type == XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR) chained = 1;
if (p->type == XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR) {
chained = 1;
android_vm = ((const struct { XrStructureType type; const void *next; void *vm; void *activity; } *)p)->vm;
}
for (uint32_t i = 0; i < info->enabledExtensionCount; ++i)
if (!strcmp(info->enabledExtensionNames[i], "XR_KHR_android_create_instance")) enabled = 1;
@@ -420,6 +460,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrDestroySwapchain(XrSwapchain swapchain) {
PFN_xrDestroySwapchain fn = (PFN_xrDestroySwapchain)lookup(active_instance, "xrDestroySwapchain");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
forget_swapchain(swapchain);
surf_on_destroy(swapchain);
flip_on_destroy(swapchain);
emul_on_destroy_swapchain(swapchain);
if (equirect_emul && emul_is_virtual(swapchain)) { emul_virtual_destroy(swapchain); return XR_SUCCESS; }
@@ -673,6 +714,8 @@ XRAPI_ATTR XrResult XRAPI_CALL xrDestroySpace(XrSpace space) {
#include "session_fixes.c"
#include "layer_emul_gl.c"
#include "surface_swapchain.c"
#include "eye_debug.c"
XRAPI_ATTR XrResult XRAPI_CALL xrCreateSession(XrInstance instance, const XrSessionCreateInfo *info, XrSession *session) {
PFN_xrCreateSession fn = (PFN_xrCreateSession)lookup(instance, "xrCreateSession");
@@ -864,6 +907,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrLocateViews(XrSession session, const XrViewLoca
XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInfo *info) {
PFN_xrEndFrame fn = (PFN_xrEndFrame)lookup(active_instance, "xrEndFrame");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
if (eye_debug) eye_debug_end_frame(session, info);
{ // frame pacing statistics every ~5 s: fps and submitted-vs-predicted display time
static struct timespec start;
static int frames;
@@ -969,6 +1013,13 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
continue;
}
}
if (layer && (layer->type == XR_TYPE_COMPOSITION_LAYER_QUAD || layer->type == XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR) &&
!surf_prepare_layer(layer->type == XR_TYPE_COMPOSITION_LAYER_QUAD
? ((const XrCompositionLayerQuad *)layer)->subImage.swapchain
: ((const XrCompositionLayerCylinderKHR *)layer)->subImage.swapchain)) {
++dropped; // an emulated video surface without a frame yet
continue;
}
if (!layer || (layer_fix && !layer_usable(layer))) { ++dropped; continue; }
if (layer->type == XR_TYPE_COMPOSITION_LAYER_QUAD) {
const XrCompositionLayerQuad *flipped = flip_quad(session, (const XrCompositionLayerQuad *)layer, &quads[count]);
@@ -1241,6 +1292,8 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr(XrInstance instance, const
if (layer_debug || refresh_rate > 0) {
HOOK_AS(xrRequestDisplayRefreshRateFB, hook_request_refresh_rate)
}
if (surface_emul) HOOK_AS(xrCreateSwapchainAndroidSurfaceKHR, hook_xrCreateSwapchainAndroidSurfaceKHR)
if (eye_debug || release_wait) HOOK_AS(xrReleaseSwapchainImage, eye_hook_xrReleaseSwapchainImage)
if (sync_guard || layer_debug) HOOK_AS(xrSyncActions, hook_xrSyncActions)
if (layer_debug) HOOK_AS(xrGetActionStateBoolean, hook_xrGetActionStateBoolean)
if (layer_debug || aim_correction_on() || profile_remap)
+510
View File
@@ -0,0 +1,510 @@
// SPDX-License-Identifier: GPL-3.0-only
// Included by frame_adapter.c (after flip_vk.c and layer_emul_gl.c). Emulates XR_KHR_android_surface_swapchain,
// which the Frame's runtime lists but answers with XR_ERROR_FUNCTION_UNSUPPORTED. Games use it to play a video on a
// panel (OVROverlay "external surface", Android MediaPlayer/ExoPlayer drawing into a Surface): without it the panel has
// no image and is dropped, and a game that waits for its intro video shows black forever (I Am Monkey).
//
// * xrCreateSwapchainAndroidSurfaceKHR: the runtime first; if it can't, an ordinary runtime swapchain of the same size
// (sRGB RGBA8) is created and returned as the game's swapchain, and the game gets a real android.view.Surface from a
// SurfaceTexture owned by a worker thread (own EGL context; JNI through the JavaVM of xrCreateInstance).
// * The worker latches each new video frame (any size, YUV: SurfaceTexture samples it), draws it into an RGBA8
// texture of the swapchain's size and reads it back (glReadPixels) into a shared buffer.
// * xrEndFrame: a layer showing an emulated swapchain gets the newest frame uploaded first (Vulkan: staging buffer +
// copy on the session's queue; GLES: glTexSubImage2D in the app's context), then is submitted as usual.
// * Any failure: the call returns the runtime's own result (as before), so nothing gets worse.
#include <jni.h>
#define SURF_MAX 8
typedef void *(*PFN_ASurfaceTexture_fromSurfaceTexture)(JNIEnv *, jobject);
typedef int (*PFN_ASurfaceTexture_updateTexImage)(void *);
typedef void (*PFN_ASurfaceTexture_getTransformMatrix)(void *, float[16]);
typedef int64_t (*PFN_ASurfaceTexture_getTimestamp)(void *);
typedef void (*PFN_ASurfaceTexture_release)(void *);
#define surf_vm ((JavaVM *)android_vm) // from XrInstanceCreateInfoAndroidKHR (frame_adapter.c)
typedef struct {
int used;
XrSwapchain handle;
uint32_t width, height;
// worker
pthread_t thread;
int stop, ready, failed; // ready: surface handed out; failed: worker gave up
jobject surface; // global ref, returned to the game
// newest frame (RGBA8, top row first), written by the worker
uint8_t *pixels;
uint64_t seq; // bumps with every new frame
int64_t frames;
// upload side (app render thread)
uint64_t uploaded_seq;
int uploads, upload_failures, has_content;
VkImage vk_images[MAX_IMAGES];
uint32_t gl_images[MAX_IMAGES];
uint32_t image_count;
VkBuffer staging;
VkDeviceMemory staging_memory;
void *staging_map;
VkCommandPool pool; // own command buffer + fence: uploads never wait for the GPU in xrEndFrame
VkCommandBuffer cmd;
VkFence fence;
int in_flight; // a copy was submitted and its fence not yet seen signalled
} surf_swapchain;
static pthread_mutex_t surf_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t surf_cond = PTHREAD_COND_INITIALIZER;
static surf_swapchain surfs[SURF_MAX];
static int surf_vulkan; // the session is Vulkan (else GLES)
static surf_swapchain *surf_find(XrSwapchain handle) {
for (int i = 0; i < SURF_MAX; ++i)
if (surfs[i].used && surfs[i].handle == handle) return &surfs[i];
return NULL;
}
// ---------------------------------------------------------------- worker: SurfaceTexture -> RGBA pixels
static const char *surf_vs = "#version 300 es\nout vec2 uv;\nvoid main() {\n"
" vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));\n"
" uv = p; gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);\n}\n";
// window row 0 (glReadPixels' first row) must hold the image's top: sample t = 1 - y (SurfaceTexture t=0 is the bottom)
static const char *surf_fs = "#version 300 es\n#extension GL_OES_EGL_image_external_essl3 : require\n"
"precision mediump float;\nuniform samplerExternalOES tex;\nuniform mat4 st;\nin vec2 uv;\nout vec4 color;\n"
"void main() { color = texture(tex, (st * vec4(uv.x, 1.0 - uv.y, 0.0, 1.0)).xy); }\n";
typedef void (*PFN_glReadPixels_)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *);
typedef void (*PFN_glTexParameteri_)(GLenum, GLenum, GLint);
typedef void (*PFN_glUniformMatrix4fv_)(GLint, GLsizei, GLboolean, const GLfloat *);
typedef void (*PFN_glPixelStorei_)(GLenum, GLint);
typedef void (*PFN_glTexSubImage2D_)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *);
typedef EGLDisplay (*PFN_eglGetDisplay_)(EGLNativeDisplayType);
typedef EGLBoolean (*PFN_eglInitialize_)(EGLDisplay, EGLint *, EGLint *);
static PFN_glReadPixels_ s_glReadPixels;
static PFN_glTexParameteri_ s_glTexParameteri;
static PFN_glUniformMatrix4fv_ s_glUniformMatrix4fv;
static PFN_glPixelStorei_ s_glPixelStorei;
static PFN_glTexSubImage2D_ s_glTexSubImage2D;
static PFN_eglGetDisplay_ s_eglGetDisplay;
static PFN_eglInitialize_ s_eglInitialize;
static PFN_ASurfaceTexture_fromSurfaceTexture s_ast_from;
static PFN_ASurfaceTexture_updateTexImage s_ast_update;
static PFN_ASurfaceTexture_getTransformMatrix s_ast_matrix;
static PFN_ASurfaceTexture_getTimestamp s_ast_timestamp;
static PFN_ASurfaceTexture_release s_ast_release;
static int surf_load(void) {
static int state; // 0 untried, 1 ok, -1 failed
if (state) return state > 0;
state = -1;
if (!emul_load_gl()) { LOG("surface_emul: EGL/GLES not available"); return 0; }
void *egl = dlopen("libEGL.so", RTLD_NOW | RTLD_LOCAL), *gles = dlopen("libGLESv3.so", RTLD_NOW | RTLD_LOCAL);
void *android = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL);
if (!egl || !gles || !android) { LOG("surface_emul: libEGL/libGLESv3/libandroid missing"); return 0; }
s_glReadPixels = (PFN_glReadPixels_)dlsym(gles, "glReadPixels");
s_glTexParameteri = (PFN_glTexParameteri_)dlsym(gles, "glTexParameteri");
s_glUniformMatrix4fv = (PFN_glUniformMatrix4fv_)dlsym(gles, "glUniformMatrix4fv");
s_glPixelStorei = (PFN_glPixelStorei_)dlsym(gles, "glPixelStorei");
s_glTexSubImage2D = (PFN_glTexSubImage2D_)dlsym(gles, "glTexSubImage2D");
s_eglGetDisplay = (PFN_eglGetDisplay_)dlsym(egl, "eglGetDisplay");
s_eglInitialize = (PFN_eglInitialize_)dlsym(egl, "eglInitialize");
s_ast_from = (PFN_ASurfaceTexture_fromSurfaceTexture)dlsym(android, "ASurfaceTexture_fromSurfaceTexture");
s_ast_update = (PFN_ASurfaceTexture_updateTexImage)dlsym(android, "ASurfaceTexture_updateTexImage");
s_ast_matrix = (PFN_ASurfaceTexture_getTransformMatrix)dlsym(android, "ASurfaceTexture_getTransformMatrix");
s_ast_timestamp = (PFN_ASurfaceTexture_getTimestamp)dlsym(android, "ASurfaceTexture_getTimestamp");
s_ast_release = (PFN_ASurfaceTexture_release)dlsym(android, "ASurfaceTexture_release");
if (!s_glReadPixels || !s_glTexParameteri || !s_glUniformMatrix4fv || !s_glPixelStorei || !s_glTexSubImage2D ||
!s_eglGetDisplay || !s_eglInitialize || !s_ast_from || !s_ast_update || !s_ast_matrix || !s_ast_timestamp ||
!s_ast_release) {
LOG("surface_emul: a GL/EGL/ASurfaceTexture function is missing");
return 0;
}
state = 1;
return 1;
}
static void surf_fail(surf_swapchain *s, const char *why) {
LOG("surface_emul: %s", why);
pthread_mutex_lock(&surf_lock);
s->failed = 1;
pthread_cond_broadcast(&surf_cond);
pthread_mutex_unlock(&surf_lock);
}
static void *surf_worker(void *arg) {
surf_swapchain *s = arg;
JNIEnv *env = NULL;
if ((*surf_vm)->AttachCurrentThread(surf_vm, &env, NULL) != JNI_OK || !env) { surf_fail(s, "no JNI env"); return NULL; }
EGLDisplay dpy = s_eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint cfg_attribs[] = {EGL_RENDERABLE_TYPE, 0x40 /* EGL_OPENGL_ES3_BIT */, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE};
EGLConfig config = NULL;
EGLint n = 0, ctx_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE}, pb[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE};
EGLContext ctx = EGL_NO_CONTEXT;
EGLSurface pbuf = EGL_NO_SURFACE;
void *ast = NULL;
jobject st_local = NULL, st_global = NULL;
GLuint ext_tex = 0, rgba_tex = 0, fbo = 0, vao = 0, program = 0;
if (dpy == EGL_NO_DISPLAY || !s_eglInitialize(dpy, NULL, NULL) || !p_eglChooseConfig(dpy, cfg_attribs, &config, 1, &n) ||
n < 1 || (ctx = p_eglCreateContext(dpy, config, EGL_NO_CONTEXT, ctx_attribs)) == EGL_NO_CONTEXT ||
(pbuf = p_eglCreatePbufferSurface(dpy, config, pb)) == EGL_NO_SURFACE || !p_eglMakeCurrent(dpy, pbuf, pbuf, ctx)) {
surf_fail(s, "EGL context failed");
goto out;
}
// the SurfaceTexture's external texture, and the RGBA target the frames are drawn into
p_glGenTextures(1, &ext_tex);
p_glBindTexture(0x8D65 /* GL_TEXTURE_EXTERNAL_OES */, ext_tex);
s_glTexParameteri(0x8D65, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
s_glTexParameteri(0x8D65, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
p_glGenTextures(1, &rgba_tex);
p_glBindTexture(GL_TEXTURE_2D, rgba_tex);
p_glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, (GLsizei)s->width, (GLsizei)s->height);
p_glGenFramebuffers(1, &fbo);
p_glBindFramebuffer(GL_FRAMEBUFFER, fbo);
p_glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rgba_tex, 0);
if (p_glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { surf_fail(s, "framebuffer incomplete"); goto out; }
{
GLuint v = emul_compile(GL_VERTEX_SHADER, "", surf_vs), f = emul_compile(GL_FRAGMENT_SHADER, "", surf_fs);
if (!v || !f) { surf_fail(s, "shader compile failed"); goto out; }
program = p_glCreateProgram();
p_glAttachShader(program, v);
p_glAttachShader(program, f);
p_glLinkProgram(program);
GLint ok = 0;
p_glGetProgramiv(program, GL_LINK_STATUS, &ok);
if (!ok) { surf_fail(s, "program link failed"); goto out; }
}
p_glGenVertexArrays(1, &vao);
// android.graphics.SurfaceTexture(texName) + android.view.Surface(SurfaceTexture)
{
jclass st_class = (*env)->FindClass(env, "android/graphics/SurfaceTexture");
jclass surface_class = (*env)->FindClass(env, "android/view/Surface");
if (!st_class || !surface_class) { (*env)->ExceptionClear(env); surf_fail(s, "SurfaceTexture/Surface class missing"); goto out; }
jmethodID st_init = (*env)->GetMethodID(env, st_class, "<init>", "(I)V");
jmethodID st_size = (*env)->GetMethodID(env, st_class, "setDefaultBufferSize", "(II)V");
jmethodID surface_init = (*env)->GetMethodID(env, surface_class, "<init>", "(Landroid/graphics/SurfaceTexture;)V");
st_local = (*env)->NewObject(env, st_class, st_init, (jint)ext_tex);
if (!st_local || (*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); surf_fail(s, "new SurfaceTexture failed"); goto out; }
(*env)->CallVoidMethod(env, st_local, st_size, (jint)s->width, (jint)s->height);
jobject surface_local = (*env)->NewObject(env, surface_class, surface_init, st_local);
if (!surface_local || (*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); surf_fail(s, "new Surface failed"); goto out; }
st_global = (*env)->NewGlobalRef(env, st_local);
ast = s_ast_from(env, st_local);
if (!ast) { surf_fail(s, "ASurfaceTexture_fromSurfaceTexture failed"); goto out; }
pthread_mutex_lock(&surf_lock);
s->surface = (*env)->NewGlobalRef(env, surface_local);
s->ready = 1;
pthread_cond_broadcast(&surf_cond);
pthread_mutex_unlock(&surf_lock);
(*env)->DeleteLocalRef(env, surface_local);
}
LOG("surface_emul: Surface ready for %ux%u swapchain %p", s->width, s->height, (void *)(uintptr_t)s->handle);
{
GLint u_tex = p_glGetUniformLocation(program, "tex"), u_st = p_glGetUniformLocation(program, "st");
size_t bytes = (size_t)s->width * s->height * 4;
uint8_t *buf = malloc(bytes);
int64_t last_ts = -1, window_frames = 0, window_start = 0;
while (!s->stop && buf) {
struct timespec pause = {0, 8000000}; // ~120 checks a second: well above video frame rates
nanosleep(&pause, NULL);
if (s_ast_update(ast) != 0) continue;
int64_t ts = s_ast_timestamp(ast);
if (ts == last_ts) continue; // no new frame latched
last_ts = ts;
float m[16];
s_ast_matrix(ast, m);
p_glBindFramebuffer(GL_FRAMEBUFFER, fbo);
p_glViewport(0, 0, (GLsizei)s->width, (GLsizei)s->height);
p_glUseProgram(program);
p_glActiveTexture(GL_TEXTURE0);
p_glBindTexture(0x8D65, ext_tex);
p_glUniform1i(u_tex, 0);
s_glUniformMatrix4fv(u_st, 1, GL_FALSE, m);
p_glBindVertexArray(vao);
p_glDrawArrays(GL_TRIANGLES, 0, 3);
s_glPixelStorei(GL_PACK_ALIGNMENT, 1);
s_glReadPixels(0, 0, (GLsizei)s->width, (GLsizei)s->height, GL_RGBA, GL_UNSIGNED_BYTE, buf);
GLenum err = p_glGetError();
pthread_mutex_lock(&surf_lock);
if (!err && s->pixels) { memcpy(s->pixels, buf, bytes); s->seq++; s->frames++; }
pthread_mutex_unlock(&surf_lock);
if (err) { static int warned; if (warned++ < 5) LOG("surface_emul: GL error 0x%x drawing a frame", err); }
int64_t now = monotonic_ns();
if (!window_start) {
window_start = now;
LOG("surface_emul: first video frame (timestamp %lld)", (long long)ts);
}
if (++window_frames && now - window_start > 5000000000ll) {
LOG("surface_emul: %.1f video frames/s, %d uploaded, %d upload failures", window_frames * 1e9 / (now - window_start),
s->uploads, s->upload_failures);
window_frames = 0;
window_start = now;
}
}
free(buf);
}
out:
if (ast) s_ast_release(ast);
if (st_global) (*env)->DeleteGlobalRef(env, st_global);
if (ctx != EGL_NO_CONTEXT) { p_eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); p_eglDestroyContext(dpy, ctx); }
if (pbuf != EGL_NO_SURFACE) p_eglDestroySurface(dpy, pbuf);
(*surf_vm)->DetachCurrentThread(surf_vm);
return NULL;
}
// ---------------------------------------------------------------- uploads (app render thread)
static struct {
PFN_vkCreateBuffer CreateBuffer;
PFN_vkGetBufferMemoryRequirements GetBufferMemoryRequirements;
PFN_vkAllocateMemory AllocateMemory;
PFN_vkBindBufferMemory BindBufferMemory;
PFN_vkMapMemory MapMemory;
PFN_vkCmdCopyBufferToImage CmdCopyBufferToImage;
PFN_vkCmdClearColorImage CmdClearColorImage;
PFN_vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties;
PFN_vkGetFenceStatus GetFenceStatus;
int state;
} svk;
static int surf_vk_ready(void) {
if (svk.state) return svk.state > 0;
svk.state = -1;
if (!vk_ready()) return 0;
#define SDEV(name) svk.name = (PFN_vk##name)vk.GetDeviceProcAddr(vk.device, "vk" #name); if (!svk.name) return 0;
SDEV(CreateBuffer) SDEV(GetBufferMemoryRequirements) SDEV(AllocateMemory) SDEV(BindBufferMemory) SDEV(MapMemory)
SDEV(CmdCopyBufferToImage) SDEV(CmdClearColorImage) SDEV(GetFenceStatus)
#undef SDEV
void *lib = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)dlsym(lib, "vkGetInstanceProcAddr") : NULL;
svk.GetPhysicalDeviceMemoryProperties = gipa ? (PFN_vkGetPhysicalDeviceMemoryProperties)gipa(vk.instance,
"vkGetPhysicalDeviceMemoryProperties") : NULL;
if (!svk.GetPhysicalDeviceMemoryProperties) return 0;
svk.state = 1;
return 1;
}
static void surf_barrier(VkCommandBuffer cmd, VkImage image, VkImageLayout from, VkImageLayout to,
VkAccessFlags src_access, VkAccessFlags dst_access) {
VkImageMemoryBarrier b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, src_access, dst_access, from, to,
VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image,
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, NULL, 0,
NULL, 1, &b);
}
static int surf_staging(surf_swapchain *s) {
if (s->staging_map) return 1;
VkCommandPoolCreateInfo pool = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL,
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, vk.family};
if (vk.CreateCommandPool(vk.device, &pool, NULL, &s->pool) != VK_SUCCESS) return 0;
VkCommandBufferAllocateInfo alloc = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, NULL, s->pool,
VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1};
if (vk.AllocateCommandBuffers(vk.device, &alloc, &s->cmd) != VK_SUCCESS) return 0;
VkFenceCreateInfo fence = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL, 0};
if (vk.CreateFence(vk.device, &fence, NULL, &s->fence) != VK_SUCCESS) return 0;
VkBufferCreateInfo bi = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, NULL, 0, (VkDeviceSize)s->width * s->height * 4,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_SHARING_MODE_EXCLUSIVE, 0, NULL};
if (svk.CreateBuffer(vk.device, &bi, NULL, &s->staging) != VK_SUCCESS) return 0;
VkMemoryRequirements req;
svk.GetBufferMemoryRequirements(vk.device, s->staging, &req);
VkPhysicalDeviceMemoryProperties props;
svk.GetPhysicalDeviceMemoryProperties(vk.physical, &props);
uint32_t want = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, type = UINT32_MAX;
for (uint32_t i = 0; i < props.memoryTypeCount && type == UINT32_MAX; ++i)
if ((req.memoryTypeBits & (1u << i)) && (props.memoryTypes[i].propertyFlags & want) == want) type = i;
if (type == UINT32_MAX) return 0;
VkMemoryAllocateInfo ai = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, req.size, type};
if (svk.AllocateMemory(vk.device, &ai, NULL, &s->staging_memory) != VK_SUCCESS) return 0;
if (svk.BindBufferMemory(vk.device, s->staging, s->staging_memory, 0) != VK_SUCCESS) return 0;
return svk.MapMemory(vk.device, s->staging_memory, 0, VK_WHOLE_SIZE, 0, &s->staging_map) == VK_SUCCESS;
}
// Copy the newest frame (or black, the first time) into the next image of the runtime swapchain. Returns 1 if the
// swapchain now has an image to show, -1 if the previous copy is still running (try next frame), 0 on failure.
static int surf_upload(surf_swapchain *s, int black) {
PFN_xrAcquireSwapchainImage acquire = (PFN_xrAcquireSwapchainImage)lookup(active_instance, "xrAcquireSwapchainImage");
PFN_xrWaitSwapchainImage wait = (PFN_xrWaitSwapchainImage)lookup(active_instance, "xrWaitSwapchainImage");
PFN_xrReleaseSwapchainImage release = (PFN_xrReleaseSwapchainImage)lookup(active_instance, "xrReleaseSwapchainImage");
if (!acquire || !wait || !release || !s->image_count) return 0;
uint32_t index = 0;
XrSwapchainImageAcquireInfo ai = {XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, NULL};
XrSwapchainImageWaitInfo wi = {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, NULL, 100000000};
XrSwapchainImageReleaseInfo ri = {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, NULL};
if (surf_vulkan && s->in_flight) { // the previous copy still reads the staging buffer: try again next frame
if (svk.GetFenceStatus(vk.device, s->fence) != VK_SUCCESS) return -1;
vk.ResetFences(vk.device, 1, &s->fence);
s->in_flight = 0;
}
if (XR_FAILED(acquire(s->handle, &ai, &index)) || index >= s->image_count) return 0;
if (XR_FAILED(wait(s->handle, &wi))) { release(s->handle, &ri); return 0; }
int ok = 0;
size_t bytes = (size_t)s->width * s->height * 4;
if (surf_vulkan) {
if (!black) {
pthread_mutex_lock(&surf_lock);
memcpy(s->staging_map, s->pixels, bytes);
pthread_mutex_unlock(&surf_lock);
}
VkImage img = s->vk_images[index];
VkCommandBufferBeginInfo begin = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL};
VkCommandBuffer cmd = s->cmd;
vk.ResetCommandBuffer(cmd, 0);
vk.BeginCommandBuffer(cmd, &begin);
surf_barrier(cmd, img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT);
if (black) {
VkClearColorValue c = {{0, 0, 0, 1}};
VkImageSubresourceRange r = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
svk.CmdClearColorImage(cmd, img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &c, 1, &r);
} else {
VkBufferImageCopy copy = {0, 0, 0, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, {0, 0, 0}, {s->width, s->height, 1}};
svk.CmdCopyBufferToImage(cmd, s->staging, img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
}
surf_barrier(cmd, img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
vk.EndCommandBuffer(cmd);
VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, 1, &cmd, 0, NULL};
// released right after the submit: the runtime's own work on this queue runs after the copy
ok = vk.QueueSubmit(vk.queue, 1, &submit, s->fence) == VK_SUCCESS;
s->in_flight = ok;
} else if (!black) { // GLES: the app's context is current on its render thread (xrEndFrame)
GLint prev_tex = 0, prev_align = 4, prev_unpack = 0;
p_glGetIntegerv(GL_TEXTURE_BINDING_2D, &prev_tex);
p_glGetIntegerv(GL_UNPACK_ALIGNMENT, &prev_align);
p_glGetIntegerv(0x88EF /* GL_PIXEL_UNPACK_BUFFER_BINDING */, &prev_unpack);
if (prev_unpack) { typedef void (*bb)(GLenum, GLuint); static bb bind; if (!bind) bind = (bb)dlsym(RTLD_DEFAULT, "glBindBuffer"); if (bind) bind(0x88EC, 0); }
p_glBindTexture(GL_TEXTURE_2D, s->gl_images[index]);
s_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
pthread_mutex_lock(&surf_lock);
s_glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)s->width, (GLsizei)s->height, GL_RGBA, GL_UNSIGNED_BYTE, s->pixels);
pthread_mutex_unlock(&surf_lock);
ok = p_glGetError() == GL_NO_ERROR;
s_glPixelStorei(GL_UNPACK_ALIGNMENT, prev_align);
p_glBindTexture(GL_TEXTURE_2D, (GLuint)prev_tex);
if (prev_unpack) { typedef void (*bb)(GLenum, GLuint); static bb bind; if (!bind) bind = (bb)dlsym(RTLD_DEFAULT, "glBindBuffer"); if (bind) bind(0x88EC, (GLuint)prev_unpack); }
}
release(s->handle, &ri);
return ok;
}
// xrEndFrame: before a layer showing an emulated swapchain is submitted. Returns 0 if it has nothing to show yet.
static int surf_prepare_layer(XrSwapchain handle) {
pthread_mutex_lock(&surf_lock);
surf_swapchain *s = surf_find(handle);
uint64_t seq = s ? s->seq : 0;
pthread_mutex_unlock(&surf_lock);
if (!s) return 1; // not ours
if (seq != s->uploaded_seq) {
int r = surf_upload(s, 0);
if (r > 0) { s->uploaded_seq = seq; s->uploads++; s->has_content = 1; }
else if (r == 0 && s->upload_failures++ < 5) LOG("surface_emul: upload failed (swapchain %p)", (void *)(uintptr_t)handle);
}
return s->has_content;
}
// ---------------------------------------------------------------- the emulated entry points
typedef XrResult (XRAPI_PTR *PFN_xrCreateSwapchainAndroidSurfaceKHR_)(XrSession, const XrSwapchainCreateInfo *,
XrSwapchain *, jobject *);
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrCreateSwapchainAndroidSurfaceKHR(XrSession session,
const XrSwapchainCreateInfo *info, XrSwapchain *swapchain, jobject *surface) {
PFN_xrCreateSwapchainAndroidSurfaceKHR_ fn =
(PFN_xrCreateSwapchainAndroidSurfaceKHR_)lookup(active_instance, "xrCreateSwapchainAndroidSurfaceKHR");
XrResult result = fn ? fn(session, info, swapchain, surface) : XR_ERROR_FUNCTION_UNSUPPORTED;
if (result != XR_ERROR_FUNCTION_UNSUPPORTED || !info || !swapchain || !surface) return result;
LOG("surface_emul: runtime has no Android surface swapchains: emulating %ux%u (vm %s, %s session)", info->width,
info->height, surf_vm ? "ok" : "MISSING", vk.device ? "Vulkan" : "GLES");
if (!surf_vm || !info->width || !info->height || !surf_load()) return result;
surf_vulkan = vk.device != VK_NULL_HANDLE;
if (surf_vulkan && !surf_vk_ready()) { LOG("surface_emul: Vulkan upload path unavailable"); return result; }
pthread_mutex_lock(&surf_lock);
surf_swapchain *s = NULL;
for (int i = 0; i < SURF_MAX && !s; ++i)
if (!surfs[i].used) s = &surfs[i];
if (s) { memset(s, 0, sizeof(*s)); s->used = 1; }
pthread_mutex_unlock(&surf_lock);
if (!s) { LOG("surface_emul: too many surface swapchains"); return result; }
// the runtime swapchain the game gets instead (what its layer will show)
PFN_xrCreateSwapchain create = (PFN_xrCreateSwapchain)lookup(active_instance, "xrCreateSwapchain");
PFN_xrEnumerateSwapchainImages enumerate =
(PFN_xrEnumerateSwapchainImages)lookup(active_instance, "xrEnumerateSwapchainImages");
PFN_xrDestroySwapchain destroy = (PFN_xrDestroySwapchain)lookup(active_instance, "xrDestroySwapchain");
XrSwapchainCreateInfo ci = {XR_TYPE_SWAPCHAIN_CREATE_INFO, NULL, 0,
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT |
XR_SWAPCHAIN_USAGE_SAMPLED_BIT,
surf_vulkan ? 43 /* VK_FORMAT_R8G8B8A8_SRGB */ : 0x8C43 /* GL_SRGB8_ALPHA8 */,
1, info->width, info->height, 1, 1, 1};
XrSwapchain handle = XR_NULL_HANDLE;
XrResult cr = create && enumerate ? create(session, &ci, &handle) : XR_ERROR_FUNCTION_UNSUPPORTED;
if (XR_FAILED(cr)) {
LOG("surface_emul: xrCreateSwapchain failed %d", cr);
pthread_mutex_lock(&surf_lock); s->used = 0; pthread_mutex_unlock(&surf_lock);
return result;
}
s->handle = handle;
s->width = info->width;
s->height = info->height;
s->pixels = calloc((size_t)s->width * s->height, 4);
uint32_t n = 0;
if (surf_vulkan) {
XrSwapchainImageVulkanKHR images[MAX_IMAGES];
for (int i = 0; i < MAX_IMAGES; ++i) images[i] = (XrSwapchainImageVulkanKHR){XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR, NULL, VK_NULL_HANDLE};
if (XR_SUCCEEDED(enumerate(handle, MAX_IMAGES, &n, (XrSwapchainImageBaseHeader *)images)))
for (uint32_t i = 0; i < n && i < MAX_IMAGES; ++i) s->vk_images[i] = images[i].image;
} else {
emul_gles_image images[MAX_IMAGES];
for (int i = 0; i < MAX_IMAGES; ++i) images[i] = (emul_gles_image){XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR, NULL, 0};
if (XR_SUCCEEDED(enumerate(handle, MAX_IMAGES, &n, (XrSwapchainImageBaseHeader *)images)))
for (uint32_t i = 0; i < n && i < MAX_IMAGES; ++i) s->gl_images[i] = images[i].image;
}
s->image_count = n < MAX_IMAGES ? n : MAX_IMAGES;
int setup_ok = s->pixels && s->image_count && (!surf_vulkan || surf_staging(s));
if (setup_ok) {
pthread_mutex_lock(&surf_lock);
setup_ok = pthread_create(&s->thread, NULL, surf_worker, s) == 0;
struct timespec until;
clock_gettime(CLOCK_REALTIME, &until);
until.tv_sec += 3;
while (setup_ok && !s->ready && !s->failed && pthread_cond_timedwait(&surf_cond, &surf_lock, &until) == 0) {}
setup_ok = setup_ok && s->ready;
pthread_mutex_unlock(&surf_lock);
}
if (!setup_ok) {
LOG("surface_emul: setup failed (images %u, pixels %d): the panel stays empty", s->image_count, s->pixels != NULL);
if (s->thread) { s->stop = 1; pthread_join(s->thread, NULL); }
if (destroy) destroy(handle);
free(s->pixels);
pthread_mutex_lock(&surf_lock); s->used = 0; pthread_mutex_unlock(&surf_lock);
return result;
}
// something valid to show from the first frame on (Vulkan: a black image; GLES: the layer waits for a frame)
if (surf_vulkan && surf_upload(s, 1) > 0) s->has_content = 1;
remember_swapchain(handle);
*swapchain = handle;
*surface = s->surface;
LOG("surface_emul: emulated Android surface swapchain %p (%u images)", (void *)(uintptr_t)handle, s->image_count);
return XR_SUCCESS;
}
// xrDestroySwapchain: an emulated swapchain's worker and surface go with it
static void surf_on_destroy(XrSwapchain handle) {
pthread_mutex_lock(&surf_lock);
surf_swapchain *s = surf_find(handle);
pthread_mutex_unlock(&surf_lock);
if (!s) return;
s->stop = 1;
if (s->thread) pthread_join(s->thread, NULL);
if (surf_vm && s->surface) {
JNIEnv *env = NULL;
int attached = 0;
if ((*surf_vm)->GetEnv(surf_vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
attached = (*surf_vm)->AttachCurrentThread(surf_vm, &env, NULL) == JNI_OK;
}
if (env) (*env)->DeleteGlobalRef(env, s->surface);
if (attached) (*surf_vm)->DetachCurrentThread(surf_vm);
}
pthread_mutex_lock(&surf_lock);
free(s->pixels);
s->pixels = NULL;
s->used = 0;
pthread_mutex_unlock(&surf_lock);
LOG("surface_emul: destroyed %p", (void *)(uintptr_t)handle);
}
+14 -4
View File
@@ -5,12 +5,12 @@ Everything is fetched on demand into native/.cache (git-ignored):
- Android NDK r27c (27.2.12479018) from Google's repository (checksummed via repository2-3.xml)
- OpenXR headers at the commits each component was written against (KhronosGroup/OpenXR-SDK)
- Temurin JDK 21 (javac) and Android build-tools (d8) for the Java stub classes
Then builds: FrameBridge adapter (arm64 + arm32), VrApi bridge, platform compat, GL shim, oculusos stub dex, the
Then builds: FrameBridge adapter (arm64 + arm32), VrApi bridge, platform compat, language packs, GL shim, oculusos stub dex, the
timefix OpenXR layer for Proton games (linux-arm64, glibc; the NDK's clang builds it freestanding), the
OculusHMDConnected helper for Rift games under Proton (win-x64 PE; the NDK's clang + lld-link, no Windows SDK), and
rewrites artifacts/SHA256SUMS. Run `frameport parity` afterwards to see which games change.
python native/build.py [--only adapter,bridge,compat,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,ovrpshim,vrsettings] [--ndk PATH]
python native/build.py [--only adapter,bridge,compat,langpack,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,ovrpshim,vrsettings] [--ndk PATH]
"""
from __future__ import annotations
@@ -223,6 +223,15 @@ def build_compat(tc: Path):
"-Wl,--version-script=exports.map", "-o", ART / "arm64-v8a/libovrplatformcompat.so"], cwd=src)
def build_langpack(tc: Path):
"""Language packs from the game's files (see langpack/langpack.c): DT_NEEDED-injected into overport's platform loader."""
src = HERE / "langpack"
run([exe(tc, "aarch64-linux-android29-clang"), "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror",
"-fvisibility=hidden", f"-ffile-prefix-map={src}=native/langpack", "-Wl,--no-undefined",
"-Wl,-z,max-page-size=16384", "-Wl,-soname,libfp_langpack.so", "langpack.c", "-ldl", "-llog",
"-o", ART / "arm64-v8a/libfp_langpack.so"], cwd=src)
def build_glshim(tc: Path):
src = HERE / "glshim"
run([exe(tc, "aarch64-linux-android29-clang"), "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror",
@@ -299,7 +308,7 @@ def write_sums():
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="adapter,bridge,compat,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,ovrpshim,vrsettings")
ap.add_argument("--only", default="adapter,bridge,compat,langpack,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,ovrpshim,vrsettings")
ap.add_argument("--ndk")
args = ap.parse_args()
parts = set(args.only.split(","))
@@ -307,11 +316,12 @@ def main():
(ART / d).mkdir(parents=True, exist_ok=True)
tc = clang_dir(ndk(args.ndk)) if parts - {"dex"} else None
steps = {"adapter": lambda: build_adapter(tc), "bridge": lambda: build_bridge(tc), "compat": lambda: build_compat(tc),
"langpack": lambda: build_langpack(tc),
"glshim": lambda: build_glshim(tc), "xrshim": lambda: build_xrshim(tc), "dex": build_dex, "xrlayer": lambda: build_xrlayer(tc),
"oculushmd": lambda: build_oculushmd(tc), "vkshim": lambda: build_vkshim(tc),
"ovrpshim": lambda: build_ovrpshim(tc),
"vrsettings": lambda: build_vrsettings(tc)}
for name in ("adapter", "bridge", "compat", "glshim", "xrshim", "vkshim", "ovrpshim", "dex", "xrlayer", "oculushmd", "vrsettings"):
for name in ("adapter", "bridge", "compat", "langpack", "glshim", "xrshim", "vkshim", "ovrpshim", "dex", "xrlayer", "oculushmd", "vrsettings"):
if name in parts:
log(f"build {name}")
steps[name]()
+913
View File
@@ -0,0 +1,913 @@
// SPDX-License-Identifier: GPL-3.0-only
//
// FramePort language packs: answers the Meta Platform SDK's language-pack calls from `*.lang` files that already
// sit in the game's data (OBB / app files), without any download.
//
// Why: OVRPort's libovrplatformloader.so is a dispatcher in front of Meta's own loader (…_meta.so). It answers
// ovr_LanguagePack_GetCurrent / ovr_LanguagePack_SetCurrent with `return 0` (request id 0, no message ever comes
// back), so a game that asks for its language pack waits for an answer that never arrives.
//
// How it is wired (patch frame.langpacks):
// * this library becomes the first DT_NEEDED of the dispatcher;
// * the dispatcher's own exports of the functions defined here are marked STB_LOCAL in its .dynsym, so symbol
// lookups (the game's imports and dlsym on the dispatcher's handle) continue to this library;
// * everything we do not answer ourselves is forwarded to the dispatcher's original function, found at run time by
// reading the dispatcher's in-memory .dynsym (the entries are still there, only no longer visible to lookups).
//
// What it implements (see https://developers.meta.com/vr/documentation/native/ps-language-packs/):
// ovr_LanguagePack_GetCurrent / SetCurrent answered here
// ovr_AssetFile_GetList the dispatcher's list + our packs (type "language_pack")
// ovr_AssetFile_StatusById answered here for our packs (always "installed")
// ovr_PopMessage, ovr_FreeMessage, ovr_Message_*, ovr_AssetDetails*_*, ovr_LanguagePackInfo_*,
// ovr_AssetFileDownloadResult_*, ovr_Error_* wrappers: our messages/handles are served here, any other
// handle goes to the dispatcher unchanged
//
// Where the packs are looked for (first file per tag wins; depth <= 3):
// $FRAMEPORT_LANGPACK_DIRS (':'-separated), otherwise
// /sdcard/Android/obb/<pkg>, /sdcard/Android/data/<pkg>/files, the same under /storage/emulated/0, and
// /data/steam_app/obb (where Lepton mounts the host's obb folder)
// A pack is a regular file named <BCP47 tag>.lang (de.lang -> tag "de").
//
// Which pack is "current": the one the game applied with SetCurrent; else $FRAMEPORT_LANGPACK (a tag); else the only
// pack if there is exactly one.
#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <dlfcn.h>
#include <elf.h>
#include <link.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#ifdef __ANDROID__
#include <android/log.h>
#endif
#define EXPORT __attribute__((visibility("default")))
typedef uint64_t u64;
typedef uint32_t u32;
// Log line (logcat tag "fp_langpack" on Android, so it lands in the game's launch.log; on other systems stderr, only
// when $FRAMEPORT_LANGPACK_DEBUG is set).
static void fplog(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void fplog(const char *fmt, ...) {
char line[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(line, sizeof line, fmt, ap);
va_end(ap);
#ifdef __ANDROID__
__android_log_print(ANDROID_LOG_INFO, "fp_langpack", "%s", line);
#else
if (getenv("FRAMEPORT_LANGPACK_DEBUG")) fprintf(stderr, "fp_langpack: %s\n", line);
#endif
}
// accessor calls can repeat every frame: only the first FP_TRACE_MAX are logged
#define FP_TRACE_MAX 400
static int g_traced;
#define fptrace(...) \
do { \
if (__atomic_fetch_add(&g_traced, 1, __ATOMIC_RELAXED) < FP_TRACE_MAX) fplog(__VA_ARGS__); \
} while (0)
// how long the dispatcher gets to answer AssetFile_GetList before we answer with our packs alone
#ifndef FP_LIST_TIMEOUT_MS
#define FP_LIST_TIMEOUT_MS 1500
#endif
#ifndef FP_LOADER_BASENAME
#define FP_LOADER_BASENAME "libovrplatformloader.so"
#endif
// ovrMessageType values (same table as native/platformcompat/message_type.cpp)
#define MSG_ASSETFILE_GETLIST 0x4AFC6F74u
#define MSG_ASSETFILE_STATUSBYID 0x5D955D38u
#define MSG_LANGUAGEPACK_GETCURRENT 0x1F90F0D5u
#define MSG_LANGUAGEPACK_SETCURRENT 0x5B4FBBE0u
#define MAXP 32
#define PATHLEN 1024
#define MAX_DEPTH 3
/* ---------------------------------------------------------------------------------------------------------------
* Finding the dispatcher's original functions
* ------------------------------------------------------------------------------------------------------------- */
typedef struct {
const char *name;
void *addr;
} find_t;
static uintptr_t fixptr(uintptr_t base, uintptr_t v) {
// bionic leaves d_ptr as a link-time address, glibc adds the load bias in place
return v < base ? base + v : v;
}
static size_t count_syms(uintptr_t base, const ElfW(Dyn) *dyn) {
const uint32_t *gnu = NULL, *sysv = NULL;
for (const ElfW(Dyn) *d = dyn; d->d_tag != DT_NULL; d++) {
if (d->d_tag == DT_GNU_HASH) gnu = (const uint32_t *)fixptr(base, d->d_un.d_ptr);
if (d->d_tag == DT_HASH) sysv = (const uint32_t *)fixptr(base, d->d_un.d_ptr);
}
if (sysv) return sysv[1]; // nchain
if (!gnu) return 0;
uint32_t nbuckets = gnu[0], symoffset = gnu[1], bloom_size = gnu[2];
const uint32_t *buckets = gnu + 4 + bloom_size * (sizeof(ElfW(Addr)) / 4);
const uint32_t *chains = buckets + nbuckets;
uint32_t max = 0;
for (uint32_t i = 0; i < nbuckets; i++)
if (buckets[i] > max) max = buckets[i];
if (max < symoffset) return symoffset;
while (!(chains[max - symoffset] & 1)) max++;
return (size_t)max + 1;
}
static int find_cb(struct dl_phdr_info *info, size_t size, void *data) {
(void)size;
find_t *f = (find_t *)data;
const char *n = info->dlpi_name ? info->dlpi_name : "";
const char *slash = strrchr(n, '/');
if (strcmp(slash ? slash + 1 : n, FP_LOADER_BASENAME) != 0) return 0;
uintptr_t base = info->dlpi_addr;
const ElfW(Dyn) *dyn = NULL;
for (int i = 0; i < info->dlpi_phnum; i++)
if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) dyn = (const ElfW(Dyn) *)(base + info->dlpi_phdr[i].p_vaddr);
if (!dyn) return 1;
const ElfW(Sym) *symtab = NULL;
const char *strtab = NULL;
for (const ElfW(Dyn) *d = dyn; d->d_tag != DT_NULL; d++) {
if (d->d_tag == DT_SYMTAB) symtab = (const ElfW(Sym) *)fixptr(base, d->d_un.d_ptr);
if (d->d_tag == DT_STRTAB) strtab = (const char *)fixptr(base, d->d_un.d_ptr);
}
size_t n_syms = count_syms(base, dyn);
if (!symtab || !strtab || !n_syms) return 1;
for (size_t i = 1; i < n_syms; i++) {
const ElfW(Sym) *s = &symtab[i];
if (s->st_shndx == SHN_UNDEF || s->st_value == 0) continue;
if (ELF64_ST_TYPE(s->st_info) != STT_FUNC) continue;
if (strcmp(strtab + s->st_name, f->name) == 0) {
f->addr = (void *)(base + s->st_value);
break;
}
}
return 1;
}
static void *orig_sym(const char *name) {
find_t f = {name, NULL};
dl_iterate_phdr(find_cb, &f);
return f.addr;
}
// o_<Name>(...) calls the dispatcher's original ovr_<Name>; 0/NULL when it has none
#define DEFORIG(RET, NAME, PARAMS, ARGS) \
static RET o_##NAME PARAMS { \
typedef RET(*fn_t) PARAMS; \
static fn_t f; \
static int tried; \
if (!tried) { \
f = (fn_t)orig_sym("ovr_" #NAME); \
tried = 1; \
} \
return f ? f ARGS : (RET)0; \
}
DEFORIG(void *, PopMessage, (void), ())
DEFORIG(void, FreeMessage, (void *m), (m))
DEFORIG(u32, Message_GetType, (const void *m), (m))
DEFORIG(u64, Message_GetRequestID, (const void *m), (m))
DEFORIG(_Bool, Message_IsError, (const void *m), (m))
DEFORIG(void *, Message_GetError, (const void *m), (m))
DEFORIG(void *, Message_GetAssetDetails, (const void *m), (m))
DEFORIG(void *, Message_GetAssetDetailsArray, (const void *m), (m))
DEFORIG(void *, Message_GetAssetFileDownloadResult, (const void *m), (m))
DEFORIG(size_t, AssetDetailsArray_GetSize, (const void *a), (a))
DEFORIG(void *, AssetDetailsArray_GetElement, (const void *a, size_t i), (a, i))
DEFORIG(u64, AssetDetails_GetAssetId, (const void *d), (d))
DEFORIG(const char *, AssetDetails_GetAssetType, (const void *d), (d))
DEFORIG(const char *, AssetDetails_GetDownloadStatus, (const void *d), (d))
DEFORIG(const char *, AssetDetails_GetFilepath, (const void *d), (d))
DEFORIG(const char *, AssetDetails_GetIapStatus, (const void *d), (d))
DEFORIG(void *, AssetDetails_GetLanguage, (const void *d), (d))
DEFORIG(const char *, AssetDetails_GetMetadata, (const void *d), (d))
DEFORIG(const char *, LanguagePackInfo_GetTag, (const void *l), (l))
DEFORIG(const char *, LanguagePackInfo_GetEnglishName, (const void *l), (l))
DEFORIG(const char *, LanguagePackInfo_GetNativeName, (const void *l), (l))
DEFORIG(u64, AssetFileDownloadResult_GetAssetId, (const void *r), (r))
DEFORIG(const char *, AssetFileDownloadResult_GetFilepath, (const void *r), (r))
DEFORIG(u64, AssetFile_GetList, (void), ())
DEFORIG(u64, AssetFile_StatusById, (u64 id), (id))
DEFORIG(int, Error_GetCode, (const void *e), (e))
DEFORIG(int, Error_GetHttpCode, (const void *e), (e))
DEFORIG(const char *, Error_GetMessage, (const void *e), (e))
DEFORIG(const char *, Error_GetDisplayableMessage, (const void *e), (e))
/* ---------------------------------------------------------------------------------------------------------------
* Finding the packs
* ------------------------------------------------------------------------------------------------------------- */
typedef struct {
char tag[48];
char path[PATHLEN];
u64 id;
} pack_t;
static const struct {
const char *tag, *en, *native;
} NAMES[] = {
{"en", "English", "English"}, {"de", "German", "Deutsch"}, {"fr", "French", "Français"},
{"es", "Spanish", "Español"}, {"it", "Italian", "Italiano"}, {"pt", "Portuguese", "Português"},
{"nl", "Dutch", "Nederlands"}, {"pl", "Polish", "Polski"}, {"ru", "Russian", "Русский"},
{"tr", "Turkish", "Türkçe"}, {"ja", "Japanese", "日本語"}, {"ko", "Korean", "한국어"},
{"zh", "Chinese", "中文"}, {"ar", "Arabic", "العربية"}, {"cs", "Czech", "Čeština"},
{"sv", "Swedish", "Svenska"}, {"da", "Danish", "Dansk"}, {"fi", "Finnish", "Suomi"},
{"nb", "Norwegian", "Norsk"}, {"hu", "Hungarian", "Magyar"}, {"uk", "Ukrainian", "Українська"},
{"el", "Greek", "Ελληνικά"}, {"he", "Hebrew", "עברית"}, {"th", "Thai", "ไทย"},
{"id", "Indonesian", "Indonesia"}, {"vi", "Vietnamese", "Tiếng Việt"}, {"ro", "Romanian", "Română"},
};
static u64 hash_tag(const char *tag) {
u64 h = 1469598103934665603ULL; // FNV-1a over the lower-case tag
for (const char *p = tag; *p; p++) {
h ^= (unsigned char)((*p >= 'A' && *p <= 'Z') ? *p + 32 : *p);
h *= 1099511628211ULL;
}
return 0x4650000000000000ULL | (h & 0x0000FFFFFFFFFFFFULL); // 'FP' prefix: never a store asset id
}
static int tag_eq(const char *a, const char *b) { return strcasecmp(a, b) == 0; }
static int base_len(const char *tag) {
int n = 0;
while (tag[n] && tag[n] != '-' && tag[n] != '_') n++;
return n;
}
static int valid_tag(const char *t) {
if (!*t) return 0;
for (; *t; t++)
if (!((*t >= 'a' && *t <= 'z') || (*t >= 'A' && *t <= 'Z') || (*t >= '0' && *t <= '9') || *t == '-' ||
*t == '_'))
return 0;
return 1;
}
static void add_pack(pack_t *out, int *n, const char *tag, const char *path) {
for (int i = 0; i < *n; i++)
if (tag_eq(out[i].tag, tag)) return; // first one wins
pack_t *p = &out[(*n)++];
snprintf(p->tag, sizeof p->tag, "%s", tag);
snprintf(p->path, sizeof p->path, "%s", path);
p->id = hash_tag(tag);
}
static int g_logged_dirs;
// Tags to leave out of the list (comma separated, case-insensitive): env FRAMEPORT_LANGPACK_SKIP, plus the lines
// of a file "fp_langpack_skip" in any scanned folder. For finding out which pack a game needs reported: e.g. a game
// whose built-in language works without being a "pack".
static __thread char g_skip[160]; // per thread: scans may run on several game threads at once
static void read_skip_file(const char *dir) {
char path[PATHLEN], line[160];
if (snprintf(path, sizeof path, "%s/fp_langpack_skip", dir) >= (int)sizeof path) return;
FILE *f = fopen(path, "r");
if (!f) return;
size_t n = fread(line, 1, sizeof line - 1, f);
fclose(f);
line[n] = 0;
for (char *c = line; *c; c++)
if (*c == '\n' || *c == '\r' || *c == ' ') *c = ',';
size_t have = strlen(g_skip), room = sizeof g_skip - have;
if (room > 3) snprintf(g_skip + have, room, ",%.*s,", (int)room - 3, line);
}
static int skipped(const char *tag) {
char want[64], have[sizeof g_skip + 2];
snprintf(want, sizeof want, ",%s,", tag);
snprintf(have, sizeof have, ",%s,%s", getenv("FRAMEPORT_LANGPACK_SKIP") ? getenv("FRAMEPORT_LANGPACK_SKIP") : "",
g_skip);
for (char *c = want; *c; c++) *c = (char)tolower((unsigned char)*c);
for (char *c = have; *c; c++) *c = (char)tolower((unsigned char)*c);
return strstr(have, want) != NULL;
}
static void scan_dir(const char *dir, int depth, pack_t *out, int *n) {
DIR *d = opendir(dir);
if (d && depth == 0) read_skip_file(dir);
if (!g_logged_dirs && depth == 0) fplog("looking in %s: %s", dir, d ? "found" : "not readable");
if (!d) return;
struct dirent *e;
while (*n < MAXP && (e = readdir(d)) != NULL) {
if (e->d_name[0] == '.') continue;
char path[PATHLEN];
if (snprintf(path, sizeof path, "%s/%s", dir, e->d_name) >= (int)sizeof path) continue;
struct stat st;
if (stat(path, &st) != 0) continue;
if (S_ISDIR(st.st_mode)) {
if (depth < MAX_DEPTH) scan_dir(path, depth + 1, out, n);
} else if (S_ISREG(st.st_mode)) {
size_t len = strlen(e->d_name);
if (len > 5 && strcasecmp(e->d_name + len - 5, ".lang") == 0) {
char tag[48];
if (len - 5 >= sizeof tag) continue;
memcpy(tag, e->d_name, len - 5);
tag[len - 5] = 0;
if (valid_tag(tag) && !skipped(tag)) add_pack(out, n, tag, path);
}
}
}
closedir(d);
}
static void package_name(char *out, size_t cap) {
out[0] = 0;
FILE *f = fopen("/proc/self/cmdline", "r");
if (!f) return;
size_t n = fread(out, 1, cap - 1, f);
fclose(f);
out[n] = 0; // argv[0] ends at the first NUL: the package (or package:process)
char *colon = strchr(out, ':');
if (colon) *colon = 0;
}
static int scan_dirs(pack_t *out);
static int scan(pack_t *out) {
int n = scan_dirs(out);
static int last = -1;
if (n != last) {
last = n;
fplog("%d language pack(s) found", n);
for (int i = 0; i < n; i++) fplog(" pack %s -> %s", out[i].tag, out[i].path);
}
g_logged_dirs = 1;
return n;
}
static int scan_dirs(pack_t *out) {
int n = 0;
g_skip[0] = 0; // read again from the folders below
const char *dirs = getenv("FRAMEPORT_LANGPACK_DIRS");
if (dirs && *dirs) {
char buf[PATHLEN * 2];
snprintf(buf, sizeof buf, "%s", dirs);
for (char *save = NULL, *p = strtok_r(buf, ":", &save); p; p = strtok_r(NULL, ":", &save)) scan_dir(p, 0, out, &n);
return n;
}
char pkg[256];
package_name(pkg, sizeof pkg);
if (!g_logged_dirs) fplog("package \"%s\"", pkg);
if (!pkg[0] || strchr(pkg, '/')) return 0;
// Unreal names the files of an Android game by their /storage/emulated/0 path (its own OBB mount does), so that
// spelling comes first: a pack found in both gets the path the engine would use itself.
static const char *const FORMATS[] = {"/storage/emulated/0/Android/obb/%s",
"/storage/emulated/0/Android/data/%s/files", "/sdcard/Android/obb/%s",
"/sdcard/Android/data/%s/files"};
for (size_t i = 0; i < sizeof FORMATS / sizeof *FORMATS; i++) {
char dir[PATHLEN];
snprintf(dir, sizeof dir, FORMATS[i], pkg);
scan_dir(dir, 0, out, &n);
}
// Lepton mounts the host's <app>/lepton-app/obb here (read-only) and only links /sdcard/Android/obb/<pkg> to it
// at boot (liblepton/mounting.sh: podman_mount_entry "$LEPTON_MOUNT_OBB_DIR" "/$APP_MOUNT_TARGET/obb", default
// APP_MOUNT_TARGET=data/steam_app), so look there too.
scan_dir("/data/steam_app/obb", 0, out, &n);
return n;
}
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static char g_current[48]; // tag the game applied with SetCurrent
static int find_tag(const pack_t *p, int n, const char *tag) {
for (int i = 0; i < n; i++)
if (tag_eq(p[i].tag, tag)) return i;
int bl = base_len(tag); // "de-DE" -> "de" (and the reverse: "de" asked, "de-de" present)
for (int i = 0; i < n; i++)
if (base_len(p[i].tag) == bl && strncasecmp(p[i].tag, tag, (size_t)bl) == 0) return i;
return -1;
}
static int pick_current(const pack_t *p, int n) {
char want[48] = "";
pthread_mutex_lock(&g_lock);
snprintf(want, sizeof want, "%s", g_current);
pthread_mutex_unlock(&g_lock);
if (want[0]) {
int i = find_tag(p, n, want);
if (i >= 0) return i;
}
const char *env = getenv("FRAMEPORT_LANGPACK");
if (env && *env) {
int i = find_tag(p, n, env);
if (i >= 0) return i;
}
return n == 1 ? 0 : -1;
}
/* ---------------------------------------------------------------------------------------------------------------
* Messages and handles. Every object we hand out lives inside one msg_t, so "is this handle ours" is an address
* range check against the live messages.
* ------------------------------------------------------------------------------------------------------------- */
// The asset's Metadata. Deadpool VR (Unreal) only accepts a language pack whose Metadata equals its own version string
// ("1.0.40.356975.Quest", built from five parts with "%s.%s.%s.%s.%s"), which Meta's store sets at upload. The
// patch writes the game's versionName behind the marker below (frame.langpacks, frameport.patches.frame.langpack);
// FRAMEPORT_LANGPACK_META overrides it. Without either the Metadata stays empty, as before.
#define META_LEN 96
#define META_MARK "@FPMETA@"
__attribute__((used)) static char g_meta_slot[sizeof META_MARK + META_LEN] = META_MARK;
static void pack_meta(char *out) {
const char *env = getenv("FRAMEPORT_LANGPACK_META");
const volatile char *slot = g_meta_slot + sizeof META_MARK;
out[0] = 0;
if (env && *env) snprintf(out, META_LEN, "%s", env);
else {
int i = 0;
for (; i < META_LEN - 1 && slot[i]; i++) out[i] = slot[i];
out[i] = 0;
}
}
typedef struct {
char tag[48], en[64], nat[64];
} lang_t;
typedef struct {
u64 id;
char type[16], status[16], iap[8], meta[META_LEN];
char path[PATHLEN];
lang_t *lang;
} details_t;
typedef struct {
u64 id;
char path[PATHLEN];
} result_t;
typedef struct {
int code, http;
char msg[128];
} err_t;
typedef struct msg {
struct msg *all_next, *q_next;
u32 type;
u64 req;
int is_error, has_det, has_res;
err_t err;
details_t det;
lang_t lng;
result_t res;
u32 arr; // its address is the handle of the details array
int n;
details_t dets[MAXP];
lang_t langs[MAXP];
void *orig_msg, *orig_arr;
size_t orig_n;
} msg_t;
static msg_t *g_all, *g_qhead, *g_qtail;
static u64 g_next_req = 0x4650000000000001ULL;
#define MAX_PENDING 16
static u64 g_pending[MAX_PENDING];
static u64 g_pending_ms[MAX_PENDING];
static u64 g_expired[MAX_PENDING]; // requests we answered ourselves after the timeout: their late answer is dropped
static int g_expired_next; // when each one was asked // dispatcher requests whose AssetFile_GetList answer we extend
static msg_t *owner(const void *p) {
msg_t *found = NULL;
pthread_mutex_lock(&g_lock);
for (msg_t *m = g_all; m; m = m->all_next)
if ((const char *)p >= (const char *)m && (const char *)p < (const char *)m + sizeof *m) {
found = m;
break;
}
pthread_mutex_unlock(&g_lock);
return found;
}
static msg_t *new_msg(u32 type, u64 req) {
msg_t *m = (msg_t *)calloc(1, sizeof *m);
if (!m) return NULL;
m->type = type;
m->req = req ? req : __atomic_fetch_add(&g_next_req, 1, __ATOMIC_RELAXED);
pthread_mutex_lock(&g_lock);
m->all_next = g_all;
g_all = m;
pthread_mutex_unlock(&g_lock);
return m;
}
static void post(msg_t *m) {
pthread_mutex_lock(&g_lock);
m->q_next = NULL;
if (g_qtail) g_qtail->q_next = m;
else g_qhead = m;
g_qtail = m;
pthread_mutex_unlock(&g_lock);
}
static void fail(msg_t *m, int code, const char *text) {
m->is_error = 1;
m->err.code = code;
snprintf(m->err.msg, sizeof m->err.msg, "%s", text);
}
static void fill_details(details_t *d, lang_t *l, const pack_t *p) {
d->id = p->id;
snprintf(d->type, sizeof d->type, "language_pack");
snprintf(d->status, sizeof d->status, "installed");
snprintf(d->iap, sizeof d->iap, "free");
snprintf(d->path, sizeof d->path, "%s", p->path);
pack_meta(d->meta);
snprintf(l->tag, sizeof l->tag, "%s", p->tag);
snprintf(l->en, sizeof l->en, "%s", p->tag);
snprintf(l->nat, sizeof l->nat, "%s", p->tag);
int bl = base_len(p->tag);
for (size_t i = 0; i < sizeof NAMES / sizeof *NAMES; i++)
if ((int)strlen(NAMES[i].tag) == bl && strncasecmp(NAMES[i].tag, p->tag, (size_t)bl) == 0) {
snprintf(l->en, sizeof l->en, "%s", NAMES[i].en);
snprintf(l->nat, sizeof l->nat, "%s", NAMES[i].native);
break;
}
d->lang = l;
}
static u64 now_ms(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (u64)t.tv_sec * 1000u + (u64)t.tv_nsec / 1000000u;
}
static int take_pending(u64 req) {
int hit = 0;
pthread_mutex_lock(&g_lock);
for (int i = 0; i < MAX_PENDING; i++)
if (g_pending[i] == req) {
g_pending[i] = 0;
hit = 1;
break;
}
pthread_mutex_unlock(&g_lock);
return hit;
}
static int take_expired(u64 req) {
int hit = 0;
pthread_mutex_lock(&g_lock);
for (int i = 0; i < MAX_PENDING; i++)
if (req && g_expired[i] == req) {
g_expired[i] = 0;
hit = 1;
break;
}
pthread_mutex_unlock(&g_lock);
return hit;
}
static void add_pending(u64 req) {
pthread_mutex_lock(&g_lock);
for (int i = 0; i < MAX_PENDING; i++)
if (!g_pending[i]) {
g_pending[i] = req;
g_pending_ms[i] = now_ms();
break;
}
pthread_mutex_unlock(&g_lock);
}
static void fill_list(msg_t *m, const pack_t *p, int n) {
for (int i = 0; i < n && i < MAXP; i++) fill_details(&m->dets[i], &m->langs[i], &p[i]);
m->n = n < MAXP ? n : MAXP;
}
// The dispatcher's AssetFile_GetList answer arrived: ours + theirs in one array.
static void *wrap_list(void *orig) {
pack_t packs[MAXP];
int n = scan(packs);
if (n == 0) return orig;
msg_t *m = new_msg(MSG_ASSETFILE_GETLIST, o_Message_GetRequestID(orig));
if (!m) return orig;
fill_list(m, packs, n);
m->orig_msg = orig;
if (!o_Message_IsError(orig)) {
m->orig_arr = o_Message_GetAssetDetailsArray(orig);
if (m->orig_arr) m->orig_n = o_AssetDetailsArray_GetSize(m->orig_arr);
}
return m;
}
// A GetList the dispatcher has not answered within FP_LIST_TIMEOUT_MS: answer with our packs alone (request id kept).
// Returns NULL if nothing is overdue or no pack exists (then a late answer from the dispatcher still reaches the
// game); once we answered, the dispatcher's late answer is dropped (ovr_PopMessage), so the game gets one answer.
static msg_t *expire_pending(void) {
u64 req = 0, now = now_ms();
pthread_mutex_lock(&g_lock);
for (int i = 0; i < MAX_PENDING; i++)
if (g_pending[i] && now - g_pending_ms[i] >= FP_LIST_TIMEOUT_MS) {
req = g_pending[i];
g_pending[i] = 0;
break;
}
pthread_mutex_unlock(&g_lock);
if (!req) return NULL;
pack_t packs[MAXP];
int n = scan(packs);
fplog("AssetFile_GetList %llu: no answer after %d ms, answering with %d pack(s)", (unsigned long long)req,
FP_LIST_TIMEOUT_MS, n);
if (n == 0) return NULL;
msg_t *m = new_msg(MSG_ASSETFILE_GETLIST, req);
if (!m) return NULL;
fill_list(m, packs, n);
pthread_mutex_lock(&g_lock);
g_expired[g_expired_next] = req;
g_expired_next = (g_expired_next + 1) % MAX_PENDING;
pthread_mutex_unlock(&g_lock);
return m;
}
/* ---------------------------------------------------------------------------------------------------------------
* Requests
* ------------------------------------------------------------------------------------------------------------- */
EXPORT u64 ovr_LanguagePack_GetCurrent(void) {
pack_t packs[MAXP];
int n = scan(packs), i = pick_current(packs, n);
fplog("LanguagePack_GetCurrent -> %s", i >= 0 ? packs[i].tag : "none applied");
msg_t *m = new_msg(MSG_LANGUAGEPACK_GETCURRENT, 0);
if (!m) return 0;
u64 req = m->req;
if (i < 0) {
fail(m, 404, "no language pack is applied");
} else {
fill_details(&m->det, &m->lng, &packs[i]);
m->has_det = 1;
}
post(m);
return req;
}
EXPORT u64 ovr_LanguagePack_SetCurrent(const char *tag) {
pack_t packs[MAXP];
int n = scan(packs), i = (tag && *tag) ? find_tag(packs, n, tag) : -1;
fplog("LanguagePack_SetCurrent(\"%s\") -> %s", tag ? tag : "(null)", i >= 0 ? packs[i].path : "not available");
msg_t *m = new_msg(MSG_LANGUAGEPACK_SETCURRENT, 0);
if (!m) return 0;
u64 req = m->req;
if (i < 0) {
fail(m, 404, "language pack not available on this device");
} else {
pthread_mutex_lock(&g_lock);
snprintf(g_current, sizeof g_current, "%s", packs[i].tag);
pthread_mutex_unlock(&g_lock);
m->res.id = packs[i].id;
snprintf(m->res.path, sizeof m->res.path, "%s", packs[i].path);
m->has_res = 1;
}
post(m);
return req;
}
EXPORT u64 ovr_AssetFile_GetList(void) {
u64 req = o_AssetFile_GetList();
fplog("AssetFile_GetList (dispatcher request %llu)", (unsigned long long)req);
if (req) {
add_pending(req);
return req;
}
// no dispatcher function behind us: answer with our packs alone
pack_t packs[MAXP];
int n = scan(packs);
msg_t *m = new_msg(MSG_ASSETFILE_GETLIST, 0);
if (!m) return 0;
req = m->req;
fill_list(m, packs, n);
post(m);
return req;
}
EXPORT u64 ovr_AssetFile_StatusById(u64 id) {
fplog("AssetFile_StatusById(%llu)%s", (unsigned long long)id, (id >> 48) == 0x4650 ? " (ours)" : "");
if ((id >> 48) == 0x4650) {
pack_t packs[MAXP];
int n = scan(packs);
for (int i = 0; i < n; i++)
if (packs[i].id == id) {
msg_t *m = new_msg(MSG_ASSETFILE_STATUSBYID, 0);
if (!m) return 0;
u64 req = m->req;
fill_details(&m->det, &m->lng, &packs[i]);
m->has_det = 1;
post(m);
return req;
}
msg_t *m = new_msg(MSG_ASSETFILE_STATUSBYID, 0);
if (!m) return 0;
u64 req = m->req;
fail(m, 404, "asset file not found");
post(m);
return req;
}
return o_AssetFile_StatusById(id);
}
/* ---------------------------------------------------------------------------------------------------------------
* Message loop
* ------------------------------------------------------------------------------------------------------------- */
EXPORT void *ovr_PopMessage(void) {
pthread_mutex_lock(&g_lock);
msg_t *m = g_qhead;
if (m) {
g_qhead = m->q_next;
if (!g_qhead) g_qtail = NULL;
m->q_next = NULL;
}
pthread_mutex_unlock(&g_lock);
if (m) return m;
void *o = o_PopMessage();
while (o && o_Message_GetType(o) == MSG_ASSETFILE_GETLIST && take_expired(o_Message_GetRequestID(o))) {
// we already answered this request (timeout): a second answer for the same request would reach the game twice
fplog("AssetFile_GetList %llu: late answer from the dispatcher dropped", (unsigned long long)o_Message_GetRequestID(o));
o_FreeMessage(o);
o = o_PopMessage();
}
if (o && o_Message_GetType(o) == MSG_ASSETFILE_GETLIST) {
u64 r = o_Message_GetRequestID(o);
if (take_pending(r)) {
fplog("AssetFile_GetList %llu answered by the dispatcher", (unsigned long long)r);
return wrap_list(o);
}
}
if (o) return o;
return expire_pending();
}
EXPORT void ovr_FreeMessage(void *h) {
msg_t *m = h ? owner(h) : NULL;
if (!m || (void *)m != h) {
o_FreeMessage(h);
return;
}
pthread_mutex_lock(&g_lock);
for (msg_t **pp = &g_all; *pp; pp = &(*pp)->all_next)
if (*pp == m) {
*pp = m->all_next;
break;
}
for (msg_t **pp = &g_qhead; *pp; pp = &(*pp)->q_next) // freed unpopped: leave the queue too
if (*pp == m) {
*pp = m->q_next;
break;
}
g_qtail = NULL;
for (msg_t *q = g_qhead; q; q = q->q_next) g_qtail = q;
pthread_mutex_unlock(&g_lock);
if (m->orig_msg) o_FreeMessage(m->orig_msg);
free(m);
}
EXPORT u32 ovr_Message_GetType(const void *h) {
msg_t *m = owner(h);
u32 t = m ? m->type : o_Message_GetType(h);
if (m) fptrace("Message_GetType(ours) = 0x%08X", t);
return t;
}
EXPORT u64 ovr_Message_GetRequestID(const void *h) {
msg_t *m = owner(h);
return m ? m->req : o_Message_GetRequestID(h);
}
EXPORT _Bool ovr_Message_IsError(const void *h) {
msg_t *m = owner(h);
return m ? (_Bool)m->is_error : o_Message_IsError(h);
}
EXPORT void *ovr_Message_GetError(const void *h) {
msg_t *m = owner(h);
if (!m) return o_Message_GetError(h);
return m->is_error ? (void *)&m->err : NULL;
}
EXPORT void *ovr_Message_GetAssetDetails(const void *h) {
msg_t *m = owner(h);
if (!m) return o_Message_GetAssetDetails(h);
return m->has_det ? (void *)&m->det : NULL;
}
EXPORT void *ovr_Message_GetAssetFileDownloadResult(const void *h) {
msg_t *m = owner(h);
if (!m) return o_Message_GetAssetFileDownloadResult(h);
return m->has_res ? (void *)&m->res : NULL;
}
EXPORT void *ovr_Message_GetAssetDetailsArray(const void *h) {
msg_t *m = owner(h);
if (!m) return o_Message_GetAssetDetailsArray(h);
fptrace("Message_GetAssetDetailsArray(ours)");
return m->type == MSG_ASSETFILE_GETLIST && !m->is_error ? (void *)&m->arr : NULL;
}
EXPORT size_t ovr_AssetDetailsArray_GetSize(const void *h) {
msg_t *m = owner(h);
size_t n = m ? (size_t)m->n + m->orig_n : o_AssetDetailsArray_GetSize(h);
if (m) fptrace("AssetDetailsArray_GetSize = %zu (%d ours + %zu dispatcher)", n, m->n, (size_t)m->orig_n);
return n;
}
EXPORT void *ovr_AssetDetailsArray_GetElement(const void *h, size_t i) {
msg_t *m = owner(h);
if (!m) return o_AssetDetailsArray_GetElement(h, i);
if (i < (size_t)m->n) {
fptrace("AssetDetailsArray_GetElement(%zu) = our pack %s", i, m->dets[i].lang ? m->dets[i].lang->tag : "?");
return &m->dets[i];
}
fptrace("AssetDetailsArray_GetElement(%zu) = dispatcher entry", i);
return m->orig_arr ? o_AssetDetailsArray_GetElement(m->orig_arr, i - (size_t)m->n) : NULL;
}
/* ---------------------------------------------------------------------------------------------------------------
* Accessors on our own objects (anything else goes to the dispatcher)
* ------------------------------------------------------------------------------------------------------------- */
#define IS_OURS(h) (owner(h) != NULL)
EXPORT u64 ovr_AssetDetails_GetAssetId(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetAssetId(h);
fptrace("AssetDetails_GetAssetId(ours) = %llu", (unsigned long long)((const details_t *)h)->id);
return ((const details_t *)h)->id;
}
EXPORT const char *ovr_AssetDetails_GetAssetType(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetAssetType(h);
fptrace("AssetDetails_GetAssetType(ours) = \"%s\"", ((const details_t *)h)->type);
return ((const details_t *)h)->type;
}
EXPORT const char *ovr_AssetDetails_GetDownloadStatus(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetDownloadStatus(h);
fptrace("AssetDetails_GetDownloadStatus(ours) = \"%s\"", ((const details_t *)h)->status);
return ((const details_t *)h)->status;
}
EXPORT const char *ovr_AssetDetails_GetFilepath(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetFilepath(h);
fptrace("AssetDetails_GetFilepath(ours) = \"%s\"", ((const details_t *)h)->path);
return ((const details_t *)h)->path;
}
EXPORT const char *ovr_AssetDetails_GetIapStatus(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetIapStatus(h);
fptrace("AssetDetails_GetIapStatus(ours) = \"%s\"", ((const details_t *)h)->iap);
return ((const details_t *)h)->iap;
}
EXPORT void *ovr_AssetDetails_GetLanguage(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetLanguage(h);
fptrace("AssetDetails_GetLanguage(ours)");
return (void *)((const details_t *)h)->lang;
}
EXPORT const char *ovr_AssetDetails_GetMetadata(const void *h) {
if (!IS_OURS(h)) return o_AssetDetails_GetMetadata(h);
fptrace("AssetDetails_GetMetadata(ours) = \"%s\"", ((const details_t *)h)->meta);
return ((const details_t *)h)->meta;
}
EXPORT const char *ovr_LanguagePackInfo_GetTag(const void *h) {
if (!IS_OURS(h)) return o_LanguagePackInfo_GetTag(h);
fptrace("LanguagePackInfo_GetTag(ours) = \"%s\"", ((const lang_t *)h)->tag);
return ((const lang_t *)h)->tag;
}
EXPORT const char *ovr_LanguagePackInfo_GetEnglishName(const void *h) {
if (!IS_OURS(h)) return o_LanguagePackInfo_GetEnglishName(h);
fptrace("LanguagePackInfo_GetEnglishName(ours) = \"%s\"", ((const lang_t *)h)->en);
return ((const lang_t *)h)->en;
}
EXPORT const char *ovr_LanguagePackInfo_GetNativeName(const void *h) {
if (!IS_OURS(h)) return o_LanguagePackInfo_GetNativeName(h);
fptrace("LanguagePackInfo_GetNativeName(ours) = \"%s\"", ((const lang_t *)h)->nat);
return ((const lang_t *)h)->nat;
}
EXPORT u64 ovr_AssetFileDownloadResult_GetAssetId(const void *h) {
return IS_OURS(h) ? ((const result_t *)h)->id : o_AssetFileDownloadResult_GetAssetId(h);
}
EXPORT const char *ovr_AssetFileDownloadResult_GetFilepath(const void *h) {
return IS_OURS(h) ? ((const result_t *)h)->path : o_AssetFileDownloadResult_GetFilepath(h);
}
EXPORT int ovr_Error_GetCode(const void *h) { return IS_OURS(h) ? ((const err_t *)h)->code : o_Error_GetCode(h); }
EXPORT int ovr_Error_GetHttpCode(const void *h) { return IS_OURS(h) ? ((const err_t *)h)->http : o_Error_GetHttpCode(h); }
EXPORT const char *ovr_Error_GetMessage(const void *h) {
return IS_OURS(h) ? ((const err_t *)h)->msg : o_Error_GetMessage(h);
}
EXPORT const char *ovr_Error_GetDisplayableMessage(const void *h) {
return IS_OURS(h) ? ((const err_t *)h)->msg : o_Error_GetDisplayableMessage(h);
}
+1 -1
View File
@@ -1,2 +1,2 @@
# The FramePort version: the single source (pyproject reads it via hatch; CI checks a release tag matches it).
__version__ = "0.7.0"
__version__ = "0.7.2"
+1 -1
View File
@@ -247,7 +247,7 @@ def missing_ovr_symbols(lib_bytes: dict[str, bytes]) -> set[str]:
return set()
exported = set(elf.dyn_symbols(loader, True))
linked = set(elf.needed(loader))
for extra in ("libovrplatformcompat.so", "libovrstubs.so"):
for extra in ("libovrplatformcompat.so", "libovrstubs.so", "libfp_langpack.so"):
if extra in lib_bytes and extra in linked: # only counts when the loader loads it (a lone file doesn't help)
exported |= elf.dyn_symbols(lib_bytes[extra], True)
wanted = set()
+23
View File
@@ -106,6 +106,29 @@ def replace_rodata_string(data: bytes, old: str, new: str) -> tuple[bytes, int]:
return bytes(buf), count
def hide_exports(data: bytes, names) -> tuple[bytes, list[str]]:
"""Make the exported functions `names` invisible to symbol lookup without removing them: their .dynsym entries
become STB_LOCAL (name, value and section stay, nothing moves, the hash tables are untouched). Both bionic's and
glibc's lookups only match GLOBAL/WEAK entries, so a lookup for such a name (a game's import, or dlsym on this
library's handle) goes on to the next library in the dependency list; code that reads the library's own .dynsym
(native/langpack) still finds the original address. Returns (data, names actually hidden); ELF64 only."""
if not is_elf(data) or not is_64bit(data) or data[5] != 1:
return data, []
sec = _elf(data).get_section_by_name(".dynsym")
if not isinstance(sec, SymbolTableSection):
return data, []
wanted = set(names)
entsize, start = sec["sh_entsize"] or 24, sec["sh_offset"]
buf, hidden = bytearray(data), []
for i, sym in enumerate(sec.iter_symbols()):
if (sym.name in wanted and sym["st_shndx"] != "SHN_UNDEF"
and sym["st_info"]["bind"] in ("STB_GLOBAL", "STB_WEAK")):
at = start + i * entsize + 4 # Elf64_Sym.st_info: binding in the high nibble, type in the low one
buf[at] &= 0x0F
hidden.append(sym.name)
return bytes(buf), sorted(hidden)
def add_needed(data: bytes, library: str) -> bytes:
"""Add a DT_NEEDED entry in front of the existing ones (same effect as `patchelf --add-needed`; being first matters
for symbol interposition, e.g. the GL shim must precede libEGL).
+28
View File
@@ -0,0 +1,28 @@
"""Language packs (`<BCP47 tag>.lang`) in a game's data folder (OBB / app files); see native/langpack."""
from __future__ import annotations
import os
import re
from pathlib import Path
MAX_DEPTH = 3 # same depth as the runtime scan in native/langpack/langpack.c
TAG = re.compile(r"^[A-Za-z0-9_-]+$")
def find_tags(data_dir: Path | str | None) -> list[str]:
"""Tags of the language packs below `data_dir` (de.lang -> "de"), sorted, first file per tag."""
if not data_dir:
return []
root = Path(data_dir)
if not root.is_dir():
return []
seen: dict[str, str] = {}
base_depth = len(root.parts)
for folder, dirs, files in os.walk(root):
if len(Path(folder).parts) - base_depth >= MAX_DEPTH:
dirs[:] = []
for name in files:
stem, dot, ext = name.rpartition(".")
if dot and ext.lower() == "lang" and TAG.match(stem):
seen.setdefault(stem.lower(), stem)
return sorted(seen.values(), key=str.lower)
+2 -1
View File
@@ -76,7 +76,8 @@ def steam_set(package: str, title: str = "", apk: str | Path | None = None) -> d
title = title or package
out_dir = fetch.artwork_dir(package) / "steam"
out_dir.mkdir(parents=True, exist_ok=True)
placeholder = not (set(src) - {"icon"}) # no store art (at most the APK's icon): the name on a coloured tile
# no store art (at most the APK's icon; the GUI's generated cover/banner don't count): the name on a coloured tile
placeholder = not (set(src) & (STORE_KINDS | {"shot"}))
parts = [f"{k}:{p.stat().st_size}:{p.stat().st_mtime_ns}" for k, p in sorted(src.items())]
if placeholder:
parts.append(f"placeholder:{PLACEHOLDER_VERSION}:{title}:{apk or ''}")
+17
View File
@@ -58,6 +58,8 @@ def _follow_catalog(data: dict) -> bool:
settings["recipes.app_version"] = __version__
for pkg, g in (data.get("games") or {}).items():
r, a = g.get("recipe"), g.get("analysis")
if app_updated and isinstance(a, dict):
changed |= _refresh_data_fields(g, a)
if not isinstance(r, dict) or not isinstance(a, dict) or r.get("source") == "user":
continue
entry = catalog.lookup(pkg)
@@ -71,6 +73,21 @@ def _follow_catalog(data: dict) -> bool:
return changed
def _refresh_data_fields(g: dict, a: dict) -> bool:
"""Analysis fields read from the game's data folder (cheap, no APK analysis) that newer FramePort versions added:
filled in for games already in the library, so their patches are offered without a re-analysis."""
extra = a.setdefault("extra", {})
if "lang_packs" in extra or a.get("package", "").startswith("rift."):
return False
from ..analysis import langpacks
try:
extra["lang_packs"] = langpacks.find_tags(g.get("data_dir"))
except OSError:
return False
return True
def _migrate(data: dict) -> bool:
"""One-time updates of stored recipes when a new default is introduced (each runs once per library)."""
done = data.setdefault("settings", {}).setdefault("migrations", [])
+11
View File
@@ -132,6 +132,7 @@
"Automatic SteamVR performance settings (this PC)": "",
"Back to library": "",
"Back up the signing keys ({len}) to {shown_dir} first": "",
"Before a swapchain image is handed to the Frame, wait until the game's GPU work on it has finished, for games that hand over images early (an eye flickers or jitters). Costs some frame time. 2 = only after the first 60 s (compare both in one session).": "",
"Before each Play on this PC, FramePort reads SteamVR's record of the game's last session (frames dropped; frame times from fpsVR if installed). If it dropped frames, it lowers the game's refresh rate to one whose frame budget fits (e.g. 96 → 90 Hz) and turns motion smoothing on, through SteamVR's per-application settings; each later session can step down again. Set a refresh rate or smoothing mode here to choose yourself. Ignored on the Frame.": "",
"Best guess": "",
"Blit quads flagged XrCompositionLayerImageLayoutFB VERTICAL_FLIP upside down (Vulkan). Fixes UI panels and text that show upside down (e.g. Assassin's Creed Nexus).": "",
@@ -299,6 +300,7 @@
"For games whose menus or screens jump to wherever you look.": "",
"For heavy games that use application space warp: it causes artifacts or hangs on non-Quest runtimes (e.g. Asgard's Wrath 2, Batman: Arkham Shadow).": "",
"For mixed-reality-only games. On the Frame, passthrough is emulated by the FrameBridge adapter (greyscale cameras).": "",
"For one eye looking wrong (e.g. a jittering right eye): logs each eye's submitted pose against a fresh one, the eye-to-eye relation and when each eye's image was released, also into framebridge.log in the game's storage (some games stop Android's log early). No effect on the game.": "",
"For Unreal games that close themselves right after starting (e.g. Phantom: Covert Ops). Also disables the in-game Quit.": "",
"Force enable passthrough": "",
"Found": "",
@@ -429,6 +431,7 @@
"Keyboard disconnected: {error}": "",
"KiB": "",
"Language": "",
"Language packs from the game's files": "",
"Last build": "",
"Last launch test: {get} · furthest: {value}": "",
"Later": "",
@@ -453,6 +456,7 @@
"Lets mixed-reality games start even though they insist on a camera view of your room.": "",
"Lets older Unity games start VR without Meta's system apps (they'd stay on a 2D screen).": "",
"Lets SDL and LÖVE games start on the Frame (they'd crash looking for a clipboard).": "",
"Lets the game find language files (like de.lang) that are already in its data, instead of waiting for a download that never comes.": "",
"Lets typing reach this app: Steam's on-screen keyboard or your computer's keyboard (VR is unaffected).": "",
"Lets Unity games accept a headset that isn't a Quest.": "",
"Lets Unreal games accept a headset that isn't a Quest.": "",
@@ -571,6 +575,7 @@
"OVRPort's OpenXR dispatcher aborts the app ('Wrong createInfo size', SIGABRT in libopenxr_loader.so xrCreateSwapchain) when a swapchain is wider or taller than 4096 px, which video players do for 8K video or big theatre textures (e.g. 4XVR). Raises the guard to 16384 px so the Frame's runtime (8192 px max) decides instead.": "",
"OVRPort's own converter for games that use Meta's oldest VR interface (experimental).": "",
"OVRPort's own VrApi→OpenXR adapter for engines that call libvrapi.so directly: the same upstream code as FramePort's 'VrApi → OpenXR bridge' without its Frame-specific changes. Only in OVRPort's experimental CLI builds (the stable CLI lists it but can't apply it).": "",
"OVRPort's platform loader answers the Meta Platform SDK's language-pack calls (ovr_LanguagePack_GetCurrent/SetCurrent) with 'no request', so a game that asks for its language pack never gets an answer. Adds a small library that serves language packs (<tag>.lang, e.g. de.lang) found in the game's own data folders (OBB and app files) through the same calls, the asset-file list and the status call, without any download. The game then finds the file path itself. The pack it applies with SetCurrent wins; otherwise the environment variable FRAMEPORT_LANGPACK (a tag), otherwise the only pack there is. Everything else goes to the loader unchanged. Off by default: turn it on for a game whose data has such files (the game page lists the patch only then).": "",
"Package": "",
"Pairing: on the Frame open Settings → Developer → Pair new host, then approve FramePort.": "",
"Password (first time only)": "",
@@ -594,6 +599,7 @@
"PC VR · Proton": "",
"PC VR —": "",
"PC VR ✓": "",
"Per-eye diagnostics (log)": "",
"Pick several games and install them in one go. FramePort asks every question first, then works through the queue in the background.": "",
"Picks a refresh rate and motion smoothing that suit the game on this PC.": "",
"Pico/YVR/Quest metadata": "",
@@ -760,9 +766,11 @@
"Show Steam Frame controllers": "",
"Show technical details (patch ids, exact effects, parameters)": "",
"Show the app's Android window (for typing)": "",
"Show video panels": "",
"Showing {len} of {n}": "",
"Shows 3D 360° pictures flat if they look doubled.": "",
"Shows the Frame's cameras where the game expects passthrough.": "",
"Shows videos that games play on a flat panel (e.g. an intro video).": "",
"Signing keys matter: game updates must be signed with the same key or their saves are lost on reinstall.": "",
"Signs rebuilt games": "",
"Size": "",
@@ -839,6 +847,7 @@
"The Frame's battery is at {pct} % and not charging. Plug it in (a strong charger, not a PC port): long installs can drain it, and FramePort pauses them at {pause} %.": "",
"The Frame's battery is at {pct} %: installs paused so it doesn't switch off mid-upload. Plug it in; the queue continues by itself.": "",
"The Frame's desktop password, only needed the first time so FramePort can add its own key. After that it connects with the key.": "",
"The Frame's Steam couldn't start {title} (Steam error {code}). Please send a problem report so we can see why.": "",
"The Frame's Steam library still shows the old artwork.": "",
"the game didn't pass its checks (see the list above)": "",
"the installed game (APK and its data)": "",
@@ -954,6 +963,7 @@
"Valve's Android runtime isn't installed (needs Developer Mode)": "",
"Version": "",
"Very high": "",
"Video panels that an Android media player draws into (XR_KHR_android_surface_swapchain, e.g. I Am Monkey's intro video), which the Frame's runtime refuses, get an Android Surface from FrameBridge: each video frame is copied into an ordinary swapchain the panel shows. Without it these panels are missing and a game waiting for its video stays black. 0 = leave them to the runtime.": "",
"Video players' virtual theatres and 360° videos would otherwise stay black.": "",
"Videos": "",
"Videos, documents, mods and saves on your Steam Frame": "",
@@ -964,6 +974,7 @@
"Vulkan shim (frame.vk_sanitize): SPIR-V modules matching size + SHA-256 get words inserted at a byte offset, e.g. stores that initialize locals a shader reads before writing (an undefined loop counter hung the GPU in VR4's campaign). Format: <size>:<sha256>:<byte offset>:<word>,<word>,...; several separated by ';'. Comes from a game's recipe.": "",
"Vulkan: drop invalid render-pass pointers": "",
"v{remote} (updates on the next action)": "",
"Wait for the game's GPU before showing an image": "",
"Waiting": "",
"Waiting ({n})": "",
"Waiting for the Frame": "",
+90
View File
@@ -0,0 +1,90 @@
"""Language packs (`<tag>.lang` files in the game's data) for the Meta Platform SDK (native/langpack)."""
from __future__ import annotations
from ...analysis import elf
from ..base import ApkContext, Patch, register
from . import artifact
LOADER = "libovrplatformloader.so"
LIB = "libfp_langpack.so"
META_MARK = b"@FPMETA@\0" # native/langpack: g_meta_slot = marker + META_LEN bytes the Metadata is written into
META_LEN = 96
def with_metadata(lib: bytes, text: str) -> bytes:
"""The library with `text` (the game's versionName) as the Metadata of the packs it serves.
Unreal games such as Deadpool VR only treat a pack as installed when its Metadata equals their own version string,
which Meta's store sets when the pack is uploaded."""
raw = text.encode("utf-8")
at = lib.find(META_MARK)
if not raw or len(raw) >= META_LEN or at < 0:
return lib
at += len(META_MARK)
return lib[:at] + raw + b"\0" * (META_LEN - len(raw)) + lib[at + META_LEN:]
# Every function native/langpack/langpack.c defines. The loader's own exports of these are hidden (see
# elf.hide_exports) so lookups reach LIB first; tests/test_langpack.py keeps this list equal to the C source.
EXPORTS = (
"ovr_AssetDetailsArray_GetElement", "ovr_AssetDetailsArray_GetSize", "ovr_AssetDetails_GetAssetId",
"ovr_AssetDetails_GetAssetType", "ovr_AssetDetails_GetDownloadStatus", "ovr_AssetDetails_GetFilepath",
"ovr_AssetDetails_GetIapStatus", "ovr_AssetDetails_GetLanguage", "ovr_AssetDetails_GetMetadata",
"ovr_AssetFileDownloadResult_GetAssetId", "ovr_AssetFileDownloadResult_GetFilepath", "ovr_AssetFile_GetList",
"ovr_AssetFile_StatusById", "ovr_Error_GetCode", "ovr_Error_GetDisplayableMessage", "ovr_Error_GetHttpCode",
"ovr_Error_GetMessage", "ovr_FreeMessage", "ovr_LanguagePackInfo_GetEnglishName",
"ovr_LanguagePackInfo_GetNativeName", "ovr_LanguagePackInfo_GetTag", "ovr_LanguagePack_GetCurrent",
"ovr_LanguagePack_SetCurrent", "ovr_Message_GetAssetDetails", "ovr_Message_GetAssetDetailsArray",
"ovr_Message_GetAssetFileDownloadResult", "ovr_Message_GetError", "ovr_Message_GetRequestID",
"ovr_Message_GetType", "ovr_Message_IsError", "ovr_PopMessage",
)
class LanguagePacks(Patch):
id = "frame.langpacks"
title = "Language packs from the game's files"
description = ("OVRPort's platform loader answers the Meta Platform SDK's language-pack calls "
"(ovr_LanguagePack_GetCurrent/SetCurrent) with 'no request', so a game that asks for its language "
"pack never gets an answer. Adds a small library that serves language packs (<tag>.lang, e.g. "
"de.lang) found in the game's own data folders (OBB and app files) through the same calls, the "
"asset-file list and the status call, without any download. The game then finds the file path "
"itself. The pack it applies with SetCurrent wins; otherwise the environment variable "
"FRAMEPORT_LANGPACK (a tag), otherwise the only pack there is. Everything else goes to the "
"loader unchanged. Off by default: turn it on for a game whose data has such files (the game "
"page lists the patch only then).")
order = 32
experimental = True # opt-in: checked in a headset with Deadpool VR, AC Nexus and Asgard's Wrath 2 only
# never part of a default recipe (few games tested): shown under Customize for games whose data has
# language packs, off until the user turns it on
def applies(self, a):
return LOADER in a.libs and "arm64-v8a" in a.abis and bool((a.extra or {}).get("lang_packs"))
def apply(self, ctx: ApkContext) -> bool:
ws = ctx.ws
if ws.abi != "arm64-v8a" or not ws.has(ws.lib(LOADER)):
return False
loader = ws.read_lib(LOADER)
patched, hidden = elf.hide_exports(loader, EXPORTS)
if not hidden and LIB in elf.needed(loader):
return False # applied by an earlier build
if not hidden:
ctx.notes.append("the platform loader has none of the language-pack functions: nothing to replace")
return False
patched = elf.add_needed(patched, LIB)
ws.put(ws.lib(LOADER), patched)
version = (ctx.analysis.version or "").strip()
ws.put(ws.lib(LIB), with_metadata(artifact(ws.abi, LIB), version))
ctx.notes.append(f"language packs served by {LIB} ({len(hidden)} loader functions replaced, "
f"Metadata \"{version}\")")
return True
def validate(self, ctx: ApkContext):
ws = ctx.ws
if not ws.has(ws.lib(LOADER)):
return []
linked = LIB in elf.needed(ws.read_lib(LOADER))
return [("Language-pack library linked to the platform loader", linked and ws.has(ws.lib(LIB)), LIB)]
register(LanguagePacks)
+17 -1
View File
@@ -31,6 +31,11 @@ SETTINGS = [
("cylinder_strips", "int", 1, "Show curved panels",
"Cylinder layers (curved menus and movie screens, e.g. 4XVR), which the Frame's runtime lacks, are shown as a "
"few flat strips along the curve. 0 = drop them. 360° (equirect) layers can't be shown on the Frame."),
("surface_emul", "int", 1, "Show video panels",
"Video panels that an Android media player draws into (XR_KHR_android_surface_swapchain, e.g. I Am Monkey's "
"intro video), which the Frame's runtime refuses, get an Android Surface from FrameBridge: each video frame is "
"copied into an ordinary swapchain the panel shows. Without it these panels are missing and a game waiting for "
"its video stays black. 0 = leave them to the runtime."),
("equirect_emul", "int", 0, "Show 360° layers",
"360° (equirect) layers, e.g. a video player's virtual theatre or 360° videos (e.g. 4XVR), which the Frame's "
"runtime lacks, are drawn by a background thread into a layer behind the game's own picture: the 360° image is "
@@ -78,6 +83,14 @@ SETTINGS = [
("layer_debug", "int", 0, "Extra diagnostics (log)",
"Logs details for debugging: composition layers and swapchains, focus changes, play-space creation, pointer vs "
"grip poses, refresh rates. No effect on the game."),
("eye_debug", "int", 0, "Per-eye diagnostics (log)",
"For one eye looking wrong (e.g. a jittering right eye): logs each eye's submitted pose against a fresh one, the "
"eye-to-eye relation and when each eye's image was released, also into framebridge.log in the game's storage "
"(some games stop Android's log early). No effect on the game."),
("release_wait", "int", 0, "Wait for the game's GPU before showing an image",
"Before a swapchain image is handed to the Frame, wait until the game's GPU work on it has finished, for games "
"that hand over images early (an eye flickers or jitters). Costs some frame time. 2 = only after the first 60 s "
"(compare both in one session)."),
("scene_emul", "int", 0, "Emulate Meta scene (room)",
"Fake XR_FB_scene/spatial entities: a guardian-sized room with floor, ceiling and four walls, for mixed-reality "
"games that build their level from the room (e.g. Demeter)."),
@@ -150,6 +163,9 @@ UI: dict[str, dict] = {
"cylinder_strips": dict(group="screens", level="common", label="Show curved menus and screens",
help="The Frame can't show curved panels; this shows them as gently bent strips.",
control=("switch",)),
"surface_emul": dict(group="screens", level="common", label="Show video panels",
help="Shows videos that games play on a flat panel (e.g. an intro video).",
control=("switch",)),
"flip_emul": dict(group="screens", level="common", label="Fix upside-down menus",
help="Turns menus and text the right way up.", control=("switch",)),
"stable_local": dict(group="screens", level="common", label="Keep menus in place",
@@ -191,7 +207,7 @@ UI: dict[str, dict] = {
control=("choice", [(0, "As the game sends it"), (2, "Flat")])),
**{key: dict(group="troubleshooting", level="advanced", control=("switch",)) for key in (
"foveation_fix", "swapchain_fix", "layer_fix", "gl_hide_multiview", "mutable_fix", "flip_quads", "swap_eyes",
"strip_depth", "respace_kick", "layer_debug")},
"strip_depth", "respace_kick", "layer_debug", "eye_debug", "release_wait")},
}
+2
View File
@@ -42,6 +42,8 @@ SUMMARIES = {
"frame.meta_permissions": "Declares Meta's permissions some mixed-reality games ask for, so they don't stop.",
"frame.ovrplatformcompat": "Adds a small piece of Meta's platform library that some games need to start.",
"frame.ovrstubs": "Provides stand-ins for Meta store functions the game expects, so it doesn't crash at start.",
"frame.langpacks": "Lets the game find language files (like de.lang) that are already in its data, instead of "
"waiting for a download that never comes.",
"frame.unity_no_msaa": "Turns off a smoothing setting that crashes some older Unity games on the Frame.",
"frame.unity_runtime_msaa_off": "Keeps a smoothing setting off that the game turns on itself and that can freeze "
"the Frame.",
+15 -1
View File
@@ -9,10 +9,12 @@ PC (Revive + local Steam) or on the Frame (Proton + Revive).
"""
from __future__ import annotations
import threading
import time
from pathlib import Path
from . import build as builder
from .analysis import langpacks
from .analysis.detect import analyze
from .artwork import fetch as artwork
from .core import library
@@ -275,6 +277,7 @@ def add_game(src: SourceGame, reporter: Reporter | None = None) -> dict:
if reporter:
reporter.log(f"analyzing {src.apk.name}")
a = analyze(src.apk, data_bytes=src.data_bytes())
a.extra["lang_packs"] = langpacks.find_tags(src.data_dir)
recipe = engine.suggest(a)
return library.upsert_game(
a.package, title=recipe.title or a.label, name=src.name, apk=str(src.apk),
@@ -294,6 +297,7 @@ def reanalyze(package: str, reporter: Reporter | None = None) -> dict:
if reporter:
reporter.log(f"analyzing {src.apk.name}")
a = analyze(src.apk, data_bytes=src.data_bytes())
a.extra["lang_packs"] = langpacks.find_tags(src.data_dir)
suggested = engine.suggest(a)
keep = library.recipe_from_dict(entry["recipe"]).source == "user"
return library.upsert_game(package, analysis=a.to_dict(), suggested=library.recipe_to_dict(suggested),
@@ -399,6 +403,15 @@ def recipe_fingerprint(recipe: dict) -> str:
return fp(recipe)
_build_locks: dict[str, threading.Lock] = {}
_build_locks_guard = threading.Lock()
def _build_lock(package: str) -> threading.Lock:
with _build_locks_guard:
return _build_locks.setdefault(package, threading.Lock())
def build_game(package: str, reporter: Reporter, outdir: Path | None = None) -> dict:
entry = library.game(package)
if is_rift(entry):
@@ -409,7 +422,8 @@ def build_game(package: str, reporter: Reporter, outdir: Path | None = None) ->
a = library.analysis_from_dict(entry["analysis"])
recipe = library.recipe_from_dict(entry["recipe"])
out = outdir or (output_dir() / quest_dump.display_name(entry.get("name") or package))
res = builder.build(src, a, recipe, out, reporter)
with _build_lock(package): # one build per game at a time: builds share the game's work folder
res = builder.build(src, a, recipe, out, reporter)
art, store_title = artwork.fetch(package, res.apk)
build_info = {"apk": str(res.apk), "alt_apk": str(res.alt_apk) if res.alt_apk else None, "sha256": res.sha256,
"alt_sha256": res.alt_sha256, "applied": res.applied, "checks": res.checks, "ok": res.ok,
+55 -14
View File
@@ -23,9 +23,10 @@ from ..frame.connection import NOT_IN_LIBRARY, AgentFailed
from ..i18n import fmt_size, tr, tr_n
from ..recommend import catalog
from . import components as C
from . import jobs as jobs_module
from . import theme as T
from .components import install_state # noqa: F401 (re-exported: tests and older callers import it from here)
from .jobs import Job, JobManager
from .jobs import Job
NAV = [("library", tr("Library"), ft.Icons.GRID_VIEW_ROUNDED),
("frame", tr("Steam Frame"), ft.Icons.VIEW_IN_AR_ROUNDED),
@@ -33,6 +34,22 @@ NAV = [("library", tr("Library"), ft.Icons.GRID_VIEW_ROUNDED),
POLL_SECONDS = 30
def window_geometry(saved: dict | None, scale: float) -> dict:
"""Window properties for the start from the saved `ui.window` setting: the size (first start: 16:10 sized for the
UI scale), the position when it is plausible (a window left on a monitor that is gone would open off screen; far
off values are ignored, the system then places it) and maximized."""
saved = saved or {}
w, h = saved.get("size") or (round(1280 * scale), round(780 * scale))
out = {"width": max(int(w), 1000), "height": max(int(h), 680)}
pos = saved.get("pos")
if isinstance(pos, (list, tuple)) and len(pos) == 2 and all(isinstance(v, (int, float)) for v in pos) \
and -16000 < pos[0] < 16000 and -8 <= pos[1] < 9000:
out["left"], out["top"] = int(pos[0]), int(pos[1])
if saved.get("maximized"):
out["maximized"] = True
return out
class FramePortApp:
def __init__(self, page: ft.Page):
from .views.activity import ActivityPanel
@@ -52,7 +69,10 @@ class FramePortApp:
self.files_view = None # likewise (views/files.FilesView): keeps the location/folder between visits
self.exe_queue: list[str] = [] # games whose executable the user should confirm (after a scan)
self._failures: list[Job] = [] # failed installs/tests, shown together when the queue is done
self.jobs = JobManager(self._on_job)
self.jobs = jobs_module.shared() # one queue per process, shared by every window session
self.jobs.subscribe(self._on_job)
self._handled_jobs: set[int] = set() # finished jobs this session has reacted to (pop-ups, refreshes)
page.on_close = lambda e: self.jobs.unsubscribe(self._on_job) # session gone: stop drawing into it
from .updater import Updater
self.updater = Updater(self) # new FramePort releases (sidebar card, Library bar, one-click update)
@@ -63,9 +83,10 @@ class FramePortApp:
page.window.min_width, page.window.min_height = 1000, 680
if not page.web:
# 16:10 sized for the UI scale (the first start used to open too narrow at 125 %: toolbars were cut off);
# later starts reopen at the size the window was left at
w, h = (library.setting("ui.window") or {}).get("size") or (round(1280 * T.SCALE), round(780 * T.SCALE))
page.window.width, page.window.height = max(int(w), 1000), max(int(h), 680)
# later starts reopen where the window was left: size, position (GitHub #32: always top left on Windows),
# maximized
for key, value in window_geometry(library.setting("ui.window"), T.SCALE).items():
setattr(page.window, key, value)
page.window.on_event = self._on_window_event
page.on_keyboard_event = self._on_key
if page.web: # the library's right-click menu; otherwise the browser shows its own
@@ -104,12 +125,25 @@ class FramePortApp:
# ================================================================== shell
def _on_window_event(self, e) -> None:
"""Remember the window size (once a resize ends; not while maximized or full screen)."""
win = self.page.window
if e.type == ft.WindowEventType.RESIZED and not (win.maximized or win.full_screen) and win.width and \
win.height:
size = [round(win.width), round(win.height)]
self.page.run_thread(library.update_setting, "ui.window", lambda v: {**(v or {}), "size": size}, {})
"""Remember the window's size and position (once a resize/move ends; not while maximized or full screen) and
whether it is maximized."""
win, change = self.page.window, None
if e.type in (ft.WindowEventType.MAXIMIZE, ft.WindowEventType.UNMAXIMIZE):
change = {"maximized": e.type == ft.WindowEventType.MAXIMIZE}
elif win.maximized or win.full_screen:
return
elif e.type == ft.WindowEventType.RESIZED and win.width and win.height:
change = {"size": [round(win.width), round(win.height)]}
if win.left is not None and win.top is not None: # resizing from the left/top edge moves it too
change["pos"] = [round(win.left), round(win.top)]
elif e.type in (ft.WindowEventType.MOVED, ft.WindowEventType.CLOSE) and win.left is not None and \
win.top is not None:
change = {"pos": [round(win.left), round(win.top)]}
if e.type == ft.WindowEventType.CLOSE: # the app is going away: write it now
library.update_setting("ui.window", lambda v: {**(v or {}), **change}, {})
return
if change:
self.page.run_thread(library.update_setting, "ui.window", lambda v: {**(v or {}), **change}, {})
def top_bar(self, heading: str, subtitle: str = "", actions: list[ft.Control] | None = None) -> ft.Control:
heads = [C.title(heading), C.body(subtitle)] if subtitle else [C.title(heading)]
@@ -366,8 +400,8 @@ class FramePortApp:
self._refresh_sidebar()
self.activity.refresh()
self._keep_frame_awake()
if job and job.state in ("done", "failed", "cancelled") and job.finished and not getattr(job, "_handled", 0):
job._handled = 1
if job and job.state in ("done", "failed", "cancelled") and job.finished and id(job) not in self._handled_jobs:
self._handled_jobs.add(id(job))
if job.kind == "app-update" and job.state != "done":
self.updater.restart = None # the update didn't get ready: don't quit
self.updater.on_jobs_changed() # an update waiting for the queue to empty installs now
@@ -518,7 +552,14 @@ class FramePortApp:
self._add_then_play(pkg, title) # e.g. the shortcut step failed during the install
return
library.upsert_game(pkg, last_played=time.time())
if to == "frame":
steam = res.get("steam") or {}
if to == "frame" and steam: # what the Frame's Steam logged about this launch (GitHub #21/#30)
applog.log.info("Play %s: Steam %s %s", pkg, steam.get("result"), steam.get("lines"))
if to == "frame" and steam.get("result") == "error": # 9 = "Game configuration unavailable"
self.toast(tr("The Frame's Steam couldn't start {title} (Steam error {code}). Please send a problem "
"report so we can see why.").format(title=title, code=steam.get("code")), error=True,
action=tr("Report a problem"), on_action=lambda e: self.report_problem_dialog(pkg))
elif to == "frame":
self.toast(tr("Starting {title} on the Frame — put the headset on").format(title=title))
elif res.get("steamvr") is False:
msg = tr("Starting {title}, but SteamVR isn't running — it may open as a flat window. "
+19
View File
@@ -100,6 +100,10 @@ class JobManager:
def subscribe(self, fn: Callable[[Job | None], None]) -> None:
self._listeners.append(fn)
def unsubscribe(self, fn: Callable[[Job | None], None]) -> None:
if fn in self._listeners:
self._listeners.remove(fn)
def submit(self, job: Job) -> Job:
job.reporter.subscribe(lambda ev, j=job: self._event(j, ev))
with self._cv:
@@ -225,3 +229,18 @@ class JobManager:
if self.save_logs:
applog.save_job_log(job.kind, job.package, job.state, job.text())
self._notify(job, force=True)
_shared: JobManager | None = None
_shared_lock = threading.Lock()
def shared() -> JobManager:
"""The process's one job queue. Flet builds a new app object for every window session (a reconnect after sleep
or a reload): with a queue per session, the old session's job kept running unseen and the same game could be
built twice at once in the same work folder (both builds then failed)."""
global _shared
with _shared_lock:
if _shared is None:
_shared = JobManager()
return _shared
+66
View File
@@ -0,0 +1,66 @@
// Test fixture for tests/test_langpack.py: a stand-in for OVRPort's platform loader (libovrplatformloader.so).
// Like the real one it answers ovr_LanguagePack_GetCurrent/SetCurrent with `return 0` and keeps its own message queue;
// AssetFile_GetList/StatusById queue one message that carries one "store" asset (id 7).
// Build: cc -shared -fPIC -O1 fakeloader.c -o libovrplatformloader.so
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef uint64_t u64;
typedef struct { uint32_t type; u64 req; int err; } fmsg;
typedef struct { u64 id; char type[16]; char path[32]; } fdet;
static fmsg *q[16];
static int qn, freed;
static u64 next_req = 100;
static fdet store = {7, "store", "/store/a"};
static int arr_handle;
static u64 post(uint32_t type, int err) {
fmsg *m = calloc(1, sizeof *m);
m->type = type;
m->req = next_req++;
m->err = err;
q[qn++] = m;
return m->req;
}
u64 ovr_AssetFile_GetList(void) {
if (getenv("FAKE_SILENT_LIST")) return next_req++; // asks, never answers (the case the timeout fallback is for)
return post(0x4AFC6F74u, 0);
}
u64 ovr_AssetFile_StatusById(u64 id) { return post(0x5D955D38u, id != 7); }
u64 ovr_LanguagePack_GetCurrent(void) { return 0; }
u64 ovr_LanguagePack_SetCurrent(const char *tag) { (void)tag; return 0; }
void *ovr_PopMessage(void) {
if (!qn) return NULL;
fmsg *m = q[0];
memmove(q, q + 1, sizeof(q[0]) * (size_t)--qn);
return m;
}
void ovr_FreeMessage(void *m) { freed++; free(m); }
uint32_t ovr_Message_GetType(const void *m) { return ((const fmsg *)m)->type; }
u64 ovr_Message_GetRequestID(const void *m) { return ((const fmsg *)m)->req; }
_Bool ovr_Message_IsError(const void *m) { return ((const fmsg *)m)->err != 0; }
void *ovr_Message_GetError(const void *m) { (void)m; return NULL; }
void *ovr_Message_GetAssetDetails(const void *m) { return ((const fmsg *)m)->err ? NULL : &store; }
void *ovr_Message_GetAssetDetailsArray(const void *m) { (void)m; return &arr_handle; }
size_t ovr_AssetDetailsArray_GetSize(const void *a) { (void)a; return 1; }
void *ovr_AssetDetailsArray_GetElement(const void *a, size_t i) { (void)a; return i == 0 ? &store : NULL; }
u64 ovr_AssetDetails_GetAssetId(const void *d) { return ((const fdet *)d)->id; }
const char *ovr_AssetDetails_GetAssetType(const void *d) { return ((const fdet *)d)->type; }
const char *ovr_AssetDetails_GetDownloadStatus(const void *d) { (void)d; return "available"; }
const char *ovr_AssetDetails_GetFilepath(const void *d) { return ((const fdet *)d)->path; }
const char *ovr_AssetDetails_GetIapStatus(const void *d) { (void)d; return "free"; }
void *ovr_AssetDetails_GetLanguage(const void *d) { (void)d; return NULL; }
const char *ovr_AssetDetails_GetMetadata(const void *d) { (void)d; return ""; }
// not part of the SDK: lets the test see that our wrapper frees the dispatcher's own message
int fake_freed(void) { return freed; }
void fake_late_list(u64 req) { // the dispatcher answers a GetList after all (late)
fmsg *m = calloc(1, sizeof *m);
m->type = 0x4AFC6F74u;
m->req = req;
q[qn++] = m;
}
+58
View File
@@ -49,6 +49,23 @@ def test_launcher_template(monkeypatch, tmp_path):
assert subprocess.run(["bash", "-n", str(anchor / "launch.sh")]).returncode == 0
def test_launcher_repairs_save_folder_permissions(monkeypatch, tmp_path):
"""SUPERHOT creates its cloud save folder with mode 1700 and quits when it can't write there (Lepton's app
writes through the folder's group): the launcher gives every storage folder owner and group write permission."""
a = load_agent(monkeypatch, tmp_path)
anchor = tmp_path / "anchor"
anchor.mkdir()
a.write_launcher(str(anchor), str(tmp_path / "game"), "com.x.y", "T", 1, "/lepton/lepton", {})
fix = next(line for line in (anchor / "launch.sh").read_text().splitlines() if line.startswith("fix_perms()"))
saves = tmp_path / "game" / "lepton-data" / "external" / "Android" / "data" / "com.x.y" / "files" / "cloud"
saves.mkdir(parents=True)
os.chmod(saves, 0o1700)
if os.stat(saves).st_mode & 0o777 != 0o700:
pytest.skip("filesystem doesn't keep modes")
subprocess.run(["bash", "-c", f"app_dir={tmp_path / 'game'}\n{fix}\nfix_perms"], check=True)
assert os.stat(saves).st_mode & 0o770 == 0o770
def test_cli_protocol(tmp_path):
p = subprocess.run([sys.executable, str(AGENT), "nope"], capture_output=True, text=True)
assert p.returncode == 2 and json.loads(p.stdout)["ok"] is False
@@ -896,3 +913,44 @@ def test_shortcuts_lost_after_steam_restart(monkeypatch, tmp_path):
exe, title, start, icon, tag, tags, openvr = a.shortcut_args("com.x.y")
a.upsert_shortcut(str(cfg / "shortcuts.vdf"), exe, title, start, icon, tag, tags=tags, openvr=openvr)
assert a.shortcuts_lost(["42"], ["com.x.y"]) == []
def test_steam_launch_result_reads_steams_log(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
monkeypatch.setattr(a.time, "sleep", lambda s: None)
log = tmp_path / "console_log.txt"
old = "[2026-10-04 12:00:00] SteamUI: WARNING: LaunchGameAction: launch error 9 3554078061 LaunchApp AppError_18\n"
log.write_text(old)
start = log.stat().st_size # lines from before this launch don't count
assert a.steam_launch_result(str(log), start, 3554078061, wait=0)["result"] == "silent"
with open(log, "a") as f: # GitHub #21/#30: Steam's "Game configuration unavailable"
f.write("[2026-10-04 12:09:52] SteamUI: WARNING: LaunchGameAction: launch error 9 3554078061 LaunchApp "
"AppError_18 \n")
got = a.steam_launch_result(str(log), start, 3554078061, wait=0)
assert got["result"] == "error" and got["code"] == 9 and got["detail"] == "LaunchApp AppError_18"
log.write_text(old + "[2026-10-04 19:12:16] GameAction [AppID 2369265159, ActionID 4] : LaunchApp changed task "
"to CreatingProcess with \"\"\n")
assert a.steam_launch_result(str(log), start, 2369265159, wait=0)["result"] == "started"
def test_steam_library_report(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
anchor = tmp_path / "Applications/quest-frame/com.x.y"
anchor.mkdir(parents=True)
(anchor / "deployment.json").write_text(json.dumps({"package": "com.x.y", "appid": 1, "title": "X", "base": "b"}))
cfg = tmp_path / ".local/share/Steam/userdata/42/config"
cfg.mkdir(parents=True)
exe, title, start, icon, tag, tags, openvr = a.shortcut_args("com.x.y")
appid = a.upsert_shortcut(str(cfg / "shortcuts.vdf"), exe, title, start, icon, tag, tags=tags, openvr=openvr)
a.upsert_shortcut(str(cfg / "shortcuts.vdf"), '"/usr/bin/other"', "Other", "/", "")
logs = tmp_path / ".local/share/Steam/logs"
logs.mkdir()
(logs / "console_log.txt").write_text(f"noise\n[x] GameAction [AppID {appid}, ActionID 1] : LaunchApp changed "
"task to Completed\n path_shortcut: \"/a.desktop\"\n")
monkeypatch.setattr(a, "run", lambda cmd, **k: SimpleNamespace(returncode=1, stdout=""))
rep, console = a.steam_library_report()
acc = rep["accounts"][0]
assert acc["shortcuts"] == 2 and acc["exe_dupes"] == 0 and acc["shortcuts_vdf_written"]
assert acc["frameport"] == [{"package": "com.x.y", "appid": appid, "title": "X", "start_dir": start,
"openvr": acc["frameport"][0]["openvr"], "options": acc["frameport"][0]["options"]}]
assert f"[AppID {appid}" in console and "noise" not in console and "path_shortcut" not in console
+16
View File
@@ -312,6 +312,22 @@ def test_picked_art_survives_installs(monkeypatch):
assert (d / "portrait.png").read_bytes() == png("red")
def test_generated_cover_still_gets_a_steam_placeholder():
"""The library's generated cover/banner (apps without store art, e.g. WiiCompiled) aren't store art: Steam still
gets the placeholder set (it used to get nothing at all, a blank tile in the Frame's library)."""
from PIL import Image
from frameport.artwork import fetch, steam
pkg = "org.example.generated"
d = fetch.artwork_dir(pkg)
d.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (600, 900)).save(d / "cover.jpg")
Image.new("RGB", (920, 430)).save(d / "banner.jpg")
art = steam.steam_set(pkg, title="Generated Cover App")
assert {"portrait", "landscape", "hero"} <= set(art)
def test_apps_without_store_art_get_a_cover(tmp_path):
"""FramePort's library shows a cover (name + APK icon) for apps no store knows; store art always wins."""
import zipfile
+416
View File
@@ -0,0 +1,416 @@
"""Language packs (native/langpack + patch frame.langpacks).
The C library is compiled for this host and driven through ctypes against a stand-in for OVRPort's platform loader
(tests/fixtures/src/fakeloader.c) that went through the real ELF patch (elf.hide_exports): lookups for the hidden
names no longer find the loader's functions, and the library still reaches them by reading the loader's .dynsym.
Needs a C compiler on Linux; the device side (bionic) is not covered here."""
import ctypes as C
import platform
import re
import shutil
import subprocess
import time
import zipfile
from pathlib import Path
import pytest
from frameport.analysis import elf, langpacks
from frameport.apk.workspace import ApkWorkspace
from frameport.core.events import Reporter
from frameport.core.models import Analysis
from frameport.patches import base
from frameport.patches.frame import langpack as patch_mod
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "native/langpack/langpack.c"
FAKE = Path(__file__).with_name("fixtures") / "src" / "fakeloader.c"
CC = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
pytestmark = pytest.mark.skipif(not CC or platform.system() != "Linux", reason="needs a C compiler on Linux")
GETLIST, STATUSBYID, GETCURRENT, SETCURRENT = 0x4AFC6F74, 0x5D955D38, 0x1F90F0D5, 0x5B4FBBE0
VOIDP = C.c_void_p
def _analysis(**kw):
d = dict(package="com.example.questgame", version="1.0", label="Quest Game", abis=["arm64-v8a"], engine="Unity",
xr="OpenXR", graphics="Vulkan (declared in manifest)", direct_vrapi=False, libs=[], launcher_activity=None,
has_info_category=True, meta_permissions=[], uses_glad_gl=False, unity_msaa_levels=0,
oculus_os_classes=False, is_overport_output=True, debuggable=True, extra={"size": 1})
d.update(kw)
return Analysis(**d)
def _compile(src, out, *extra):
subprocess.run([CC, "-shared", "-fPIC", "-O1", "-Wall", "-Wextra", "-Werror", *extra, str(src), "-o", str(out),
"-ldl", "-lpthread"], check=True, capture_output=True)
@pytest.fixture(scope="module")
def built(tmp_path_factory):
d = tmp_path_factory.mktemp("langpack-build")
_compile(FAKE, d / "fakeloader.so")
_compile(SRC, d / "langpack.so", "-fvisibility=hidden")
_compile(SRC, d / "langpack_fast.so", "-fvisibility=hidden", "-DFP_LIST_TIMEOUT_MS=100")
original = (d / "fakeloader.so").read_bytes()
patched, hidden = elf.hide_exports(original, patch_mod.EXPORTS)
return {"lib": d / "langpack.so", "fast": d / "langpack_fast.so", "original": original, "patched": patched,
"hidden": hidden}
def _dlclose(lib):
libdl = C.CDLL(None)
libdl.dlclose.argtypes = [VOIDP]
libdl.dlclose(lib._handle)
class Api:
"""The library under test (`lp`) and the stand-in loader behind it (`loader`)."""
def __init__(self, lp, loader):
self.lp, self.loader = lp, loader
def f(self, name, res, *args, lib=None):
fn = getattr(lib or self.lp, name)
fn.restype, fn.argtypes = res, list(args)
return fn
def pop(self):
return self.f("ovr_PopMessage", VOIDP)()
def msg_type(self, m):
return self.f("ovr_Message_GetType", C.c_uint32, VOIDP)(m)
def req_id(self, m):
return self.f("ovr_Message_GetRequestID", C.c_uint64, VOIDP)(m)
def is_error(self, m):
return bool(self.f("ovr_Message_IsError", C.c_bool, VOIDP)(m))
def free(self, m):
self.f("ovr_FreeMessage", None, VOIDP)(m)
def details(self, d):
s = lambda name: self.f(name, C.c_char_p, VOIDP)(d) # noqa: E731
lang = self.f("ovr_AssetDetails_GetLanguage", VOIDP, VOIDP)(d)
out = {"id": self.f("ovr_AssetDetails_GetAssetId", C.c_uint64, VOIDP)(d),
"type": s("ovr_AssetDetails_GetAssetType"), "status": s("ovr_AssetDetails_GetDownloadStatus"),
"path": s("ovr_AssetDetails_GetFilepath")}
if lang:
ls = lambda name: self.f(name, C.c_char_p, VOIDP)(lang) # noqa: E731
out.update(tag=ls("ovr_LanguagePackInfo_GetTag"), en=ls("ovr_LanguagePackInfo_GetEnglishName"),
native=ls("ovr_LanguagePackInfo_GetNativeName"))
return out
def ask(self, name, *args):
"""Send a request, pop the answer, return (message type, error?, payload getter result)."""
argtypes = [C.c_char_p] if args and isinstance(args[0], bytes) else ([C.c_uint64] if args else [])
req = self.f(name, C.c_uint64, *argtypes)(*args)
m = self.pop()
assert m and self.req_id(m) == req
return m
def _api(built, tmp_path, monkeypatch, which):
monkeypatch.delenv("FRAMEPORT_LANGPACK", raising=False)
lib = tmp_path / "lib"
lib.mkdir()
(lib / "libovrplatformloader.so").write_bytes(built["patched"]) # the name the library looks for
shutil.copy(built[which], lib / "libfp_langpack.so")
loader = C.CDLL(str(lib / "libovrplatformloader.so"))
lp = C.CDLL(str(lib / "libfp_langpack.so"))
yield Api(lp, loader)
_dlclose(lp)
_dlclose(loader)
@pytest.fixture
def api(built, tmp_path, monkeypatch):
yield from _api(built, tmp_path, monkeypatch, "lib")
@pytest.fixture
def api_fast(built, tmp_path, monkeypatch): # same library with a 100 ms GetList timeout
yield from _api(built, tmp_path, monkeypatch, "fast")
@pytest.fixture
def packs(tmp_path, monkeypatch):
root = tmp_path / "obb"
(root / "sub").mkdir(parents=True)
for rel in ("de.lang", "en-us.lang", "sub/fr.lang", "notes.txt", "x y.lang"):
(root / rel).write_bytes(b"data")
monkeypatch.setenv("FRAMEPORT_LANGPACK_DIRS", str(root))
return root
def test_exports_match_the_c_source():
text = SRC.read_text()
defined = set(re.findall(r"^EXPORT\s+[^;{(]*?\b(ovr_\w+)\s*\(", text, re.M))
assert defined == set(patch_mod.EXPORTS)
assert len(patch_mod.EXPORTS) == len(defined)
def test_hide_exports_keeps_symbols_but_hides_them_from_lookup(built, tmp_path):
assert set(built["hidden"]) >= {"ovr_PopMessage", "ovr_LanguagePack_GetCurrent", "ovr_AssetFile_GetList"}
assert "fake_freed" not in built["hidden"]
d = tmp_path / "orig"
d.mkdir()
(d / "a.so").write_bytes(built["original"])
(d / "b.so").write_bytes(built["patched"])
orig, patched = C.CDLL(str(d / "a.so")), C.CDLL(str(d / "b.so"))
try:
assert orig.ovr_PopMessage and patched.fake_freed # visible before, others untouched
with pytest.raises(AttributeError):
patched.ovr_PopMessage # noqa: B018 hidden: a lookup goes on to the next library
# the entries are still defined (the library reads their addresses from .dynsym)
assert "ovr_PopMessage" in elf.dyn_symbols(built["patched"], True)
assert elf.hide_exports(built["patched"], patch_mod.EXPORTS)[1] == [] # idempotent
finally:
_dlclose(orig)
_dlclose(patched)
def test_get_current_without_a_choice_is_an_error_when_several_packs(api, packs):
m = api.ask("ovr_LanguagePack_GetCurrent")
assert api.msg_type(m) == GETCURRENT and api.is_error(m)
err = api.f("ovr_Message_GetError", VOIDP, VOIDP)(m)
assert api.f("ovr_Error_GetCode", C.c_int, VOIDP)(err) == 404
assert b"no language pack" in api.f("ovr_Error_GetMessage", C.c_char_p, VOIDP)(err)
assert not api.f("ovr_Message_GetAssetDetails", VOIDP, VOIDP)(m)
api.free(m)
def test_get_current_by_environment_and_single_pack(api, packs, monkeypatch, tmp_path):
monkeypatch.setenv("FRAMEPORT_LANGPACK", "DE")
m = api.ask("ovr_LanguagePack_GetCurrent")
assert not api.is_error(m)
d = api.details(api.f("ovr_Message_GetAssetDetails", VOIDP, VOIDP)(m))
assert d["type"] == b"language_pack" and d["status"] == b"installed"
assert d["path"] == str(packs / "de.lang").encode()
assert (d["tag"], d["en"], d["native"]) == (b"de", b"German", b"Deutsch")
assert d["id"] >> 48 == 0x4650
api.free(m)
# exactly one pack and nothing chosen: that one
monkeypatch.delenv("FRAMEPORT_LANGPACK")
only = tmp_path / "only"
only.mkdir()
(only / "de.lang").write_bytes(b"x")
monkeypatch.setenv("FRAMEPORT_LANGPACK_DIRS", str(only))
m = api.ask("ovr_LanguagePack_GetCurrent")
assert api.details(api.f("ovr_Message_GetAssetDetails", VOIDP, VOIDP)(m))["tag"] == b"de"
api.free(m)
def test_set_current_then_status_then_get_current(api, packs):
m = api.ask("ovr_LanguagePack_SetCurrent", b"de-DE") # the base language matches
assert api.msg_type(m) == SETCURRENT and not api.is_error(m)
res = api.f("ovr_Message_GetAssetFileDownloadResult", VOIDP, VOIDP)(m)
asset = api.f("ovr_AssetFileDownloadResult_GetAssetId", C.c_uint64, VOIDP)(res)
path = api.f("ovr_AssetFileDownloadResult_GetFilepath", C.c_char_p, VOIDP)(res)
assert asset and path == str(packs / "de.lang").encode()
api.free(m)
m = api.ask("ovr_AssetFile_StatusById", asset) # the confirm step of the documented flow
assert api.msg_type(m) == STATUSBYID and not api.is_error(m)
d = api.details(api.f("ovr_Message_GetAssetDetails", VOIDP, VOIDP)(m))
assert (d["status"], d["path"], d["id"]) == (b"installed", path, asset)
api.free(m)
m = api.ask("ovr_LanguagePack_GetCurrent") # the choice sticks
assert api.details(api.f("ovr_Message_GetAssetDetails", VOIDP, VOIDP)(m))["tag"] == b"de"
api.free(m)
m = api.ask("ovr_AssetFile_StatusById", asset + 1) # ours by prefix, but unknown
assert api.is_error(m)
api.free(m)
def test_set_current_unknown_pack_is_an_error(api, packs):
for tag in (b"xx", b""):
m = api.ask("ovr_LanguagePack_SetCurrent", tag)
assert api.is_error(m) and not api.f("ovr_Message_GetAssetFileDownloadResult", VOIDP, VOIDP)(m)
api.free(m)
def test_asset_list_adds_our_packs_to_the_loaders_list(api, packs):
req = api.f("ovr_AssetFile_GetList", C.c_uint64)()
assert req == 100 # the loader's own request id
m = api.pop()
assert api.msg_type(m) == GETLIST and api.req_id(m) == req and not api.is_error(m)
arr = api.f("ovr_Message_GetAssetDetailsArray", VOIDP, VOIDP)(m)
size = api.f("ovr_AssetDetailsArray_GetSize", C.c_size_t, VOIDP)(arr)
items = [api.details(api.f("ovr_AssetDetailsArray_GetElement", VOIDP, VOIDP, C.c_size_t)(arr, i))
for i in range(size)]
assert size == 4
ours = [i for i in items if i["type"] == b"language_pack"]
assert {i["tag"] for i in ours} == {b"de", b"en-us", b"fr"} and {i["status"] for i in ours} == {b"installed"}
store = [i for i in items if i["type"] == b"store"] # the loader's own entry, served by the loader's accessors
assert store == [{"id": 7, "type": b"store", "status": b"available", "path": b"/store/a"}]
assert api.f("ovr_AssetDetailsArray_GetElement", VOIDP, VOIDP, C.c_size_t)(arr, 4) is None
before = api.loader.fake_freed()
api.free(m) # frees the loader's message behind ours too
assert api.loader.fake_freed() == before + 1
def _our_metadata(api):
api.f("ovr_AssetFile_GetList", C.c_uint64)()
m = api.pop()
arr = api.f("ovr_Message_GetAssetDetailsArray", VOIDP, VOIDP)(m)
get = api.f("ovr_AssetDetailsArray_GetElement", VOIDP, VOIDP, C.c_size_t)
out = {api.f("ovr_AssetDetails_GetMetadata", C.c_char_p, VOIDP)(get(arr, i))
for i in range(api.f("ovr_AssetDetailsArray_GetSize", C.c_size_t, VOIDP)(arr))
if api.f("ovr_AssetDetails_GetAssetType", C.c_char_p, VOIDP)(get(arr, i)) == b"language_pack"}
api.free(m)
return out
def test_metadata_is_empty_without_the_games_version(api, packs, monkeypatch):
monkeypatch.delenv("FRAMEPORT_LANGPACK_META", raising=False)
assert _our_metadata(api) == {b""}
def test_metadata_from_the_environment(api, packs, monkeypatch):
monkeypatch.setenv("FRAMEPORT_LANGPACK_META", "2.0.1.77.Quest")
assert _our_metadata(api) == {b"2.0.1.77.Quest"}
def test_patch_writes_the_games_version_as_the_metadata(built, tmp_path, monkeypatch):
monkeypatch.delenv("FRAMEPORT_LANGPACK_META", raising=False)
lib = patch_mod.with_metadata(built["lib"].read_bytes(), "1.0.40.356975.Quest")
assert len(lib) == built["lib"].stat().st_size and b"1.0.40.356975.Quest" in lib
assert patch_mod.with_metadata(lib, "") == lib and patch_mod.with_metadata(b"no marker", "1") == b"no marker"
assert patch_mod.with_metadata(lib, "x" * 200) == lib # too long for the slot: left as it was
d = tmp_path / "meta"
d.mkdir()
(d / "libovrplatformloader.so").write_bytes(built["patched"])
(d / "libfp_langpack.so").write_bytes(lib)
root = tmp_path / "obb"
root.mkdir()
(root / "de.lang").write_bytes(b"1")
monkeypatch.setenv("FRAMEPORT_LANGPACK_DIRS", str(root))
loader, lp = C.CDLL(str(d / "libovrplatformloader.so")), C.CDLL(str(d / "libfp_langpack.so"))
try:
assert _our_metadata(Api(lp, loader)) == {b"1.0.40.356975.Quest"}
finally:
_dlclose(lp)
_dlclose(loader)
def _tags(api):
api.f("ovr_AssetFile_GetList", C.c_uint64)()
m = api.pop()
arr = api.f("ovr_Message_GetAssetDetailsArray", VOIDP, VOIDP)(m)
get = api.f("ovr_AssetDetailsArray_GetElement", VOIDP, VOIDP, C.c_size_t)
size = api.f("ovr_AssetDetailsArray_GetSize", C.c_size_t, VOIDP)(arr)
out = {api.details(get(arr, i)).get("tag") for i in range(size)}
api.free(m)
out.discard(None)
return out
def test_packs_can_be_left_out_by_environment_or_file(api, packs, monkeypatch):
assert _tags(api) == {b"de", b"en-us", b"fr"}
monkeypatch.setenv("FRAMEPORT_LANGPACK_SKIP", "EN-US, x")
assert _tags(api) == {b"de", b"fr"}
monkeypatch.delenv("FRAMEPORT_LANGPACK_SKIP")
(packs / "fp_langpack_skip").write_text("de\nfr\n")
assert _tags(api) == {b"en-us"}
(packs / "fp_langpack_skip").unlink()
assert _tags(api) == {b"de", b"en-us", b"fr"} # nothing remembered between lists
def test_everything_else_reaches_the_loader_unchanged(api, packs):
# a status request for the loader's own asset: its message comes back as it is
req = api.f("ovr_AssetFile_StatusById", C.c_uint64, C.c_uint64)(7)
assert req == 100
m = api.pop()
assert api.msg_type(m) == STATUSBYID and not api.is_error(m)
d = api.details(api.f("ovr_Message_GetAssetDetails", VOIDP, VOIDP)(m))
assert d["path"] == b"/store/a"
api.free(m)
assert api.loader.fake_freed() == 1
assert api.pop() is None
def test_asset_list_without_packs_is_the_loaders_message(api, tmp_path, monkeypatch):
monkeypatch.setenv("FRAMEPORT_LANGPACK_DIRS", str(tmp_path / "nothing-here"))
api.f("ovr_AssetFile_GetList", C.c_uint64)()
m = api.pop()
arr = api.f("ovr_Message_GetAssetDetailsArray", VOIDP, VOIDP)(m)
assert api.f("ovr_AssetDetailsArray_GetSize", C.c_size_t, VOIDP)(arr) == 1
api.free(m)
assert api.loader.fake_freed() == 1
def test_asset_list_the_loader_never_answers_gets_our_packs_after_the_timeout(api_fast, packs, monkeypatch):
monkeypatch.setenv("FAKE_SILENT_LIST", "1")
req = api_fast.f("ovr_AssetFile_GetList", C.c_uint64)()
assert req == 100
assert api_fast.pop() is None # not overdue yet
time.sleep(0.2)
m = api_fast.pop()
assert m and api_fast.msg_type(m) == GETLIST and api_fast.req_id(m) == req and not api_fast.is_error(m)
arr = api_fast.f("ovr_Message_GetAssetDetailsArray", VOIDP, VOIDP)(m)
size = api_fast.f("ovr_AssetDetailsArray_GetSize", C.c_size_t, VOIDP)(arr)
tags = {api_fast.details(api_fast.f("ovr_AssetDetailsArray_GetElement", VOIDP, VOIDP, C.c_size_t)(arr, i))["tag"]
for i in range(size)}
assert tags == {b"de", b"en-us", b"fr"}
api_fast.free(m)
assert api_fast.pop() is None # answered once
before = api_fast.loader.fake_freed()
# the dispatcher's answer arrives after all: dropped, not a second answer
api_fast.loader.fake_late_list(C.c_uint64(req))
assert api_fast.pop() is None
assert api_fast.loader.fake_freed() == before + 1
def test_find_tags_in_the_data_folder(tmp_path):
root = tmp_path / "game"
(root / "a" / "b" / "c" / "d").mkdir(parents=True)
for rel in ("de.lang", "a/EN-us.LANG", "a/b/c/fr.lang", "a/b/c/d/too-deep.lang", "bad name.lang", "x.txt"):
(root / rel).write_bytes(b"1")
assert langpacks.find_tags(root) == ["de", "EN-us", "fr"]
assert langpacks.find_tags(None) == [] and langpacks.find_tags(tmp_path / "missing") == []
def _apk(tmp_path, built):
p = tmp_path / "in.apk"
with zipfile.ZipFile(p, "w") as z:
z.writestr("AndroidManifest.xml", b"manifest")
z.writestr("classes.dex", b"dex\n035\0")
z.writestr("lib/arm64-v8a/libovrplatformloader.so", built["original"])
return p
def test_patch_links_the_library_and_hides_the_loaders_functions(built, tmp_path, monkeypatch):
monkeypatch.setattr(patch_mod, "artifact", lambda abi, name: b"\x7fELF-langpack")
patch = base.get("frame.langpacks")
a = _analysis(libs=["libovrplatformloader.so"], extra={"size": 1, "lang_packs": ["de", "en-us"]})
assert patch.applies(a) # the game's data has language packs
assert patch.detect(a) is None # opt-in: never part of a suggested recipe
assert not patch.applies(_analysis(libs=["libovrplatformloader.so"])) # no language packs: nothing to serve
assert not patch.applies(_analysis(libs=[], extra={"size": 1, "lang_packs": ["de"]})) # no platform loader
with ApkWorkspace(_apk(tmp_path, built)) as ws:
ctx = base.ApkContext(ws, a, {}, Reporter(), {})
assert patch.apply(ctx)
loader = ws.read_lib("libovrplatformloader.so")
assert elf.needed(loader)[0] == "libfp_langpack.so"
assert "ovr_PopMessage" in elf.dyn_symbols(loader, True) # still defined, only no longer global
assert ws.read_lib("libfp_langpack.so") == b"\x7fELF-langpack"
assert all(ok for _, ok, _ in patch.validate(ctx))
assert not patch.apply(base.ApkContext(ws, a, {}, Reporter(), {})) # applied once is enough
assert any("language packs" in n for n in ctx.notes)
def test_games_already_in_the_library_get_their_language_packs_after_an_app_update(tmp_path):
"""lang_packs is read from the data folder (no APK analysis): filled in once for existing entries."""
from frameport.core import library
data = tmp_path / "data"
(data / "obb").mkdir(parents=True)
(data / "obb" / "de.lang").write_bytes(b"x")
g = {"data_dir": str(data), "analysis": {"package": "com.x.y", "extra": {}}}
assert library._refresh_data_fields(g, g["analysis"])
assert g["analysis"]["extra"]["lang_packs"] == ["de"]
assert not library._refresh_data_fields(g, g["analysis"]) # once
+36
View File
@@ -489,3 +489,39 @@ def test_flet_updates_are_serialized():
assert peak[0] == 1
finally:
Session.patch_control = original
def test_window_sessions_share_one_job_queue():
"""Every Flet session (a window reconnect builds a new app object) uses the same queue: a job started in an
old session is visible and the next one waits for it, instead of a second build of the same game at once."""
from frameport.ui import jobs
first, second = jobs.shared(), jobs.shared()
assert first is second
seen = []
listener = seen.append
first.subscribe(listener)
first.unsubscribe(listener)
first.unsubscribe(listener) # twice is harmless
assert listener not in first._listeners
def test_one_build_per_game_at_a_time():
from frameport import pipeline
assert pipeline._build_lock("com.x.y") is pipeline._build_lock("com.x.y")
assert pipeline._build_lock("com.x.y") is not pipeline._build_lock("com.x.z")
def test_window_geometry_restores_size_position_and_maximized():
from frameport.ui.app import window_geometry
first = window_geometry(None, 1.25)
assert first == {"width": 1600, "height": 975} # no position: the system places it
got = window_geometry({"size": [1400, 900], "pos": [320, 140], "maximized": True}, 1.0)
assert got == {"width": 1400, "height": 900, "left": 320, "top": 140, "maximized": True}
assert window_geometry({"size": [800, 500]}, 1.0) == {"width": 1000, "height": 680} # minimum size
# a monitor to the left (negative x) is fine; far off or malformed positions are ignored (GitHub #32)
assert window_geometry({"pos": [-1800, 50]}, 1.0)["left"] == -1800
for bad in ([-20000, 0], [100, -400], [99999, 0], ["a", 1], [1]):
assert "left" not in window_geometry({"pos": bad}, 1.0)