mirror of
https://github.com/spoopyghosty0/frameport.git
synced 2026-10-07 00:00:41 +02:00
Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
271ce56d08 | ||
|
|
0e47ce8f1a | ||
|
|
ad924669d3 | ||
|
|
311277ae40 | ||
|
|
bad59bfb5b | ||
|
|
9b57c4753f | ||
|
|
1301e60be1 | ||
|
|
069a74f97e | ||
|
|
683ae5bcf6 | ||
|
|
af904c62e6 | ||
|
|
f2d93af973 | ||
|
|
59fb47a827 | ||
|
|
9e169e069b | ||
|
|
eed6e4aaed | ||
|
|
9829ee1666 | ||
|
|
13069db28a | ||
|
|
7058105056 | ||
|
|
df5b949f1a | ||
|
|
3929ff0a8b | ||
|
|
4910440f56 | ||
|
|
bda9045be6 | ||
|
|
a7890d46de | ||
|
|
50ab3eb341 | ||
|
|
4313b52792 | ||
|
|
4f9ecf4801 | ||
|
|
9a5efa28f5 | ||
|
|
cf900cd9d4 | ||
|
|
ef21b33ca2 | ||
|
|
799f1bd9f1 | ||
|
|
44a056095d | ||
|
|
6037b13e88 | ||
|
|
c3a34ace99 | ||
|
|
05843633a7 | ||
|
|
5198f704e9 | ||
|
|
eeee7d2b84 | ||
|
|
772c26d91a | ||
|
|
db0a78ccc3 | ||
|
|
01d764e05c | ||
|
|
0c5c1638ed | ||
|
|
a49cfb0b57 | ||
|
|
0f975d2233 | ||
|
|
ccff9ab486 | ||
|
|
f2cf7db507 | ||
|
|
2f740bbb41 | ||
|
|
1462d3d471 | ||
|
|
22d10c1ff0 | ||
|
|
8b9657b2e6 | ||
|
|
bc6f6b7fe2 | ||
|
|
8f3c8b33ba | ||
|
|
8187c79d17 | ||
|
|
2ecf7f8624 | ||
|
|
6200662bc7 | ||
|
|
d2c72264be | ||
|
|
f37f7be9c7 | ||
|
|
d05dd27971 | ||
|
|
fd478f4c70 | ||
|
|
d834ffac42 | ||
|
|
3e11175001 | ||
|
|
85a11061d0 | ||
|
|
e26cb8b0db | ||
|
|
208d7bb4dd | ||
|
|
cf1a2c9181 | ||
|
|
ba9ccc3606 | ||
|
|
83a614d645 | ||
|
|
5734c1fdee | ||
|
|
af791a45b4 | ||
|
|
11c8802b07 | ||
|
|
70d519a5a9 | ||
|
|
4e00c88949 | ||
|
|
1b62d643f3 | ||
|
|
6bd4eb523f | ||
|
|
d22123c657 | ||
|
|
0137cd993b | ||
|
|
7b8e7c2c5d | ||
|
|
990331e5b6 | ||
|
|
56b370f582 | ||
|
|
ac628cd284 | ||
|
|
c12b2f6992 | ||
|
|
a110e8573f | ||
|
|
4fdeeaf829 | ||
|
|
dbabb37343 | ||
|
|
7afee4bf59 | ||
|
|
7367a35176 | ||
|
|
9948f946c5 | ||
|
|
3870500972 | ||
|
|
a7b02c00ee | ||
|
|
09c7bb6ea7 | ||
|
|
3761dfd62d | ||
|
|
f86d9021f9 | ||
|
|
83e901a682 | ||
|
|
246e5fc5ee | ||
|
|
17403779cb | ||
|
|
0e03e061a4 | ||
|
|
d8cf19fb20 | ||
|
|
7cd9a38eaf | ||
|
|
4f3593192f | ||
|
|
974426d1d0 | ||
|
|
b7a0e0cb5b | ||
|
|
38edc26092 | ||
|
|
e96e25bade | ||
|
|
67c991ca4f | ||
|
|
d2017194f3 | ||
|
|
7a11706b3a | ||
|
|
76d4390b19 | ||
|
|
2022d9986a | ||
|
|
9ff7edf93b | ||
|
|
a5722b50a0 | ||
|
|
0a13ca72a2 | ||
|
|
c53d754007 | ||
|
|
a1662da17d | ||
|
|
0141bad259 | ||
|
|
6ed95684dc | ||
|
|
a6ca8385a9 | ||
|
|
210410f125 |
No files matched your search
@@ -5,6 +5,15 @@ on:
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dev:
|
||||
description: "Publish the bundles as the dev build (testers: Settings → Updates → Install the latest dev build)"
|
||||
type: boolean
|
||||
default: true
|
||||
notes:
|
||||
description: "What testers should try (shown before they install it)"
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@@ -40,6 +49,8 @@ jobs:
|
||||
archive: FramePort-macos-arm64.zip
|
||||
- os: ubuntu-22.04 # oldest supported: the bundle needs the build host's GLib/glibc or newer
|
||||
archive: FramePort-linux-x64.tar.gz
|
||||
- os: ubuntu-22.04-arm # Linux ARM64 (same base as x64)
|
||||
archive: FramePort-linux-arm64.tar.gz
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
@@ -48,11 +59,14 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y ninja-build libgtk-3-dev
|
||||
- run: uv sync --extra dev
|
||||
- name: Dev build version (next patch + .dev<run number>; not committed)
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.dev
|
||||
run: uv run --no-project python scripts/dev_version.py ${{ github.run_number }}
|
||||
- id: flet
|
||||
run: uv run python scripts/package.py
|
||||
continue-on-error: ${{ runner.os == 'macOS' }}
|
||||
- name: macOS fallback (PyInstaller bundle)
|
||||
if: runner.os == 'macOS' && steps.flet.outcome == 'failure'
|
||||
continue-on-error: ${{ runner.os == 'macOS' || runner.arch == 'ARM64' }}
|
||||
- name: macOS / Linux ARM64 fallback (PyInstaller bundle)
|
||||
if: (runner.os == 'macOS' || runner.arch == 'ARM64') && steps.flet.outcome == 'failure'
|
||||
run: uv run --with pyinstaller python scripts/package.py --pyinstaller
|
||||
|
||||
# ---- signing: self-signed certificate on Windows, ad-hoc on macOS ----
|
||||
@@ -95,7 +109,9 @@ jobs:
|
||||
run: ditto -c -k --keepParent "$(find dist -maxdepth 3 -name '*.app' -type d | head -1)" ${{ matrix.archive }}
|
||||
- name: Package (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: tar czf ${{ matrix.archive }} -C dist --transform 's,^linux,FramePort,' linux
|
||||
run: | # flet build -> dist/linux; the PyInstaller fallback -> dist/FramePort (one folder)
|
||||
if [ -d dist/linux ]; then tar czf ${{ matrix.archive }} -C dist --transform 's,^linux,FramePort,' linux
|
||||
else tar czf ${{ matrix.archive }} -C dist FramePort; fi
|
||||
# self-update with this archive: unpack, verify the layout (+ the signer on Windows), run the real swap script
|
||||
- name: Update smoke test
|
||||
run: uv run python scripts/update_smoke.py ${{ matrix.archive }}
|
||||
@@ -137,10 +153,50 @@ jobs:
|
||||
git fetch --force origin "refs/tags/${tag}:refs/tags/${tag}"
|
||||
whatsnew=$(git tag -l --format='%(contents:body)' "$tag")
|
||||
[ -n "$whatsnew" ] || whatsnew=$(git tag -l --format='%(contents:subject)' "$tag")
|
||||
{ echo "FramePort ${tag}: Windows (x64), macOS (Apple Silicon) and Linux (x64)."; echo;
|
||||
{ echo "FramePort ${tag}: Windows (x64), macOS (Apple Silicon) and Linux (x64, ARM64)."; echo;
|
||||
if [ -n "$whatsnew" ] && [ "$(git cat-file -t "$tag")" = tag ]; then
|
||||
echo "## What's new"; echo; echo "$whatsnew"; echo; fi
|
||||
echo "Already have FramePort? It offers this update itself (Library → **Update now**)."
|
||||
echo; cat packaging/release-footer.md; } > "$notes" # short: the update dialog shows these notes
|
||||
gh release delete "$tag" --yes 2>/dev/null || true
|
||||
gh release create "$tag" out/* packaging/FramePort-selfsigned.cer --title "FramePort ${tag}" --notes-file "$notes"
|
||||
|
||||
dev-release:
|
||||
# "Run workflow" with dev ticked: replaces the rolling `dev` pre-release (never shown by the automatic update check;
|
||||
# testers install it from Settings → Updates). Same assets + SHA256SUMS as a release.
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.dev
|
||||
needs: bundle
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: astral-sh/setup-uv@v10.2.0
|
||||
- id: version
|
||||
run: echo "version=$(uv run --no-project python scripts/dev_version.py ${{ github.run_number }})" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: out
|
||||
merge-multiple: true
|
||||
- name: Wheel
|
||||
run: uv build --wheel -o out && ls out
|
||||
- name: Checksums
|
||||
run: cd out && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt
|
||||
- name: Publish the dev build
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
NOTES: ${{ inputs.notes }}
|
||||
run: |
|
||||
notes=$(mktemp)
|
||||
last=$(git describe --tags --abbrev=0 --match 'v*' 2>/dev/null || true)
|
||||
{ echo "Dev build **${VERSION}** from commit ${GITHUB_SHA::7} ($(date -u +%Y-%m-%d)). For testing fixes before"
|
||||
echo "the next release; you get that release as a normal update."; echo
|
||||
if [ -n "$NOTES" ]; then echo "## Please test"; echo; echo "$NOTES"; echo; fi
|
||||
if [ -n "$last" ]; then echo "## Changes since ${last}"; echo
|
||||
git log --no-merges --format='- %s' "${last}..HEAD" | cut -c1-160 | head -40; fi; } > "$notes"
|
||||
gh release delete dev --yes --cleanup-tag 2>/dev/null || true
|
||||
gh release create dev out/* packaging/FramePort-selfsigned.cer --prerelease --target "$GITHUB_SHA" \
|
||||
--title "FramePort dev build ${VERSION}" --notes-file "$notes"
|
||||
@@ -19,3 +19,4 @@ CLAUDE.local.md
|
||||
# outputs of `frameport report` / `parity` / ruff
|
||||
REPORT.md
|
||||
.ruff_cache/
|
||||
.claude/worktrees/
|
||||
@@ -21,7 +21,27 @@ Read `docs/PLAYBOOK.md` (symptom → fix) before debugging a game, and `docs/FRA
|
||||
the "Send files" dialog, game menu → "Add videos & files…" = `go("files", pkg)`; multi-select bar (download/
|
||||
delete); drag-and-drop from the OS via the `flet-dropzone` extension (Apache-2.0, Flutter `desktop_drop`), which
|
||||
only a `flet build` bundle contains: `files.dropzone_available()` keeps it out of source runs and the PyInstaller
|
||||
fallback, which would show an unknown control); settings; welcome; activity panel).
|
||||
fallback, which would show an unknown control); screenshots (Steam screenshots on the Frame, `install/screenshots.py`
|
||||
+ agent v46 `list_screenshots`/`delete_screenshots`: the Frame files every headset shot under SteamVR 250820, so
|
||||
launch.sh logs `start/end <unix>` to `<anchor>/plays.log` (upgrade_launchers adds it; Proton launchers exec → start
|
||||
only) and shots are matched by time; thumbnails cached in `<data>/screenshots-cache/<frame>/`, shown by asset URL;
|
||||
delete leaves screenshots.vdf alone (Steam rewrites it at exit); game menu → "Screenshots" = `go("screenshots",
|
||||
pkg)`); live view (`views/live.py` + `install/livestream.py`: the Frame's built-in SteamVR "headset view" webcam
|
||||
(`steamvr-v4l2cam.service` → v4l2loopback "SteamVR" /dev/video99, see docs/FRAME_RUNTIME.md) + the default
|
||||
output's pulse monitor (sound) → ffmpeg/x264 + AAC (qualities scale down only; "full" = SteamVR's size) →
|
||||
fragmented MP4 on an SSH exec channel's stdout (the script stops ffmpeg on stdin EOF) → relay on 127.0.0.1 (keeps
|
||||
init + fragments since the last keyframe of the *video* track for late viewers) → player page
|
||||
`install/live_player.py` (MSE; starts muted as browsers require, "Sound on" button; 0.3 s cushion, catches up at
|
||||
1.1x, seeks only when >2 s behind: seeking to the very edge starved it) opened
|
||||
in the user's default browser: Flet can't show video outside `flet build` bundles; the stream outlives the tab and
|
||||
stops on disconnect/window close); settings; welcome; activity panel). Files, Screenshots and the Library share right-click menus
|
||||
(one `ft.ContextMenu` per view, filled on right-click; on one of several selected items they act on the whole
|
||||
selection, `C.menu_targets`) and click-and-drag multi-select (`C.DragSelect`: pan start/end on the area + item
|
||||
hover events, which Flutter also sends with the button held; Flet can't report item positions, so no rubber band).
|
||||
Selection bars sit below the list: above it, their appearing shifted the items mid-drag. Async handlers (they
|
||||
await a FilePicker) must be coroutine functions or go through `page.run_task`: Flet doesn't await a lambda's
|
||||
coroutine (the Files row Download button silently did nothing). `ui_smoke.py --fake-frame --gestures` drives real
|
||||
mouse drags/right-clicks.
|
||||
User tags live in library entries (`tags`), filters in library setting `ui.library`.
|
||||
**Performance rules** (the app froze before): never put image bytes in controls — artwork is served by URL from the
|
||||
GUI assets dir (= user data dir; `ft.run(assets_dir=…)`), as thumbnails (`artwork/thumbs.py`, Pillow); the
|
||||
@@ -76,6 +96,11 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
|
||||
auto-start SteamVR on Play (`winhost.start_steamvr`); the Frame launcher always uses `/openxr`. UI (`game.py`
|
||||
where()) states per-game where it runs; installing an Oculus game on the Frame shows a warning. Migration
|
||||
`rift_frame_native` re-analyzes + re-derives existing entries.
|
||||
- Own artwork (0.8.0): game menu → "Use your own artwork…" (also from the Find artwork dialog) =
|
||||
`views/art_dialog.show_custom_art_dialog`: one slot per kind (portrait/landscape/hero/logo/icon), FilePicker →
|
||||
`sources.apply_custom` (Pillow check, ≥64 px, ≤40 MB, scaled to ≤3840 px, PNG if alpha/logo/icon else JPEG,
|
||||
replaces only that kind + its thumbnails, drops the generated cover/banner, writes `.picked` = "custom") /
|
||||
`remove_custom`; Steam shapes are still composed from what exists (`steam.py` PREFER).
|
||||
- Art for Rift games: `artwork/sources.py` — Quest version package (OculusDB packageName, exact name or +
|
||||
"Unplugged"-type suffix, never sequels) → Meta art; OculusDB square cover; Steam (exact names only); exe icon.
|
||||
- Store details (`artwork/details.py`, entry `details`): OculusDB (description, genres, publisher, website; by Quest
|
||||
@@ -86,6 +111,11 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
|
||||
set: the name on a colour from the title hash + the APK icon, `steam_set_for`; 2D Android apps get no store lookups) and tags: how it runs, the original platform
|
||||
(Meta Quest / Oculus Rift), genres, user tags — merged with tags set in Steam (non-Steam shortcuts can't hold a
|
||||
description).
|
||||
- Linux apps (GitHub #31, library kind `linux`, `linux.<slug>`): GUI = Add games → "Add a Linux app (arm64)…" /
|
||||
"…folder…" (`app.add_linux` job → `pipeline.add_linux_app`); game page `linux_summary` (program + Change…, AppImage,
|
||||
OpenXR, source) instead of recipe/patches, `C.missing_libraries` callout (Frame deployment, else last install);
|
||||
no Analyze/Rebuild/recipe/share/Game settings actions, Frame only; platform "Linux" badge + library filter; Steam
|
||||
tags "Linux app on Frame"/"Linux"; `_follow_catalog` skips them; local files of a lone AppImage = the file only.
|
||||
- Quest/Rift twins stay separate entries, shown and named in Steam "Title (Quest)"/"(Rift)" (`core/titles.py`).
|
||||
- `Recipe.as_is` = install unchanged (pre-patched libraries): `pipeline.prepare_as_is`; auto for APKs that already
|
||||
contain FrameBridge (`frame_patched`). For Rift it changes nothing (the dump is never modified; the Frame copy
|
||||
@@ -147,7 +177,7 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
|
||||
- `agent/frameport_agent.py` — runs **on the Frame** (python3 stdlib only), JSON over SSH. Owns the install layout,
|
||||
launch.sh template, Steam shortcuts (binary VDF), launch tests. Bump `AGENT_VERSION` when changing it.
|
||||
- `bootstrap/bootstrap.sh` — one-time Frame setup served by the pairing server (sshd, app key, avahi service, Lepton).
|
||||
- `catalog/games/<package>.yaml` — 38 recipes (34 verified 2026-09-28; Deadpool VR, 4XVR, NEX Player and AC Nexus's
|
||||
- `catalog/games/<package>.yaml` (installed apps also fetch these from GitHub `main`, see "Catalog updates") — 38 recipes (34 verified 2026-09-28; Deadpool VR, 4XVR, NEX Player and AC Nexus's
|
||||
90 Hz default confirmed later by the owner); `catalog/triage.yaml` — log signatures → fixes.
|
||||
- `native/` — sources of the prebuilt binaries in `artifacts/` (adapter, VrApi bridge patches, GL shim, stubs).
|
||||
`native/build.py` rebuilds them with NDK r27c (downloaded on demand into `native/.cache`, git-ignored; uses
|
||||
@@ -414,9 +444,102 @@ for steamos (Steam Input) → agent v33 `_keyboard` uinput keyboard ("Type on Fr
|
||||
Installing a second APK into a container with `pm install` re-runs Lepton's post-install hook on the **main** app
|
||||
(`lepton.active_app_id`; moves its files to /data/steam_app) and corrupts it on the next start (fix: touch the APK →
|
||||
re-bake); `cmd_real package install` skips the hook.
|
||||
**User reports (2026-10-04, issues #4-#10):** Steam shortcuts go to the signed-in account (`loginusers.vdf`
|
||||
MostRecent) else every account (agent v35 `library_users`; it used to refuse with >1 account → Play gave Steam's "Game
|
||||
configuration unavailable"); `launch` uses the shortcut's own appid and errors `NOT_IN_LIBRARY`, the app then adds it
|
||||
and plays. Unity IL2CPP fixes share one Cpp2IL run (`unity_text_input.Il2cppReturnPatch`, `ALL_TARGETS`, cache keyed by
|
||||
global-metadata.dat): `frame.unity_runtime_msaa_off` (OVRManager raises MSAA to 4x at runtime: "Switching to the
|
||||
recommended level" → Lucky's Tale restarted the headset; `OVRDisplay.get_recommendedMSAALevel` → 0) and
|
||||
`frame.unity_multipass` (Oculus XR Plugin multiview → MultiPass via `OculusSettings.GetStereoRenderingMode`; I Am Cat's
|
||||
right eye grey). Both checked against Toy Master's Cpp2IL output, not yet in a headset. VR4 quits itself (System.exit
|
||||
after the intro movie) → catalog `use_alt`. **Catalog changes reach existing games** without hardcoded migrations:
|
||||
recipes store `catalog_rev` (= `CatalogEntry.rev()`), `library._follow_catalog` re-derives non-user recipes whose entry
|
||||
changed; a maintained entry beats the user's shared copy when its `updated`/verified date is later (`catalog._newer`).
|
||||
**Round 2 of reports (2026-10-04):** VR4's campaign hang = one fragment shader reading an uninitialized loop counter
|
||||
(reporter's capture): vkshim `vk_shader_fix` setting (`<size>:<sha256>:<offset>:<words>`, from the recipe's `adapter:`;
|
||||
matched by size + SHA-256, words inserted into a copy) — on the device the module is fixed at load ("fixed shader
|
||||
module (6488 -> 6512 bytes)"); campaign itself not yet seen in a headset by us. Text settings (kind "str") stay out of
|
||||
the Game settings dialog (saving it dropped them). I Am Cat: `GetStereoRenderingMode` is inlined (no call sites) →
|
||||
`Il2cppReturnPatch.field_loads` rewrites the field read in `OculusLoader.Initialize` (Cpp2IL gives the field offset,
|
||||
`field:<name>`); verified with Toy Master: eye swapchains array=1 ×2 instead of array=2. Builds record `recipe_fp`
|
||||
(`patches/base.recipe_fingerprint`, `Patch.revision`): a changed recipe or revised patch shows "Update on Frame".
|
||||
Remembered Frames are found again after an address change (`Frame.relocate`: scan, same SSH host key, before
|
||||
login). Packaged apps show artwork by file path (`thumbs.use_file_paths`, #16). Diagnostics: this boot's kernel log.
|
||||
Device tests of requested games (2026-10-04, headless): I Am Cat, Myst 3.3.0, BattleGlide, Blade & Sorcery: Nomad
|
||||
start (RUNNING, frames). Roblox: SIGSEGV in je_free from libroblox.so ~3 s in (likely its anti-tamper vs the re-signed
|
||||
APK). BONELAB (Unity 2021.3 Vulkan, OVRPlugin 1.94): SIGSEGV with pc == fault addr in vkCreateInstance, called from
|
||||
libSLZQuestNative.so's Vulkan hooks into an unmapped (unloaded) library right after OVRPlugin's pre-init
|
||||
xrDestroyInstance; pinning openxr/vrclient libraries (RTLD_NODELETE) did NOT help — find the unloaded library with the
|
||||
linker's dlopen/dlclose logging next. Accounting+ (Unity 2017.4 built-in Oculus, libOVRPlugin + libvrapi): Unity
|
||||
never starts VR on the Frame (no OVRPlugin/OpenXR lines; runs as a 2D app), which is why its "controller setup"
|
||||
screen can't be passed — Unity 2017's Oculus device check, not the controller profiles. Cpp2IL can't read Unity 2017.
|
||||
The Frame's Android runtime (vrclient.so) knows oculus/touch_controller but not Meta's Touch Plus/Pro profiles
|
||||
(OVRPlugin suggests those too, routinely) → adapter `profile_remap`.
|
||||
Headset round 2 (2026-10-04): the Frame drops focus often (ms to 7 s; only some are presence/standby) → games pause
|
||||
or recentre (B&S Player.OnVRPresence → Teleport, BattleGlide/Unreal pauses); focus_hold now 1 s focused / 1 s max dip
|
||||
(longer must still pause). Myst crash = vrclient xrSyncActions race after FOCUSED → `sync_guard` (confirmed); its
|
||||
object glitches: app space warp suspected (FB_space_warp is advertised and used) → recipe `patch_disable_space_warp`.
|
||||
I Am Cat multipass: poses/times consistent, but every frame is submitted after the next xrWaitFrame (one period late;
|
||||
Zink + doubled draws) and the game clamps its physics step to 10 ms → judder while still; testing scale 0.8. Roblox's
|
||||
newest crash is on Fossilize's recording thread → vk_sanitize extended to own-engine libs (engine "Other").
|
||||
Accounting+: unity_oculus_check + native/ovrpshim (libfp_ovrp.so waits via ovrp_WaitToBeginFrame before Unity
|
||||
2017's ovrp_Update2) → VR in the headset at ~72 fps (2026-10-04), but stuck at "press any button" although input
|
||||
reaches its OVRInput cleanly (probe: both Touch connected 0x63, individual buttons, input focus 1) → works with issues.
|
||||
"outside of frame bounds" warnings stay (~2/frame) and are harmless.
|
||||
Steam library (GitHub #4/#21/#27, agent v38): shortcuts go to every Steam account (signed-in first; MostRecent isn't
|
||||
always the account on the Frame); stop_steam also waits for Steam's helpers; after the restart the agent re-reads
|
||||
shortcuts.vdf and writes once more if Steam put its old copy back (`shortcuts_lost`), else reports it. 0.6.3's Play
|
||||
auto-repair (`_add_then_play`) crashed (its job got a Job, not a reporter). Uploads resume on a transient OSError.
|
||||
Lepton's Android 11 has no clipboard service (134 services; checked with `podman exec … service check clipboard`):
|
||||
SDL/LÖVE apps crashed at start → `frame.sdl_clipboard` (`apk/dex.py`: in-place dex edit, nops one invoke, fixes
|
||||
the header checksum/signature; verified with LÖVE for Android 11.5, GitHub #24 Dramatic Shape). 2D apps (vr_kind none)
|
||||
keep every suggested patch that isn't about VR (`needs_vr = False`), not a fixed list. FramePort on the Frame:
|
||||
`frame/local.py` (127.0.0.1, own key authorized; "This Frame (experimental)"; app data in
|
||||
~/.local/share/frameport-app because ~/.local/share/frameport is the agent's) and Steam library changes wait while
|
||||
Desktop Mode is open. Verified on the device 2026-10-04 (install + launch test from the Frame). Library updates on the
|
||||
Frame run one at a time (agent v40 flock): two quick uninstalls used to bring a removed shortcut back (Roblox).
|
||||
Headset round 3 (owner's verdicts, 2026-10-04): Blade & Sorcery works — its freezes were the headset's wear sensor
|
||||
flickering off while worn (vrserver.txt "HMD off/on" 0.5-2 s) → per-game `focus_hold_ms=2500` (only this game reacts;
|
||||
not a default). BattleGlide works (focus_hold). Myst works with issues (object glitches; space warp ruled out, its
|
||||
recipe keeps it on). I Am Cat works with issues (judder; scale 0.8 no help). Roblox unsupported (je_free in
|
||||
libroblox, also with the Vulkan shim). Installs skip the Steam restart when the shortcut is unchanged and wait while a
|
||||
game runs (agent v37). New default fixes in FramePort's code reach games already in a library: after every app update
|
||||
`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):** on some Frames Steam never loads FramePort's shortcuts.vdf entries (same SteamOS build and arm64 beta client as the dev Frame; IDs correct; file written before Steam starts): Play → console_log `GameAction [AppID <id>] … RequestingLicense → UpdatingAppInfo → LaunchApp failed with AppError_9` (= "Game configuration unavailable", Steam treats the id as a store app). Cause unknown; agent v42/43 diagnostics: `launch` returns `steam` (started / error + code / silent from console_log), `collect_diag` adds `steam_library` (real Steam dir, beta, Steam start vs vdf write time, entries per account, devkit games) + `steam-console.txt` (incl. Steam's `logs/shortcuts.previous.txt` if present; steamclient.so has "LoadShortcuts: rejecting attempt to load shortcuts: invalid account ID"). **Fallback (agent v43):** when Play gets AppError_9 the agent registers the game through Steam's devkit interface (what Valve's Devkit Management Tool does, MIT: `devkit-1 steam://devkit-1/<~/.steam/steam.token>/create-shortcut?response=<file>&gameid=<id>&directory=~/devkit-game` written to ~/.steam/steam.pipe; answer file / `.error`; `~/devkit-game/<id>/launch.sh` = link to the game's launch.sh, `<id>-argv.json` ["launch.sh"] (relative to the folder), `<id>-settings.json` {steam_play 0, compat_tool ""}). Steam adds it live (no restart), picks its own appid (read back from shortcuts.vdf by DevkitGameID), shows it as a normal non-Steam game named "Devkit Game: <id>" (OpenVR 0, but VR works: owner-verified 2026-10-04), art copied to grid/<appid>*. Ids: letter first, then letters/digits/_ only (spaces, '-', leading digit → "missing/invalid arguments"). Later Plays use the devkit entry; uninstall (`devkit_unregister`, `delete-shortcut` live) and purge remove it. Verified on the dev Frame: register/launch/unregister; the AppError_9 trigger itself only in unit tests. GitHub #42 (two Steam accounts, neither MostRecent): Steam rewrote the active account's shortcuts.vdf without FramePort's entries right after starting, and added the devkit entry live without saving it, so `devkit_appid` (vdf only) failed ("Steam added the devkit entry but didn't save it"); agent v55 `devkit_appid_from_log` reads Steam's `sanitize shortcut app id "~/devkit-game/<id>/launch.sh": replacing 0 with N` console line. GitHub #41 (one account): same Steam behaviour, and every install restarts Steam, which forgets the never-saved devkit entry. Agent v56: the log fallback reads only the current session's console_log.txt; Play re-registers a devkit entry that gets AppError_9; art updates also write the devkit entry's grid art (`copy_grid_art`). Open: why some Frames' Steam never loads or saves shortcuts.vdf (single account too).
|
||||
**Exit game (GitHub #36, 2026-10-04):** `Apps.TerminateApp` (what Exit game calls; reachable for tests through Steam's CEF devtools on 127.0.0.1:8080, SharedJSContext, `Runtime.evaluate` — a stdlib websocket client is enough) closed both a normal shortcut and a devkit entry on the dev Frame within 1-3 s. SIGTERM to Steam's `reaper` alone left launch.sh + Lepton (setsid) + the container running (an earlier headset launch ran on for 87 min); SIGTERM to launch.sh cleans up in ~4 s. Agent v44: launch.sh's 2 s loop ends the game when its parent (the reaper) is gone; `upgrade_launchers` (from ensure_host_fixes) adds that to existing launchers in place. Which in-headset exit path fails is still unknown. Screenshots on the Frame: all under SteamVR's appid 250820 (`760/remote/250820/screenshots`, screenshots.vdf has creation time, no game).
|
||||
**SteamVR dashboard at game start (2026-10-04):** the dashboard (Resume game / controller / VR options) was open whenever a FramePort game started (also over Lepton's 2D launcher). Steam's UI exposes `SteamClient.OpenVR.VROverlay.{IsDashboardVisible,HideDashboard,ShowDashboard}` (CEF devtools, `steam_js` in the agent). Agent v44: launch.sh starts `_dashboard_worker` (waits for FrameBridge's first `pacing:` line in launch.log, then hides a visible dashboard for 25 s, at most 3 times; log `<base>/dashboard.log`; opt out with env FRAMEPORT_KEEP_DASHBOARD=1). Verified on the dev Frame (dashboard shown → 4XVR launched via Steam → hidden ~5 s after the first frames); not yet seen in the headset. **Headset (ITR2, 2026-10-05): too late** — Steam shows its frame menu (`valve.steam.gamepadui.frame.menu`, vrwebhelper_systemui.txt `[PooledPopups] Showing`) ~0.3 s after the game's first submitted frame (FrameBridge `new layer:`), but the first `pacing:` summary comes ~8 s later; the owner had pressed Resume (`[HideDashboard] return_to_game`) before the worker looked. Agent v52: watches from the first `new layer:` line (incremental log reads, 0.5 s polls, 30 s window). Agent v53: stops for good once the player opens the dashboard with the controller (`toggle_dashboard_action` in vrwebhelper_systemui.txt since the worker started): v52 closed it 60 ms after each press, and the game, paused for it, stayed paused.
|
||||
**Space warp / ITR2 (2026-10-04):** Into The Radius 2 (UE5, `libUnreal.so` + OVRPlugin, Vulkan) uses Application SpaceWarp (extra swapchains `376x376 format=97` motion vectors + `format=129` depth); #35 reports flickering textures. OVRPort's `patch_disable_space_warp` has no effect on UE5, and hiding XR_FB_space_warp in FrameBridge's enumerate doesn't reach the game either: **OVRPort's dispatcher offers/enables XR_FB_space_warp itself**. FrameBridge `hide_space_warp` (per game, off) hides it and strips `XrCompositionLayerSpaceWarpInfoFB` (1000171000) from the projection views (log `hide_space_warp: removed space warp info`); the game still renders its MV swapchains. Test build installed on the dev Frame; flicker not yet checked in a headset. Heuristic: UE5 + OVRPlugin shows it as an option (off). `equirect_emul` is suggested for Unreal games whose graphics API isn't detected ("GLES or unknown"); on Vulkan it switches itself off (Myst/Riven/ITR2): harmless, but Unreal Vulkan detection is a known gap.
|
||||
**PR #34 (merged 2026-10-04, Lucas-Mathieu):** `native/adapter/audio_metadata.h` patches Meta XR Audio Wwise (only build ID e1619e7f…, Batman: Arkham Shadow 1.4.1) so queued audio metadata isn't freed while the current audio frame references it (smoke-bomb crash). Verified headless: installs ("metadata reclamation follows …"), 72 fps; we added a once-per-second scan limit. Outside PRs: review source, rebuild `artifacts/` ourselves, merge locally (contributor's commit kept), push main.
|
||||
**Heuristics eval (2026-10-04):** `scripts/eval_heuristics.py "<VR CyberDeck Portable>"` → 19/44 recipes exact, 322/352 fields (most diffs: `frame.unity_text_input` suggested where older catalog recipes lack it; the rest are runtime-only findings: use_alt, vk_shader_fix, focus_hold, sync_guard, multipass). `PATCHED/` copies aren't scored (already converted).
|
||||
**Power (0.9, agent v47):** sidebar bar below the Frame card: Sleep / Restart / Shut down, each confirmed (`app.frame_power`, a running game asks again). logind answers CanSuspend/CanReboot/CanPowerOff = "challenge" for an SSH session but "yes" inside a user unit, so agent `power` runs `systemctl suspend|reboot|poweroff` from a transient `systemd-run --user --on-active=3` timer (the command answers first). Restart verified on the device (back in ~84 s, new boot id).
|
||||
**Proton default (agent v51, owner's choice 2026-10-05):** the newest **stable** ARM64 Proton is the default for PC VR games (`pick_proton`: asked-for name/alias, else newest installed stable, else any stable). Agent v49-50 defaulted to Experimental; the owner's headset A/B with Rick and Morty (Experimental 69 % reprojected frames, stable felt much smoother) reverted it. The game page's Customize shows `pcvr.proton_tool` as a dropdown (Stable (default) / Experimental = alias `proton-experimental`); `ensure_proton` installs a chosen one (it asks once more for the runtime Steam only names after Proton is installed; Experimental installed unattended on the device in 53 s). A PC VR launch test that fails on stable suggests Experimental (`pipeline.PROTON_TOOL`, `proton_alternative_worth_trying`, button "Try Proton Experimental and reinstall"). Remaining Rick and Morty stutter on head turns = the game rendering below the refresh rate (reprojection), not Proton.
|
||||
**USB cable link (verified 2026-10-05, cabled to the dev PC):** `usb0` is a USB **NCM** gadget (configfs g1: `ncm.usb0` + `ffs.adb`, Valve 28de:2460) set up by `usb-ncm-gadget@usb0.service`, which only runs with `ConditionPathExists=|/etc/systemd/system/adbd.service.d/steamos-devkit-enabled` = **Developer Mode only**. `usb-ncm-dnsmasq@usb0` serves DHCP with fixed `dhcp-host` entries: Frame 10.86.200.233, PC **10.86.200.234** (`frame/usb.py` FRAME_USB_IP/PC_USB_IP). Windows 11 binds its built-in "UsbNcm Host Device" (no driver); WSL mirrored sees eth 10.86.200.234. USB is high-speed (USB 2.0): upload 36.9 MB/s vs 11.3 MB/s home Wi-Fi. Frame→PC over the cable worked without a firewall change. `scripts/usb_autotest.py` (Windows via powershell.exe from WSL), `frameport frame usb-check`. Wizard "Set up with a USB cable" (`PairingServer(host=PC_USB_IP)`; the real bootstrap ran end to end over USB). Discovery dedupes by SSH host key and prefers USB > Frame hotspot > network (`discovery.dedupe`); a lost address is re-found by key (`Frame.relocate`, tested with a dead saved address).
|
||||
**Catalog updates without a release (2026-10-05):** apps fetch `catalog/games/*.yaml` from GitHub `main` (`recommend/catalog.refresh_remote`: one API call `git/trees/main?recursive=1` + raw.githubusercontent downloads of changed blobs, cached as `catalog-gh-<sha>.yaml`, every 6 h; GUI at start + Settings → Data "Check now"; CLI background thread + `frameport catalog-update`). `catalog.load()` only reads the cache. A remote entry is skipped (`unusable_reason`) when it names a patch/adapter key this app doesn't register, has a field `CatalogEntry` doesn't know, or `min_app` > this version: add `min_app` (or rely on new patch ids) when a config needs an unreleased FramePort. Remote beats bundled unless the bundled entry has a later updated/verified date; the user's own entries still win as before. Off: setting `catalog.auto_update`, env FRAMEPORT_NO_CATALOG_UPDATE; FRAMEPORT_CATALOG_URL still overrides the source. So: **pushing a catalog change to main reaches users within 6 h** (their recipes follow via catalog_rev → Update on Frame).
|
||||
**Start activity / QuestCraft / ITR2 pop-in (2026-10-05):** WiiCompiled's VR part (`QuestActivity`, SDL, process `:game`) stays behind Lepton's flat window when the launcher is shown (`device.text_input_window`). `frame.start_activity` (opt-in; analysis `extra.vr_activity` = the original APK's activity with Meta's VR category when it isn't the launcher) gives that activity's filter LAUNCHER and every other LAUNCHER becomes INFO, per element (`axml.set_start_activity`); Lepton's own `apk-info-extractor --print-activity-name` (on the Frame under Lepton/liblepton/apk_extractor) then answers QuestActivity. **OVRPort gives every MAIN activity LAUNCHER + VR categories**, so the VR activity must come from the original APK's analysis, not the converted manifest. Lepton has no activity override (`APP_ACTIVITY` is reset when app_metadata.sh is sourced). QuestCraft reaches Minecraft 1.21.5 (Fabric, Vivecraft, Sodium; LTW "Large Thin Wrapper" GL 3.0 on the Frame's Zink) and stops at `OpenGL error 1282` in `WindowFramebuffer` createTexture (Minecraft's crash report in `files/instances/1.21.5/crash-reports/`, Pojlib's `files/latestlog.txt`); the vrclient SIGSEGV / "pthread_mutex_lock called on a destroyed mutex" afterwards is only the shutdown (Unity's render thread still in vrclient while the instance is destroyed). ITR2 "models popping in and out" in game: Unreal reads user config from **internal** storage (`lepton-data/internal/<pkg>/files/UnrealGame/<Project>/<Project>/Saved/Config/Android/Engine.ini`, not external); `r.AllowOcclusionQueries=0` there broke its menus (removed again). Vulkan shim `vk_query_slots` (two slots per occlusion query) never saw ITR2 create an occlusion query pool, and the run with it crashed (Unreal RenderThread SIGSEGV, caught by sentry-native: no tombstone; the backtrace is in `cache/sentry/*/.sentry-native/*.run/*.envelope` with module offsets) - left off. Next suspect: Unreal 5 mobile HZB occlusion reading depth stored with Valve's FDM injection layer; test = launcher `VK_INSTANCE_LAYERS=''` (Lepton then loads neither VALVE_rpo nor VALVE_fdm_injection, Fossilize still). QuestCraft: LTW overrides glGetError and returns 0 with `LIBGL_NOERROR` set; Lepton passes `LEPTON_ENV_<NAME>` to the app as `<NAME>`, so catalog `lepton_env: {LEPTON_ENV_LIBGL_NOERROR: '1'}` gets Minecraft past the GL error 1282; then black picture (see the catalog entry). FrameBridge logs `new layer` once per layer type per process and projection views only for the first frames, so a second session in the same process (Vivecraft after Unity) needs `layer_debug=1`.
|
||||
**Vulkan validation / ITR2 solved (2026-10-05):** Khronos' validation layer can't come from Lepton (its layer dir is in the read-only guest image; the Linux copies on the Frame are glibc) and a global `debug.vulkan.layers` property (via the LEPTON_GFXRECON_FP_PROPS trick) kills the container at boot. Working recipe: bundle `libVkLayer_khronos_validation.so` (Khronos android-binaries release, arm64-v8a, stored uncompressed) into a test APK re-signed with the game's key (`apk.sign.sign`), install with `frameport install <pkg> --apk`, and set the Vulkan shim's `vk_validation=1` (it adds the layer at vkCreateInstance; findings under the logcat tag VALIDATION in launch.log, each message ID capped at 10). ITR2's flicker + windows behind models = Unreal's Qualcomm shader-resolve subpasses with a depth resolve of a single-sampled depth attachment (VUID-04908/-03179); `vk_spec_fixes=1` drops that resolve (its TRANSFER_DST half never applies to ITR2: the main depth is transient). Valve's VALVE_rpo layer removed ITR2's fog (catalog `lepton_env: VK_INSTANCE_LAYERS: VK_LAYER_VALVE_fdm_injection`). `r.ViewDistanceScale=2` in the internal Saved/Config/Android/Engine.ini only exists on the owner's Frame (the catalog can't write internal storage yet). Launch tests: Lepton prints a transient "is not a running context" on the first start after an APK change (agent v54 `not_started` waits 30 s for "Boot complete!").
|
||||
**GitHub #38/#39 (2026-10-05):** PowerWash Simulator stuck at "Waiting.." on a reporter's Frame = Unity sized the right-eye image rect past its swapchain (rect 268+1656 on a 1920-wide swapchain; the runtime's recommended size differs per Frame) and SteamVR rejected every frame (`xrEndFrame failed -25`, XR_ERROR_SWAPCHAIN_RECT_INVALID), after which the game stopped calling xrEndFrame. FrameBridge `rect_clamp` (default on; sizes noted in xrCreateSwapchain; clamped layers count as swapped) keeps projection/quad rects inside their swapchain; triage `swapchain-rect-invalid`. Not reproducible on the dev Frame with `scale` (Unity's eye sizing isn't just the recommended width); no regression there (72 fps). The adapter's revision was NOT bumped (that would mark every installed game outdated): affected users rebuild. The Room VR (#38) = Unity's render thread SIGSEGV in libgallium_dri.so ~30 ms after the game recreates its eye swapchain with samples=4 (FrameBridge retries samples=1); the game's own code turns MSAA on (not OVRManager); candidate fix: hide GL_EXT_multisampled_render_to_texture (GL shim) - needs the APK to test. The launch test passed both (render thread dead / no frames): triage gap.
|
||||
**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.
|
||||
@@ -429,6 +552,11 @@ tests, builds Windows x64 / macOS arm64 / Linux x64 bundles, signs, attests and
|
||||
`FramePort-selfsigned.cer`; notes = "What's new" from the annotated tag message + the short `packaging/release-footer.md`; owner: keep release
|
||||
notes short — a few "What's new" bullets, nothing long after them).
|
||||
Installed apps find the release themselves (self-update), so the notes are what users see in the update dialog.
|
||||
- **Dev builds (for testers, no release):** Actions → build → Run workflow (main), "dev" ticked, optional "notes"
|
||||
(what to test). The bundles get version `<next patch>.dev<run number>` (`scripts/dev_version.py`, not committed) and
|
||||
replace the rolling `dev` pre-release (`dev-release` job; same assets + SHA256SUMS). Automatic update checks ignore
|
||||
pre-releases; testers use Settings → Updates → "Install the latest dev build…" (`updates.check_dev`,
|
||||
`Updater.install_dev`). `parse_version` sorts 0.9.0 < 0.9.1.devN < 0.9.1, so testers get the next release normally.
|
||||
- **Release checklist:** bump `src/frameport/_version.py` (the only version; `scripts/package.py` fails a tag build
|
||||
whose tag ≠ `v<_version>`), commit, `git tag -a vX.Y.Z -m "FramePort X.Y.Z" -m "<What's new, Markdown bullets>"`,
|
||||
push the commit and the tag. Never publish a release without its `SHA256SUMS.txt` (the updater refuses it) and keep
|
||||
|
||||
@@ -23,6 +23,14 @@ uv run ruff check . # lint
|
||||
row and a unit test.
|
||||
- Native binaries in `artifacts/` are rebuilt with `python native/build.py` (downloads the NDK).
|
||||
|
||||
## Adding a tested game
|
||||
|
||||
Tested a game on the Steam Frame? The easiest way is in FramePort: open the game → **…** → **Share working config…**.
|
||||
It opens a prefilled GitHub issue with the exact recipe; after review a workflow turns it into
|
||||
`catalog/games/<package>.yaml`. Without the app: [working config form](https://github.com/spoopyghosty0/frameport/issues/new?template=working-config.yml). Something doesn't run: the game's
|
||||
**Report a problem…** (diagnostics zip, personal data removed) or the [problem report form](https://github.com/spoopyghosty0/frameport/issues/new?template=bug-report.yml).
|
||||
After catalog changes, regenerate the games list: `python scripts/compat_list.py`.
|
||||
|
||||
## Translating FramePort
|
||||
The app's texts (screens, help, patch and setting descriptions) can be translated; the command line, logs and
|
||||
diagnostics stay English. No programming needed:
|
||||
|
||||
@@ -22,11 +22,17 @@ Install games that target the Meta Quest, Android, or general PCVR onto your **V
|
||||
[What it changes](docs/FRAME_SETUP.md).
|
||||
- **Type on Frame:** use your computer's keyboard on the Frame: in VR apps, Android apps, Steam and the desktop.
|
||||
[More](#type-on-frame).
|
||||
- **One click per game:** convert, patch, sign, upload, add to Steam with artwork, launch test.
|
||||
- **One click per game:** convert, patch, sign, upload, add to Steam with artwork, launch test. Artwork that can't be found automatically can be picked from the stores or replaced with your own images.
|
||||
- **Per-game recipes:** a tested catalog plus detection rules; every patch explained in plain words.
|
||||
- **FrameBridge:** FramePort's OpenXR adapter emulates what the Frame natively lacks (passthrough, room, controller models,
|
||||
curved and 360° layers); game settings as simple switches.
|
||||
- **Beyond Quest:** Android apps as windows, PC VR via Proton or Revive, a Files tab with drag and drop.
|
||||
- **Beyond Quest:** Android apps as windows, PC VR via Proton or Revive, Windows (non-VR) games via Proton, a Files
|
||||
tab with drag and drop.
|
||||
- **Linux apps:** install arm64 Linux apps (AppImage, a folder, or a zip/tar archive) on the Frame with a Steam
|
||||
shortcut; they run natively on SteamOS.
|
||||
- **Screenshots tab:** the screenshots you took in the headset, sorted by game (matched by play time) and day;
|
||||
view them and download them to your computer.
|
||||
- **Live view tab:** watch what the headset shows, with sound, in a browser window on your computer.
|
||||
- **Self-updating** releases, redacted diagnostics, one-click problem reports and working-config sharing.
|
||||
|
||||
## Quick start
|
||||
@@ -36,17 +42,19 @@ Install games that target the Meta Quest, Android, or general PCVR onto your **V
|
||||
2. **Connect the Frame** (once):
|
||||
1. In FramePort click **Steam Frame → Show setup command**. Keep FramePort open; the Frame and your computer must
|
||||
be on the same Wi-Fi.
|
||||
2. On the Frame press the **Steam button → Power → Switch to Desktop**.
|
||||
3. Open the app menu (bottom-left corner), search for **Konsole** and open it.
|
||||
2. On the Frame open the **SteamVR dashboard → Launch a program → Desktop**: the Linux desktop opens on a virtual
|
||||
screen.
|
||||
3. Open the app menu (bottom-left corner of that desktop) → **System → Konsole** (or search for Konsole).
|
||||
4. Type the command FramePort shows exactly as shown (on-screen keyboard or any USB/Bluetooth keyboard) and press
|
||||
**Enter**. This will run the following [bash setup script](bootstrap/bootstrap.sh).
|
||||
5. After a few seconds the desktop closes by itself and the Frame returns to its normal view; that's expected. If
|
||||
5. After a few seconds the desktop closes by itself (Steam restarts once); that's expected. If
|
||||
Steam asks to install **Lepton**, confirm it. FramePort shows the Frame as connected within a minute. No
|
||||
password needed.
|
||||
3. **Add games → Scan a folder** with your game backups (APK + OBB, or PC VR game folders).
|
||||
4. Open a game → **Install on Frame**, then play it from the Frame's Steam library.
|
||||
|
||||
Full guide, firewalls and troubleshooting: [docs/INSTALL.md](docs/INSTALL.md).
|
||||
Full guide, firewalls and troubleshooting: [docs/INSTALL.md](docs/INSTALL.md). Questions (e.g. how to lay out games
|
||||
with OBB files): [docs/FAQ.md](docs/FAQ.md).
|
||||
|
||||
## Type on Frame
|
||||
|
||||
@@ -61,11 +69,35 @@ Unity apps whose text fields close the moment you select them on the Frame (no s
|
||||
fix, so Steam's on-screen keyboard and Type on Frame work in them too.
|
||||
[Details](docs/INSTALL.md#typing-on-the-frame).
|
||||
|
||||
## Screenshots
|
||||
|
||||
Screenshots you take in the headset show up in FramePort's **Screenshots** tab, grouped by day and matched to the game
|
||||
you were playing. Open one full size, step through them, and download single shots, a selection or all of them to
|
||||
your computer.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Live view
|
||||
|
||||
The **Live view** tab streams what the headset shows, with its sound, to your computer: click **Start live view** and
|
||||
it opens in your default web browser (full screen with a double-click; click **Sound on** to hear it, as browsers start
|
||||
videos muted). Pick 360p to 1080p, or the headset view's full size. The picture comes from SteamVR's built-in headset
|
||||
view on the Frame and is encoded there while you watch (about one CPU core), so stop it when you're done. It's black
|
||||
while the headset sleeps.
|
||||
|
||||
## Compatibility
|
||||
|
||||
If a game has already been tested with FramePort, it will automatically use the optimal game config. Otherwise, FramePort
|
||||
will attempt to guess key patches. If you find a new config that works for an app you are testing, please consider submitting it to the community!
|
||||
|
||||
**[List of tested games](docs/GAMES.md)**
|
||||
|
||||
**Tested something? Share it.** In FramePort open the game → **…** → **Share working config…** (it fills in the
|
||||
recipe for you) or **Report a problem…** (attaches a diagnostics zip with personal data removed). Without the app:
|
||||
[share a working config](https://github.com/spoopyghosty0/frameport/issues/new?template=working-config.yml) · [report a problem](https://github.com/spoopyghosty0/frameport/issues/new?template=bug-report.yml). Shared configs become built-in recipes for everyone.
|
||||
|
||||
## Built on
|
||||
|
||||
[OVRPort](https://github.com/Android-XR-Bridge/OVRPort) (Quest → OpenXR, originally
|
||||
@@ -81,6 +113,7 @@ What FramePort adds itself: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
|
||||
| [INSTALL.md](docs/INSTALL.md) | Install, connect, update, PC VR, files, problem reports |
|
||||
| [FRAME_SETUP.md](docs/FRAME_SETUP.md) | What setup changes on the Frame, networks and firewalls, undoing it |
|
||||
| [COMPATIBILITY.md](docs/COMPATIBILITY.md) | What runs and how well |
|
||||
| [GAMES.md](docs/GAMES.md) | Tested games and how well they run |
|
||||
| [PLAYBOOK.md](docs/PLAYBOOK.md) | Symptoms and fixes per game |
|
||||
| [FRAME_RUNTIME.md](docs/FRAME_RUNTIME.md) | Steam Frame runtime facts |
|
||||
| [ARCHITECTURE.md](docs/ARCHITECTURE.md) | How the code is organised |
|
||||
|
||||
+1363
-63
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,13 @@
|
||||
0f681f54b59cfad2efc8883aee5a0971c2fba09d9ba2dca15a136b0ac74a59b8 ./arm64-v8a/libfp_vk.so
|
||||
48a3ecad77ec0f3215b29070e994590eb9579e04d3c88a47f37f306f9aeb01d9 ./arm64-v8a/libfp_langpack.so
|
||||
a5b03bb7ae5d953d7ded2bf117b0a19c57fae604f16f54310847f8e89593dde6 ./arm64-v8a/libfp_ovrp.so
|
||||
b5949e9e90e4c51e2733b9f6cd3c857a447552ac7291aec340407c27b034b600 ./arm64-v8a/libfp_vk.so
|
||||
383054f8b3b41dde76d062c71856cd3163655e50009c08454bc1793f393ead65 ./arm64-v8a/libfpg.so
|
||||
8e00552d1ab90f82749db3caad4f773351fa8a28edcc5ea5cbd1b31c434ff32a ./arm64-v8a/libframe_xrshim.so
|
||||
3dfcb0f2bec47857bcecc7261c58e076d872d4649718c40850f29e10c75477dd ./arm64-v8a/libglshim.so
|
||||
dc62857b4f7a23b194060599339dfe72b38c16cdf4a9eb1b1f3b4d1fb9071a6d ./arm64-v8a/libopenxr_loader_generic.so
|
||||
0780f29b4844bcf5070929d8118cfcc2e7da2f16dd0dbfe1eaf12be7f5567401 ./arm64-v8a/libopenxr_loader_generic.so
|
||||
1feaeafad467c4cafdf2b018a4d84b0bee200c3f711697b4ce97e66a3ba256ca ./arm64-v8a/libovrplatformcompat.so
|
||||
32525cd0a9ee3d9993d8871cd6905bdcf22cde4f4ba28f5db6434ce7d6554758 ./arm64-v8a/libvrapi.so
|
||||
a79c598744b98b9bf581664a80bcee1a0d11a62fdcdb99f05a0f6f381b6498cd ./armeabi-v7a/libopenxr_loader_generic.so
|
||||
9c82f4ff57395e220329a22d0f0f47ce88b77132bed4dfb7b57809077fd0d6c4 ./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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# FramePort one-time Steam Frame setup. Run in the Frame's Desktop Mode terminal (Konsole):
|
||||
# FramePort one-time Steam Frame setup. Run in the Frame's desktop terminal (SteamVR dashboard -> Launch a program
|
||||
# -> Desktop, then System -> Konsole):
|
||||
# curl -fsS <pc-ip>:<port>/<code> | bash
|
||||
# (the FramePort app shows the exact line and serves this script while its Setup page is open).
|
||||
#
|
||||
@@ -128,6 +129,6 @@ if [[ ! -x "$DEVKIT_HELPER" || ! -f "$STEAM_CONFIG" ]] || \
|
||||
echo "Couldn't turn it on automatically. Turn it on in Settings > System > Developer, then run this command again."
|
||||
exit 1
|
||||
fi
|
||||
echo "Steam restarts to turn it on. That closes Desktop Mode in a few seconds and the Frame returns to its"
|
||||
echo "Steam restarts to turn it on. That closes the desktop in a few seconds and the Frame returns to its"
|
||||
echo "normal view; setup finishes on its own. If Steam asks to install Lepton, confirm it."
|
||||
echo "Then return to FramePort on your PC: the Frame appears as connected within a minute."
|
||||
@@ -0,0 +1,21 @@
|
||||
package: com.Aldin.WotW
|
||||
title: 'Waltz of the Wizard: Extended Edition'
|
||||
status: works
|
||||
notes: From what I tested, it just works. My only complaint is that the haptics go pretty crazy. But I don't remember
|
||||
what it was like when I played it in my Quest. So it could be fine. 100% playable.
|
||||
tested_version: 5.0.8.1578
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
known_good_sha256: 522cfebf954e1cab6054798479b0b32c5ba9e38cca83dd98db2ac0f7e3c0802a
|
||||
app: 0.9.1
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260922.6101926'
|
||||
agent: 48
|
||||
issue: 44
|
||||
source_hint: WotW
|
||||
@@ -0,0 +1,20 @@
|
||||
package: com.Appnori.AllInOneSports
|
||||
title: AllInOneSports
|
||||
status: works
|
||||
tested_version: 1.9.0
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
- frame.oculusos
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
known_good_sha256: a1f9535ac569068bba25f137f131db9d4c3e997c072f3e790beac8ffef701fe3
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 35
|
||||
issue: 13
|
||||
source_hint: All In One Sports
|
||||
@@ -0,0 +1,28 @@
|
||||
package: com.Armature.VR4
|
||||
title: VR4
|
||||
status: works
|
||||
notes: Installs the no-ForceQuit build and fixes a campaign shader that hung the GPU after the opening cutscene.
|
||||
details: Entering the campaign gave a black screen, slowing audio and a crash (Mercenaries loaded). One fragment shader
|
||||
reads a loop counter before setting it, which hangs the GPU; the Vulkan shim zeroes it (vk_shader_fix). The
|
||||
no-ForceQuit build is kept. Diagnosed and confirmed on a Frame by the reporter of GitHub issue 10.
|
||||
tested_version: '2.3'
|
||||
engine: Unreal
|
||||
xr: VrApi
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
use_alt: true
|
||||
adapter:
|
||||
# one campaign shader reads an uninitialized loop counter and hangs the GPU (black screen, slowing audio, crash);
|
||||
# the Vulkan shim inserts two OpStores that zero it and its accumulator (from the reporter's capture, GitHub
|
||||
# issue 10)
|
||||
vk_shader_fix: 6488:5dcd842db8d21e3fdd13ec916d2e34dd0cfdf12a92fffaf8a27115072ef55c59:2624:0x0003003e,138,18,0x0003003e,150,42
|
||||
verified:
|
||||
date: '2026-10-02'
|
||||
known_good_sha256: 40ff74e37264b28ae8826923b69d0731d9620094c76462be34159643d6ae91b3
|
||||
app: 0.3.4
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 26
|
||||
issue: 1
|
||||
updated: '2026-10-04'
|
||||
source_hint: Resident Evil 4
|
||||
@@ -0,0 +1,36 @@
|
||||
package: com.CMGames.IntoTheRadius2
|
||||
title: Into The Radius 2
|
||||
status: works
|
||||
notes: Plays well (owner-verified 2026-10-05). Space warp is off, the headset's brief focus losses are hidden
|
||||
(focus_hold, up to 2.5 s), only Valve's foveation layer is loaded (its render-pass optimizer removed the fog) and
|
||||
an invalid depth resolve in Unreal's render passes is dropped (vk_spec_fixes; it made models flicker and windows
|
||||
show behind them). Needs FramePort 0.10.0 or newer. Loading a save can take over a minute.
|
||||
details: Unreal Engine 5 game that uses Meta's Application SpaceWarp (extra motion-vector and depth swapchains). OVRPort's
|
||||
patch_disable_space_warp doesn't reach Unreal Engine 5, so FrameBridge's hide_space_warp hides XR_FB_space_warp and
|
||||
removes the space warp info from the eye images. Working config shared in GitHub issue 35. In the headset
|
||||
(2026-10-05) the Frame dropped focus for 0.4 s and 1.0 s within ten seconds and Unreal paused each time; loading a save
|
||||
shows no frames for 40-80 s while the game's Sentry SDK (debug mode) logs its breadcrumbs. Valve's VALVE_rpo
|
||||
(render-pass optimizer) Vulkan layer removes the game's fog (owner-verified 2026-10-05; with only VALVE_fdm_injection
|
||||
loaded the fog renders), which also hid the distance culling; ruled out for the remaining pop-in - Vulkan occlusion
|
||||
query slots, Valve's FDM layer. The cause, found with Khronos' validation layer (vk_validation) - Unreal's render
|
||||
passes use Qualcomm's shader resolve (VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM) together with a depth resolve
|
||||
of a single-sampled depth attachment (VUID-VkSubpassDescription2-flags-04908, -03179), harmless on Quest's driver,
|
||||
wrong depth on the Frame's Mesa; the Vulkan shim's vk_spec_fixes drops that resolve.
|
||||
tested_version: 1.2.4
|
||||
engine: Unreal
|
||||
xr: OpenXR
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
adapter:
|
||||
equirect_emul: 1
|
||||
hide_space_warp: 1
|
||||
focus_hold: 1
|
||||
focus_hold_ms: 2500
|
||||
vk_spec_fixes: 1
|
||||
lepton_env:
|
||||
VK_INSTANCE_LAYERS: VK_LAYER_VALVE_fdm_injection
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
issue: 35
|
||||
min_app: 0.10.0
|
||||
source_hint: Into The Radius 2
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.CyanWorlds.Myst
|
||||
title: Myst
|
||||
status: issues
|
||||
notes: Minor graphical glitches on some objects.
|
||||
details: The crash is in the Frame's SteamVR runtime (vrclient.so CVRInputLatest::UpdateActionStateInternal via
|
||||
xrSyncActions) on the first input sync after focus, in 2 of 4 headset sessions. sync_guard serialises input syncs
|
||||
with event polling and pauses them for 250 ms after focus returns (confirmed in the headset, no crash). The object
|
||||
glitches are not application space warp (turning it off didn't change them and ran slightly worse).
|
||||
tested_version: 3.3.0
|
||||
engine: Unreal
|
||||
xr: OpenXR
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
adapter:
|
||||
sync_guard: 1
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
updated: '2026-10-04'
|
||||
source_hint: Myst
|
||||
@@ -0,0 +1,20 @@
|
||||
package: com.CyanWorlds.Riven
|
||||
title: Riven
|
||||
status: works
|
||||
notes: Plays as expected.
|
||||
tested_version: 1.9.0
|
||||
engine: Unreal
|
||||
xr: OpenXR
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
adapter:
|
||||
equirect_emul: 1
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
known_good_sha256: 7c211588f39c21d67998ac6a6aeb44a8ad66c6551a1b0feb1bcf44e2cef98bdf
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 35
|
||||
issue: 26
|
||||
source_hint: Riven
|
||||
@@ -0,0 +1,16 @@
|
||||
package: com.GhostlyBirdGames.BattleGlide
|
||||
title: BattleGlide
|
||||
status: works
|
||||
notes: Freezes from the headset's brief focus losses are hidden (focus_hold).
|
||||
details: The Frame drops the session out of focus for ~0.5 s every few seconds (11 times in 80 s of play) and Unreal
|
||||
pauses each time; focus_hold hides dips up to 1 s once the game has been focused for 1 s. Longer dips (real
|
||||
interruptions) still pause it.
|
||||
tested_version: 0.4.1 (BETA)
|
||||
engine: Unreal
|
||||
xr: OpenXR
|
||||
adapter:
|
||||
focus_hold: 1
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
updated: '2026-10-04'
|
||||
source_hint: BattleGlide
|
||||
@@ -0,0 +1,23 @@
|
||||
package: com.NewFolderGames.IAmCat
|
||||
title: I Am Cat
|
||||
status: issues
|
||||
notes: The view vibrates slightly, even when holding still.
|
||||
details: Unity 2022.3 with the Oculus XR Plugin falls back to GLES (Zink) on the Frame, where its single-pass
|
||||
(multiview) rendering drew the right eye wrong (GitHub issue 8); frame.unity_multipass renders each eye in its own
|
||||
pass (OculusSettings.GetStereoRenderingMode + its inlined read in OculusLoader.Initialize). Poses and frame times
|
||||
are consistent, but every frame reaches the runtime one display period late (two passes on Zink) and the game
|
||||
clamps its physics step to 10 ms, so the view judders; scale 0.8 didn't change it. Possible next steps are fixing the
|
||||
multiview path instead or the game's fixed timestep.
|
||||
tested_version: 1.4.0.0
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
- frame.unity_multipass
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-03'
|
||||
issue: 8
|
||||
updated: '2026-10-04'
|
||||
source_hint: I Am Cat
|
||||
@@ -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
|
||||
@@ -0,0 +1,15 @@
|
||||
package: com.StressLevelZero.BONELAB
|
||||
title: BONELAB
|
||||
status: unsupported
|
||||
notes: Crashes while starting its graphics (Vulkan); no fix yet.
|
||||
details: SIGSEGV in vkCreateInstance, called from the game's own Vulkan hooks (libSLZQuestNative.so) into code that no
|
||||
longer exists, right after OVRPlugin's pre-initialization creates and destroys an OpenXR instance. Keeping the
|
||||
runtime (vrclient.so) and Steam's Fossilize layer loaded didn't help, so the stale pointer is to memory freed with
|
||||
that first instance.
|
||||
tested_version: 1.2974.57485
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
updated: '2026-10-04'
|
||||
source_hint: BONELAB
|
||||
@@ -0,0 +1,22 @@
|
||||
package: com.Warpfrog.BladeAndSorcery
|
||||
title: 'Blade & Sorcery: Nomad'
|
||||
status: works
|
||||
notes: The headset's brief focus losses are hidden (focus_hold, up to 2.5 s).
|
||||
details: The Frame's runtime drops focus now and then (mostly 1.5-7 s, some only milliseconds); the game pauses
|
||||
("System menu opened", the world freezes) and re-aligns the player when focus returns (Player.OnVRPresence ->
|
||||
Teleport, the sideways jump). They match the headset's wear sensor flickering off while worn (SteamVR "HMD off" 0.5-2
|
||||
s), which only this game reacts to; focus_hold hides dips up to 2.5 s here. Rendering keeps 72 fps throughout.
|
||||
tested_version: 1.3.1
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
adapter:
|
||||
focus_hold: 1
|
||||
focus_hold_ms: 2500
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
updated: '2026-10-04'
|
||||
source_hint: Blade & Sorcery Nomad
|
||||
@@ -0,0 +1,23 @@
|
||||
package: com.beatgames.beatpaber
|
||||
title: Beat Saber (co-existence build)
|
||||
status: works
|
||||
notes: A Beat Saber build with its own package name, so a modded and an unmodded Beat Saber can be installed side by
|
||||
side.
|
||||
details: The submitted build's app label was very long and the game didn't appear in the Frame's Steam library (GitHub
|
||||
issue 27, a shortcut Steam dropped again; fixed in 0.7.0); the recipe's title names it.
|
||||
tested_version: 1.45.1_27839
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
known_good_sha256: 9965b01d5d1a3707bce1762f60d5419ce3e89bc095c63586f6940bb69696e9fd
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 35
|
||||
issue: 29
|
||||
source_hint: Beat Saber
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.beatgames.beatsaber
|
||||
title: Beat Saber
|
||||
status: works
|
||||
tested_version: 1.40.8_7379
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-03'
|
||||
known_good_sha256: ee720e040931f2547f7611e58ec5ad72d86e800dd4cf3135f576019683f2f359
|
||||
app: 0.6.1
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 33
|
||||
issue: 6
|
||||
source_hint: Beat Saber
|
||||
@@ -0,0 +1,17 @@
|
||||
package: com.camouflaj.salmon
|
||||
title: Marvel's Iron Man VR
|
||||
status: works
|
||||
tested_version: 0.1.0-250068
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
known_good_sha256: 41e0ab90f622afd50accb0b6e2553520d30a6cc82e5ab4cbb2341b48f7316a71
|
||||
app: 0.9.1
|
||||
overport_cli: 1.2.5
|
||||
issue: 47
|
||||
source_hint: Marvel's Iron Man VR
|
||||
@@ -0,0 +1,17 @@
|
||||
package: com.crowscrowscrows.AccountingPlus
|
||||
title: Accounting+
|
||||
status: issues
|
||||
notes: Starts in VR, but doesn't get past its "press any button" screen.
|
||||
details: Unity 2017.4 built-in Oculus support. frame.unity_oculus_check gets VR started (Meta's system-app check and
|
||||
the frame wait its legacy loop never makes, libfp_ovrp.so), ~72 fps. Controller input reaches the game's OVRInput
|
||||
cleanly (both Touch controllers connected, individual button bits, input focus 1 while focused) but the screen
|
||||
doesn't continue; Cpp2IL can't read this Unity version to see what it waits for.
|
||||
tested_version: 1.24.35
|
||||
engine: Unity
|
||||
xr: VrApi
|
||||
frame:
|
||||
- frame.unity_oculus_check
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
updated: '2026-10-04'
|
||||
source_hint: Accounting+
|
||||
@@ -0,0 +1,18 @@
|
||||
package: com.enhanceexperience.tetriseffect
|
||||
title: TetrisEffect
|
||||
status: works
|
||||
notes: Opened the game, messed around with the menu, and played the first level. Works great.
|
||||
tested_version: 2.0.2
|
||||
engine: Unreal
|
||||
xr: VrApi
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
known_good_sha256: 9ea10027ad8b7aefba8c14f23575c9cbbcaf3b38d12b971ea9c06635721b23c1
|
||||
app: 0.9.1
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260922.6101926'
|
||||
agent: 48
|
||||
issue: 45
|
||||
source_hint: tetriseffect
|
||||
@@ -0,0 +1,20 @@
|
||||
package: com.iillusions.spacepiratetrainerquest
|
||||
title: Space Pirate Trainer Quest
|
||||
status: works
|
||||
tested_version: '1.97'
|
||||
engine: Unity
|
||||
xr: VrApi
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
- frame.unity_runtime_msaa_off
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
known_good_sha256: 711d87e6c1fa14fdcdc8bab5792657523d0281b5d904f7f1abafd98f3189d2c0
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 35
|
||||
issue: 14
|
||||
source_hint: Space Pirate Trainer
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.lakento.dinosquest
|
||||
title: Dinosaur Island
|
||||
status: works
|
||||
tested_version: 1.7.5
|
||||
engine: Unity
|
||||
xr: VrApi
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-03'
|
||||
known_good_sha256: 41ecbc728dc533eebcc3980e140fe1764fbd1958735d8a299c63fa9cda13a923
|
||||
app: 0.6.2
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 33
|
||||
issue: 12
|
||||
source_hint: DINOSAUR ISLAND
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.owlchemylabs.jobsimulator
|
||||
title: Job Simulator
|
||||
status: works
|
||||
tested_version: 1.4.0.6515
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-03'
|
||||
known_good_sha256: 64638d7f93bb93cc61f422a43a08bb0d35b9bb4b463e90a42da7002147f03d1b
|
||||
app: 0.6.2
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 33
|
||||
issue: 11
|
||||
source_hint: Job Simulator
|
||||
@@ -0,0 +1,20 @@
|
||||
package: com.parkline.wander
|
||||
title: Wander
|
||||
status: works
|
||||
tested_version: '0.3569'
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
- frame.unity_runtime_msaa_off
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
known_good_sha256: c0c9de22b3646f35009a53796757d26f8d4e95259713f26a18fae2be995b23aa
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 35
|
||||
issue: 17
|
||||
source_hint: Wander
|
||||
@@ -0,0 +1,21 @@
|
||||
package: com.playful.LuckysTale
|
||||
title: Lucky's Tale
|
||||
status: issues
|
||||
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
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
- frame.unity_runtime_msaa_off
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-03'
|
||||
issue: 9
|
||||
updated: '2026-10-04'
|
||||
source_hint: Luckys Tale
|
||||
@@ -0,0 +1,28 @@
|
||||
package: com.qcxr.qcxr
|
||||
title: QuestCraft
|
||||
status: works
|
||||
notes: Minecraft runs in VR (Vivecraft, about 72 fps; drops while worlds load). Needs FramePort 0.10.0 or newer for
|
||||
the picture (older versions show black). On first start QuestCraft downloads its Java runtime, which didn't unpack on
|
||||
the Frame once (see details).
|
||||
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 once left nothing behind ("libjvm.so not found"; unpacked by hand). Two
|
||||
Frame fixes, both owner-verified 2026-10-05. (1) Minecraft 1.21.5 checks GL errors strictly and aborted with
|
||||
"OpenGL error 1282", an error the Frame's Mesa (Zink) reports where Quest's driver doesn't; QuestCraft's GL-to-GLES
|
||||
layer (LTW) ignores GL errors when LIBGL_NOERROR is set, which Lepton passes from LEPTON_ENV_LIBGL_NOERROR. (2) LTW
|
||||
passes desktop GL_DEPTH_COMPONENT32 through, which Mesa rejects, so every framebuffer was incomplete and the picture
|
||||
black; frame.ltw_depth (automatic for APKs with libltw.so) loads GLES through a shim that asks for
|
||||
GL_DEPTH_COMPONENT32F. Left over, harmless so far - Mesa still reports about 4 GL_INVALID_OPERATION per frame
|
||||
("in glthread", so the call is unknown; mesa_glthread=false would name it).
|
||||
tested_version: 6.0.0-RC4
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
lepton_env:
|
||||
LEPTON_ENV_LIBGL_NOERROR: '1'
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
updated: '2026-10-05'
|
||||
source_hint: QuestCraft
|
||||
@@ -0,0 +1,20 @@
|
||||
package: com.resolutiongames.abvriop.santacruz
|
||||
title: palazzo_santacruz
|
||||
status: works
|
||||
notes: Played a few levels. Passthrough also works.
|
||||
tested_version: 3.7.6.10866-release
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
known_good_sha256: 394214a68297c1e5b019dc4f65b145e7bd0e98604205616364e0c151c1afd894
|
||||
app: 0.9.1
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260922.6101926'
|
||||
agent: 48
|
||||
issue: 46
|
||||
source_hint: abvriop
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.resolutiongames.cookinggame
|
||||
title: Cook-Out
|
||||
status: works
|
||||
tested_version: 1.20.0.10625-release
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-03'
|
||||
known_good_sha256: 7217649c503adf76f3a959fc72858c446c2a42a9ce9e209286977b1950397915
|
||||
app: 0.6.1
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 33
|
||||
issue: 3
|
||||
source_hint: com.resolutiongames.cookinggame
|
||||
@@ -0,0 +1,14 @@
|
||||
package: com.roblox.client
|
||||
title: Roblox
|
||||
status: unsupported
|
||||
notes: Crashes on its first VR frame on the Frame.
|
||||
details: SIGSEGV on Roblox's render thread right after it re-creates its eye swapchains (format 37, which the Frame
|
||||
doesn't offer, retried as sRGB 43) — in its own code or inside the runtime's xrBeginFrame. No integrity or login
|
||||
check involved; also needs an online login once it runs.
|
||||
tested_version: 2.741.1051
|
||||
engine: Other
|
||||
xr: OpenXR
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
updated: '2026-10-04'
|
||||
source_hint: Roblox
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.steelcrategames.keeptalkingandnobodyexplodes
|
||||
title: Keep Talking and Nobody Explodes
|
||||
status: works
|
||||
tested_version: 1.10.15
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
verified:
|
||||
date: '2026-10-04'
|
||||
known_good_sha256: 1a6f18e6d7b077e2662c7e633d473018067f4c871f5c45c4632c58233feaeac5
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20260930.6234839'
|
||||
agent: 35
|
||||
issue: 15
|
||||
source_hint: Keep Talking and Nobody Explodes
|
||||
@@ -1,11 +1,12 @@
|
||||
package: com.stremio.vrone
|
||||
title: Stremio
|
||||
status: issues
|
||||
status: works
|
||||
notes: 'Unity 6 VR media centre (its interface is web pages in Vuplex 3D WebView). Text fields closed at once on the
|
||||
Frame (no system keyboard): frame.unity_text_input keeps them selected and device.text_input_window shows the
|
||||
Android window so Steam''s on-screen keyboard (or Type on Frame from the PC) types into them; confirmed in the
|
||||
headset by the owner (2026-10-03). Known issue: the add-ons page stays blank in VR (the add-on sync itself
|
||||
succeeds). "Play in an external player" can''t reach another app: Lepton sends every link to Steam''s browser.'
|
||||
headset by the owner (2026-10-03), who confirmed it working. Note: the add-ons page can stay blank in VR (the
|
||||
add-on sync itself succeeds). "Play in an external player" can''t reach another app: Lepton sends every link to
|
||||
Steam''s browser.'
|
||||
details: 'Patches: frame.unity_text_input (TMP_InputField.TouchScreenKeyboardShouldBeUsed -> false,
|
||||
isKeyboardUsingEvents -> true; uGUI InputField too), device.text_input_window (lepton-show-flatscreen).'
|
||||
tested_version: 0.7.5
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
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). Once your game is imported, turn on "Start straight in VR" (and off "Show the app''s
|
||||
Android window") and update it on the Frame: it then opens in VR without the flat launcher window, which otherwise
|
||||
stays in view (turn it off again to import another game). 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) that
|
||||
stays in view after it starts the VR part (QuestActivity, process :game); frame.start_activity makes QuestActivity
|
||||
the start activity (owner-verified 2026-10-05, opens straight in VR), but it skips the launcher's import step, so it
|
||||
stays off by default.
|
||||
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-05'
|
||||
source_hint: WiiCompiled
|
||||
@@ -0,0 +1,20 @@
|
||||
package: rift.superhot_vr
|
||||
title: SUPERHOT VR
|
||||
status: works
|
||||
notes: 'Supports SteamVR/OpenXR itself: runs directly, without Revive.'
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
kind: rift
|
||||
pcvr:
|
||||
- pcvr.xr_timefix
|
||||
- pcvr.steamvr_tuning
|
||||
pcvr_remove:
|
||||
- pcvr.revive
|
||||
as_is: true
|
||||
verified:
|
||||
date: '2026-10-05'
|
||||
known_good_sha256: 143dd3c6a93a45819a98e3cca8fd1535b461cdf860c927d955ca54815faf5d7b
|
||||
app: 0.6.3
|
||||
overport_cli: 1.2.5
|
||||
issue: 28
|
||||
source_hint: SUPERHOT VR
|
||||
@@ -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
|
||||
+63
-2
@@ -13,6 +13,11 @@ signatures:
|
||||
severity: fatal
|
||||
diagnosis: 32-bit-only APK. The Steam Frame has no AArch32; this cannot run. Use the PC (Rift) version via Revive.
|
||||
suggest: []
|
||||
- id: swapchain-rect-invalid
|
||||
pattern: 'xrEndFrame failed -25\b'
|
||||
severity: fatal
|
||||
diagnosis: The runtime rejects the game's frames because an image rect reaches past its swapchain (by a few pixels on some Frames); the game stops drawing (e.g. stuck at a "Waiting" box). FrameBridge from FramePort 0.10.1 clamps the rects - rebuild and reinstall the game.
|
||||
suggest: [frame.adapter]
|
||||
- id: missing-ovr-symbol
|
||||
pattern: '(UnsatisfiedLinkError|cannot locate symbol) .*"?(ovr_[A-Za-z0-9_]+|ovrMessageType_ToString)'
|
||||
severity: fatal
|
||||
@@ -44,7 +49,43 @@ signatures:
|
||||
pattern: 'zink.*DEVICE[_ ]LOST|VK_ERROR_DEVICE_LOST'
|
||||
severity: fatal
|
||||
diagnosis: The GPU hung (Zink/Mesa). For GLES Unity games MSAA render-to-texture is the usual cause.
|
||||
suggest: [frame.unity_no_msaa]
|
||||
suggest: [frame.unity_no_msaa, frame.unity_runtime_msaa_off]
|
||||
- id: unity-runtime-msaa
|
||||
pattern: 'recommended MSAA level is [248]\. Switching to the recommended level'
|
||||
severity: info
|
||||
diagnosis: The game's OVRManager turns MSAA on at runtime (QualitySettings can't keep it off). On GLES this can
|
||||
hang the Frame's GPU or restart the headset; if it does, keep it off in the game's code.
|
||||
suggest: [frame.unity_runtime_msaa_off]
|
||||
- id: runtime-input-crash
|
||||
pattern: 'vrclient\.so[^\n]*(UpdateActionStateInternal|sxr_xrSyncActions)'
|
||||
severity: fatal
|
||||
diagnosis: The Frame's runtime crashed in its controller-input code (xrSyncActions), typically right after the game
|
||||
got focus. sync_guard serialises input syncs and pauses them briefly after focus returns.
|
||||
suggest: [adapter.sync_guard]
|
||||
- id: focus-dip-teleport
|
||||
pattern: 'OnVRPresence[^\n]*Teleport'
|
||||
severity: warning
|
||||
diagnosis: The game moves the player when the headset reports presence again, which the Frame's brief focus dips
|
||||
trigger (the view jumps). focus_hold hides dips under 600 ms.
|
||||
suggest: [adapter.focus_hold]
|
||||
- id: unity-vr-device-none
|
||||
pattern: 'NewtonVR.*(not setup properly|no headset found)|Loaded VR device: None|XR: Oculus could not be loaded'
|
||||
severity: fatal
|
||||
diagnosis: Unity didn't start its Oculus VR device (older Unity checks for Meta's system apps first), so the game
|
||||
runs as a hidden 2D app.
|
||||
suggest: [frame.unity_oculus_check]
|
||||
- id: sdl-no-clipboard
|
||||
pattern: 'ClipboardManager\.addPrimaryClipChangedListener|SDLClipboardHandler\.<init>'
|
||||
severity: fatal
|
||||
diagnosis: An SDL app (SDL2 / LÖVE) crashed at start because Lepton's Android has no clipboard service.
|
||||
suggest: [frame.sdl_clipboard]
|
||||
- id: controller-profile-rejected
|
||||
pattern: 'PATH_UNSUPPORTED.*xrSuggestInteractionProfileBindings|xrSuggestInteractionProfileBindings.*(-48|PATH_UNSUPPORTED)'
|
||||
severity: info
|
||||
diagnosis: The runtime rejected controller bindings for a profile it doesn't know (Meta's Touch Plus/Pro). Usually
|
||||
harmless (Meta's OVRPlugin suggests plain Touch too); a game that suggests only these gets them again as Touch
|
||||
(profile_remap, on by default; log "controller profile ... -> oculus/touch_controller").
|
||||
suggest: []
|
||||
- id: gl-shader-failed
|
||||
pattern: 'GLShim\s*: SHADER COMPILE FAILED|#extension directive is not allowed in the middle|could not implicitly convert operands'
|
||||
severity: error
|
||||
@@ -79,7 +120,8 @@ signatures:
|
||||
agent's controller_models command).
|
||||
suggest: []
|
||||
- id: scene-missing
|
||||
pattern: 'XR_FB_scene|XR_FB_spatial_entity.*(not supported|UNSUPPORTED)|xrQuerySpacesFB'
|
||||
# not OVRPlugin's routine "Unavailable OpenXR extension: XR_FB_scene" (printed by every OVRPlugin game)
|
||||
pattern: '(?<!Unavailable OpenXR extension: )XR_FB_scene|XR_FB_spatial_entity.*(not supported|UNSUPPORTED)|xrQuerySpacesFB'
|
||||
severity: warning
|
||||
diagnosis: The game uses the Meta scene (room) API; enable the adapter's guardian-based room emulation.
|
||||
suggest: [adapter.scene_emul]
|
||||
@@ -226,6 +268,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}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Meta XR Audio metadata lifetime
|
||||
|
||||
FrameBridge automatically handles metadata retirement in the verified AArch64
|
||||
Meta XR Audio Wwise build (`e1619e7fb839badf0ea5ecc22d9f028d0b17c34d`). It requires
|
||||
the build ID and exact function prologues; other builds and 32-bit adapters are
|
||||
left unchanged. No additional patch switch or recipe entry is required.
|
||||
|
||||
The SDK queues terminated metadata for deletion, then drains those queues before
|
||||
reading the current `AkAudioObjects` snapshot. In Batman: Arkham Shadow, that
|
||||
snapshot can still reference queued metadata during smoke-bomb playback. The
|
||||
audio thread subsequently clears its dirty flags at offset 8 through the stale
|
||||
pointer. A hardware watch captured this store in
|
||||
`OculusEndpointSink::ConsumeObjectExperimentalMetadata`, at library offset
|
||||
`0x2ced90`. Reallocated input tree nodes occupy the same 48-byte size class;
|
||||
the stale store corrupts their right pointer and the game crashes later.
|
||||
|
||||
`native/adapter/audio_metadata.h` wraps the audio consumption boundary to make
|
||||
the current snapshot available to metadata cleanup. `audio_metadata_queue.h`
|
||||
retains queued objects still referenced by that snapshot, then reclaims them
|
||||
normally when the references disappear. It preserves the SDK's queue mutex,
|
||||
virtual deleting destructor, audio parameters and processing. There is no timed
|
||||
quarantine, replacement allocator, audio suppression or diagnostic memory arena.
|
||||
|
||||
Synthetic regression tests exercise mixed referenced and unreferenced queue
|
||||
entries, both metadata types, subsequent retirement, and cleanup without a live
|
||||
snapshot. On-headset smoke-bomb tests first showed the observed overwrite stopped,
|
||||
then passed with ordinary allocations and all memory diagnostics removed.
|
||||
|
||||
The existing `frame.adapter` install step includes the repair in its packaged
|
||||
adapter and updates already wrapped APKs. Rebuild the adapters and checksums with
|
||||
`python native/build.py --only adapter`.
|
||||
@@ -1,6 +1,7 @@
|
||||
# Compatibility
|
||||
|
||||
The built-in catalog has tested settings for 39 games (27 work, 6 work with known issues, 6 can't run on the Frame).
|
||||
The built-in catalog has tested settings for games, each marked as working, working with known issues, or not
|
||||
running on the Frame: see the [list of tested games](GAMES.md) (recipes in [catalog/games](../catalog/games)).
|
||||
Other games get suggested patches from detection rules; each suggestion states its reason, and every patch can be
|
||||
switched on or off under **Customize**: described in plain words, with **Show technical details** for the exact
|
||||
effect of each patch.
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# FAQ
|
||||
|
||||
## How should I lay out a game that has OBB files (an APK plus a data folder)?
|
||||
|
||||
Give every game its own folder, put the APK in it, and put the game's data next to the APK in a folder named
|
||||
after the game's **package name** (the name the `.obb` files contain, e.g. `com.Armature.VR4`):
|
||||
|
||||
```
|
||||
Games/ ← scan this folder (Add games → Scan a folder)
|
||||
├── Resident Evil 4/ ← one folder per game (any name)
|
||||
│ ├── VR4.apk ← the APK (any file name)
|
||||
│ └── com.Armature.VR4/ ← the data folder: exactly the package name
|
||||
│ ├── main.203.com.Armature.VR4.obb
|
||||
│ └── patch.203.com.Armature.VR4.obb
|
||||
└── Beat Saber/
|
||||
└── com.beatgames.beatsaber.apk ← games without OBBs: just the APK
|
||||
```
|
||||
|
||||
- **Data folder name:** the package name (`com.Armature.VR4` above), or `obb`. FramePort uses the first of the two
|
||||
that exists and isn't empty.
|
||||
- **Everything in that folder is copied** to the game's `Android/obb/<package>/` on the Frame, subfolders included.
|
||||
So games that ship raw data files instead of `.obb` files work the same way.
|
||||
- **One game per folder.** Several APKs in one folder count as one game; FramePort uses the first and keeps the others
|
||||
as alternates.
|
||||
- **Scanning:** pick the folder that contains the game folders (`Games/` above) to add them all, or one game's folder
|
||||
to add just that game. FramePort looks up to 5 levels deep.
|
||||
- **A single game:** Add games → Add an APK file… works with a lone APK too. Its data is found when the data folder sits next
|
||||
to the APK, named as above.
|
||||
|
||||
Not sure of the package name? Look at the OBB file names: `main.<version>.<package name>.obb`. Or add the APK
|
||||
first: the game's page shows the package name under **Details**.
|
||||
@@ -106,6 +106,29 @@
|
||||
- SSH: `sshd` must be enabled (`sudo systemctl enable --now sshd`), which needs a user password (`passwd`).
|
||||
- mDNS: avahi-daemon runs by default; hostname `frame` → `frame.local`.
|
||||
|
||||
## Video of the headset view (surveyed 2026-10-05; used by the Live view tab)
|
||||
- `steamvr-v4l2cam.service` (user unit, part of gamescope-session.target, `Restart=always`) runs SteamVR's
|
||||
`/opt/steamvr/bin/linuxarm64/v4l2cam --output=99`: it reads the compositor's "Headset View" (IVRHeadsetView) and
|
||||
writes it to a v4l2loopback webcam named **"SteamVR"** (`/dev/video99`, 1920x1080 RGB24, advertised 30 fps, frames
|
||||
arrive at the display rate). Nothing on the Frame reads it by default; idle it costs nothing, read ~0.2 core.
|
||||
It shows what the wearer sees (SteamVR home, Steam's panels; a game's layers are expected but not yet seen in it).
|
||||
Black and ~1 fps (one frame per ~1.0 s) while the headset sleeps (standby): a 30 fps stream then repeats each
|
||||
frame in bursts, which looks like a stall in a player. Its size follows SteamVR's headset view (v4l2cam has no size
|
||||
option), so the live view only scales down (360p/480p/720p/1080p) or sends it as is ("full").
|
||||
- Sound: `pactl get-default-sink` (`alsa_loopback_device.stereo.alsa_output.platform-sound.HiFi__Speaker__sink`) and its
|
||||
`.monitor` source carry what the headset plays; the Frame's ffmpeg has the `pulse` input and `aac`. Timestamps: pulse
|
||||
uses the wall clock, v4l2 CLOCK_MONOTONIC → `-ts mono2abs` on the v4l2 input. Don't force
|
||||
`-use_wallclock_as_timestamps` on the pulse input: it stamped bursts of AAC packets with one time.
|
||||
- Steam's own game recording / Remote Play / broadcast capture the **gamescope** PipeWire node (`CDesktopCapturePipeWire:
|
||||
... node path: gamescope`): with gamescope's `--backend openvr` that's only the flat Steam UI, not VR. Steam's arm64
|
||||
`libvideo.so` encodes with x264 (vaapi/nvenc paths don't apply). No cast/spectator feature for the Frame's own VR view
|
||||
exists in Steam's UI; the SteamVR web server (27062) has no mirror route.
|
||||
- Encoding: the Qualcomm encoder (`/dev/video23` qcom-iris-encoder, V4L2 M2M) doesn't work with the stock tools (ffmpeg
|
||||
`h264_v4l2m2m` hangs, gst `v4l2h264enc` not-negotiated). ffmpeg + libx264 works: FramePort's live view
|
||||
(`install/livestream.py`: `fps=30` before the scale, ultrafast/zerolatency, 3 threads, nice 10, fragmented MP4 on
|
||||
stdout, + AAC 128k) measured 0.34 core at 720p / 0.56 at 1080p with a quiet picture (video only); expect ~1-1.4
|
||||
cores with a busy scene.
|
||||
|
||||
## Text input
|
||||
|
||||
- Lepton's Android has no on-screen keyboard (IME) and VR apps run headless, so no Android window has keyboard focus
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Tested games
|
||||
|
||||
Games tested on the Steam Frame with FramePort's recipes. Games not listed here may work too: FramePort suggests patches for them, and a working config can be shared from the app (**Share working config…**).
|
||||
Tested a game? [Share a working config](https://github.com/spoopyghosty0/frameport/issues/new?template=working-config.yml) or [report a problem](https://github.com/spoopyghosty0/frameport/issues/new?template=bug-report.yml) (in the app: the game's **…** menu does both and fills in the details).
|
||||
Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
|
||||
| Game | Platform | Status | Notes |
|
||||
|---|---|---|---|
|
||||
| 4XVR Video Player | Quest | ✅ Works | |
|
||||
| AllInOneSports | Quest | ✅ Works | |
|
||||
| Asgard's Wrath 2 | Quest | ✅ Works | |
|
||||
| BAM | Quest | ✅ Works | |
|
||||
| BARTENDER VR SIMULATOR | Quest | ✅ Works | |
|
||||
| Batman: Arkham Shadow | Quest | ✅ Works | |
|
||||
| BattleGlide | Quest | ✅ Works | |
|
||||
| Beat Saber | Quest | ✅ Works | |
|
||||
| Beat Saber (co-existence build) | Quest | ✅ Works | |
|
||||
| Blade & Sorcery: Nomad | Quest | ✅ Works | |
|
||||
| Carve Snowboarding | Quest | ✅ Works | |
|
||||
| Cook-Out | Quest | ✅ Works | |
|
||||
| Demeter | Quest | ✅ Works | |
|
||||
| Dinosaur Island | Quest | ✅ Works | |
|
||||
| Espire 2 | Quest | ✅ Works | |
|
||||
| Genotype | Quest | ✅ Works | |
|
||||
| H.U.N.T | Quest | ✅ Works | |
|
||||
| I Am Monkey | Quest | ✅ Works | |
|
||||
| In Death: Unchained | Quest | ✅ Works | |
|
||||
| Into The Radius 2 | Quest | ✅ Works | |
|
||||
| Job Simulator | Quest | ✅ Works | |
|
||||
| Keep Talking and Nobody Explodes | Quest | ✅ Works | |
|
||||
| LEGO® Bricktales | Quest | ✅ Works | |
|
||||
| Marvel's Deadpool VR | Quest | ✅ Works | |
|
||||
| Marvel's Iron Man VR | Quest | ✅ Works | |
|
||||
| Medieval Dynasty New Settlement | Quest | ✅ Works | |
|
||||
| Mobile Suit Gundam: Silver Phantom | Quest | ✅ Works | |
|
||||
| Nano | Quest | ✅ Works | |
|
||||
| NEX Player | Quest | ✅ Works | |
|
||||
| NOPE CHALLENGE | Quest | ✅ Works | |
|
||||
| palazzo_santacruz | Quest | ✅ Works | |
|
||||
| Path of the Warrior | Quest | ✅ Works | |
|
||||
| PowerWash Simulator VR | Quest | ✅ Works | |
|
||||
| QuestCraft | Quest | ✅ Works | |
|
||||
| Rick and Morty: Virtual Rick-ality | PC VR | ✅ Works | |
|
||||
| Riven | Quest | ✅ Works | |
|
||||
| Robo Recall | Quest | ✅ Works | |
|
||||
| Sniper Elite VR: Winter Warrior | Quest | ✅ Works | |
|
||||
| Space Pirate Trainer Quest | Quest | ✅ Works | |
|
||||
| Stremio | Quest | ✅ Works | |
|
||||
| SUPERHOT VR | PC VR | ✅ Works | |
|
||||
| SUPERHOT VR | Quest | ✅ Works | |
|
||||
| TetrisEffect | Quest | ✅ Works | |
|
||||
| The Climb 2 | Quest | ✅ Works | |
|
||||
| Toy Master | Quest | ✅ Works | |
|
||||
| Under Cover | Quest | ✅ Works | |
|
||||
| VR4 | Quest | ✅ Works | |
|
||||
| Wallace & Gromit in The Grand Getaway | Quest | ✅ Works | |
|
||||
| Waltz of the Wizard: Extended Edition | Quest | ✅ Works | |
|
||||
| Wander | Quest | ✅ Works | |
|
||||
| Accounting+ | Quest | ⚠️ Works with issues | Starts in VR, but doesn't get past its "press any button" screen. |
|
||||
| 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 | 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). |
|
||||
| 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. |
|
||||
| Journey of the Gods | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
|
||||
| Roblox | Quest | ❌ Doesn't run | Crashes on its first VR frame on the Frame. |
|
||||
| Shadow Point | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
|
||||
| Sniper Elite VR | Quest | ❌ Doesn't run | GPU hang (zink: DEVICE LOST) even with MSAA off. |
|
||||
| Sports Scramble (Santa Cruz) | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
|
||||
+61
-6
@@ -9,6 +9,7 @@ runtime, the OVRPort CLI and apksigner into its data folder (Settings → Tools
|
||||
| Windows 10/11 (x64) | `FramePort-windows-x64.zip` | `FramePort.exe` |
|
||||
| macOS (Apple Silicon) | `FramePort-macos-arm64.zip` | `FramePort.app` |
|
||||
| Linux (x64, GTK 3; Ubuntu 22.04 or newer) | `FramePort-linux-x64.tar.gz` | `FramePort/FramePort` |
|
||||
| Linux (ARM64, GTK 3; Ubuntu 22.04 or newer) | `FramePort-linux-arm64.tar.gz` | `FramePort/FramePort` |
|
||||
| Command line only (Python 3.11+) | `frameport-<version>-py3-none-any.whl` | `frameport --help` |
|
||||
|
||||
The command-line version installs from the wheel's release link with `uv tool install <link>` (or pipx / pip).
|
||||
@@ -22,7 +23,7 @@ start shows a warning:
|
||||
`FramePort-selfsigned.cer` (attached to each release) into *Trusted Root Certification Authorities* (Current User) to
|
||||
show FramePort as the publisher; the certificate can only sign code. Remove it with `certmgr.msc`.
|
||||
- **macOS:** right-click `FramePort.app` → **Open** → **Open** (once), or `xattr -dr com.apple.quarantine FramePort.app`.
|
||||
- **Linux:** `tar xzf FramePort-linux-x64.tar.gz && ./FramePort/FramePort`.
|
||||
- **Linux:** `tar xzf FramePort-linux-x64.tar.gz && ./FramePort/FramePort` (ARM64: `FramePort-linux-arm64.tar.gz`).
|
||||
|
||||
## Connecting the Steam Frame
|
||||
|
||||
@@ -30,12 +31,12 @@ The Frame and the computer must be on the same network.
|
||||
|
||||
1. In FramePort open **Steam Frame** and click **Show setup command**.
|
||||
2. First time only, on the Frame:
|
||||
1. Press the **Steam button → Power → Switch to Desktop**.
|
||||
2. Open the app menu (bottom-left corner), search for **Konsole** and open it.
|
||||
1. Open the **SteamVR dashboard → Launch a program → Desktop**: the Linux desktop opens on a virtual screen.
|
||||
2. Open the app menu (bottom-left corner of that desktop) → **System → Konsole** (or search for Konsole).
|
||||
3. Type the command FramePort shows exactly as shown (on-screen keyboard or any USB/Bluetooth keyboard) and press
|
||||
**Enter**. It looks like `curl -fsS 192.168.1.20:8765/1a2b3c4d | bash`: your computer's address, then a
|
||||
one-time code.
|
||||
4. After a few seconds the desktop closes by itself and the Frame returns to its normal view; that's expected. If
|
||||
4. After a few seconds the desktop closes by itself (Steam restarts once); that's expected. If
|
||||
Steam asks to install **Lepton** (Valve's Android runtime), confirm it.
|
||||
|
||||
FramePort connects by itself within a minute. No password is needed. The command lets FramePort in and turns on
|
||||
@@ -48,11 +49,33 @@ The Frame and the computer must be on the same network.
|
||||
and approve it on the Frame (Valve's own devkit pairing; it only sends this computer's key to the Frame). Install
|
||||
Lepton from the Steam Frame page afterwards if it's missing.
|
||||
|
||||
### With a USB cable
|
||||
|
||||
For networks that block the setup (guest Wi-Fi, firewalls, discovery not working), and for faster uploads:
|
||||
|
||||
1. On the Frame, turn on **Developer Mode** (Settings → System → Developer Mode). The Frame's USB network only exists
|
||||
in Developer Mode.
|
||||
2. Connect the Frame's USB-C port to the computer.
|
||||
3. In FramePort: **Steam Frame → Set up with a USB cable**. FramePort detects the cable and shows the setup command,
|
||||
which reaches the computer over the cable. Already set up? It connects over the cable right away.
|
||||
|
||||
The cable needs no driver on Windows 10/11, macOS or Linux, and the computer gets an address from the Frame
|
||||
automatically. Uploads use the cable whenever it's plugged in (about 37 MB/s, ~3× typical Wi-Fi), even when FramePort
|
||||
connected over Wi-Fi. Unplug it any time: FramePort finds the Frame on Wi-Fi again by itself.
|
||||
|
||||
### Firewalls
|
||||
|
||||
If the setup command only says "timed out", a firewall on your computer blocks the Frame; the setup page
|
||||
says which after about 45 seconds. Details per system: [FRAME_SETUP.md](FRAME_SETUP.md#network-and-firewalls).
|
||||
|
||||
## Running FramePort on the Frame (experimental)
|
||||
|
||||
FramePort can run on the Steam Frame itself, without a PC: in **Desktop Mode**, download
|
||||
`FramePort-linux-arm64.tar.gz`, unpack it (`tar xzf FramePort-linux-arm64.tar.gz`) and start `FramePort/FramePort`.
|
||||
Turn on **Developer Mode** first (Steam → Settings → System); FramePort then manages "This Frame" directly, with
|
||||
no pairing. Games are added to the Steam library when you go back to **Gaming Mode** (Steam has to restart for it,
|
||||
which would end Desktop Mode). This is new: please report anything odd with **Report a problem**.
|
||||
|
||||
## Installing games
|
||||
|
||||
- **Install on Frame** on a game's page (or select several in the Library and install them together). Installs run
|
||||
@@ -92,6 +115,12 @@ reality), showing only what matters for that game. Changes are kept with the gam
|
||||
|
||||
## Updating
|
||||
|
||||
**Game configs** (the tested recipes in the catalog) update by themselves: FramePort checks GitHub every 6 hours for
|
||||
newly confirmed or fixed configs and uses them without a FramePort update; a game whose recipe changed then shows
|
||||
**Update on Frame**. Configs that need a newer FramePort are skipped until you update. Settings → Data shows the last
|
||||
check (**Check now**) and turns this off.
|
||||
|
||||
|
||||
FramePort checks for a new release at start and every 6 hours (it only downloads the release information). When one
|
||||
exists, the Library shows **Update now**: FramePort downloads the new version, verifies it against the release's
|
||||
`SHA256SUMS.txt` (on Windows also the signature), restarts and opens as the new version. Games, settings, signing keys
|
||||
@@ -101,6 +130,10 @@ Settings → **Updates**: turn the check off, or turn on **Install updates autom
|
||||
installs at the next start). If FramePort's folder isn't writable, **Update now** opens the release page instead. The
|
||||
update log is `logs/update.log` in the data folder.
|
||||
|
||||
**Dev builds:** when you're asked to test a fix before it's released, use Settings → Updates → **Install the latest
|
||||
dev build…**. It shows what to test, then installs like an update (same checks). Dev builds are less tested; the next
|
||||
release is offered to you as a normal update.
|
||||
|
||||
Command line: `frameport update` (`--check` only checks, exit code 10 = update available; `--yes` doesn't ask).
|
||||
`FRAMEPORT_NO_UPDATE_CHECK=1` turns all checks off.
|
||||
|
||||
@@ -118,12 +151,33 @@ an installed Revive, or downloads a portable copy.
|
||||
on the game page.
|
||||
- Games that use the Oculus Platform SDK check the licence through the Oculus app, so they run on the PC only.
|
||||
|
||||
**Windows games without VR:** **Add games → Add one game folder…** with the game's folder (pick the program that
|
||||
starts it if asked). FramePort installs it on the Frame and Proton runs it as a window, like Steam's own Windows games;
|
||||
it shows up in the Frame's Steam library tagged "Windows game on Frame". Whether a game runs depends on Proton on ARM
|
||||
(x86 games run through emulation).
|
||||
|
||||
## Linux apps (arm64)
|
||||
|
||||
The Frame runs SteamOS on an arm64 CPU, so native Linux apps built for **aarch64/arm64** run on it directly (no
|
||||
Android container, no Proton). **Add games → Add a Linux app (arm64)…** takes an AppImage or a `.zip`/`.tar.gz`/
|
||||
`.tar.xz` archive; **Add a Linux app folder…** takes an unpacked app. FramePort finds the program that starts it (the
|
||||
game page's **Change…** picks another one) and whether it's a VR (OpenXR) app. **Install on Frame** uploads it
|
||||
unchanged and adds it to the Frame's Steam library, tagged "Linux app on Frame"; Play, launch tests and Uninstall
|
||||
work like for other games.
|
||||
|
||||
- x86_64 builds can't run on the Frame: FramePort says so when you add one. Look for an aarch64/arm64 download.
|
||||
- The app must bring the libraries SteamOS doesn't have. If some are missing, the install reports them and the game
|
||||
page lists them: look for a build that includes them.
|
||||
- From the command line: `frameport add-linux <AppImage, folder or archive> [--exe <program>]`.
|
||||
|
||||
## Files on the Frame (videos, documents, mods, saves)
|
||||
|
||||
The **Files** tab manages files on the Frame over the same connection as installs; no other transfer app is needed.
|
||||
Pick a location, browse folders, and use **Upload files** / **Upload folder**, **New folder**, or the download, rename
|
||||
and delete buttons on each entry. Tick several entries (or the box above the list for all) to download or delete them
|
||||
together. In the downloaded app you can also drag files and folders from Explorer / Finder / your file manager onto
|
||||
and delete buttons on each entry. Right-click an entry (or the empty space) for the same actions in a menu. Tick
|
||||
several entries (or the box above the list for all), or click and drag across them, to download or delete them
|
||||
together; a right-click on one of them then acts on all. The **Screenshots** tab and the **Library** work the same
|
||||
way: right-click for a menu, drag across cards to select several. In the downloaded app you can also drag files and folders from Explorer / Finder / your file manager onto
|
||||
the list to upload them into the open folder. Uploads and downloads run in the Activity panel, resume after an interruption and
|
||||
skip files that are already there.
|
||||
|
||||
@@ -153,6 +207,7 @@ and `frameport <command> --help` describe every option. The main ones:
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `scan <folder>` / `list` / `show <game>` | add games, list the library, show a game's analysis and patches |
|
||||
| `add-linux <path>` | add an arm64 Linux app (AppImage, folder or archive) |
|
||||
| `recipe <game> --enable/--disable <patch>` | change a game's patches (`patches` lists them all) |
|
||||
| `build <game>` / `install <game>` / `test <game>` | build, install on the Frame (`--to pc` for PC VR on this PC), launch test |
|
||||
| `frame discover` / `frame connect` / `frame info` | find, pair with and describe the Frame |
|
||||
|
||||
@@ -15,6 +15,11 @@ 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) |
|
||||
| Play gives Steam's "Game configuration unavailable"; Steam's console_log: `GameAction [AppID <id>] … RequestingLicense → UpdatingAppInfo → LaunchApp failed with AppError_9` | this Frame's Steam never loaded FramePort's shortcuts.vdf entry (it treats the id as a store app); cause unknown (GitHub #21/#30) | automatic since agent v43: Play registers the game through Steam's devkit interface ("Devkit Game: …", `devkit_register`) and starts that; uninstall removes it |
|
||||
| Steam's Exit game leaves the game running (container `lepton-steamlaunch-<appid>` still up) | Steam stopped only its `reaper`; launch.sh and Lepton (setsid) never got a signal (GitHub #36) | agent v44: launch.sh's 2 s loop ends the game when its parent is gone (`upgrade_launchers` adds it to existing launchers); by hand: `podman kill lepton-steamlaunch-<appid>` |
|
||||
| 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 +35,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`) |
|
||||
@@ -49,7 +55,17 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
| PC VR game judders/stutters although the GPU keeps up; vrcompositor.txt "Timed out. N total" high or frames dropped | the game misses the headset's refresh (e.g. 96 Hz = 10.4 ms; Stormland's slow frames take 10.7 ms) | `pcvr.steamvr_tuning` (default on): next Play sets SteamVR per-app `preferredRefreshRate` + `motionSmoothingOverride` via `fp_vrsettings.exe` |
|
||||
| Quest app keeps recentering / snapping the view when you turn your head; log shows session state 5→4→3→4→5 within a second | the Frame briefly takes focus; the app recenters on focus changes | unfixed: hiding the dips (debounce) made AC Nexus stay black, so it was removed |
|
||||
| Video player / app finds no local videos; MediaProvider "Requested path /home/steamos/... doesn't appear under ..." | Lepton's /sdcard is a symlink to a host path, so Android's media index rejects every file | upload in the Files tab (Videos = /sdcard/Movies) and browse folders in the app |
|
||||
| Batman: Arkham Shadow closes during smoke-bomb effects; later input-tree corruption | Meta XR Audio Wwise deletes queued metadata still referenced by the current audio frame, then writes through the stale pointer | FrameBridge automatically retires metadata after current-frame references disappear, for the verified AArch64 SDK build only; see [AUDIO_METADATA.md](AUDIO_METADATA.md) |
|
||||
| Game stays on a loading or "Waiting" box although it reached FOCUSED; log `FrameBridge: xrEndFrame failed -25` then no more `pacing:` lines (e.g. PowerWash Simulator on some Frames, GitHub #39) | The eye image rect ends a few pixels past its swapchain (Unity rounds the swapchain width, the runtime's recommended size differs per Frame); SteamVR rejects every frame with XR_ERROR_SWAPCHAIN_RECT_INVALID | FrameBridge clamps every projection/quad image rect to its swapchain (`rect_clamp`, default on since 0.10.1; log `rect_clamp: view N image rect clamped`): rebuild + reinstall the game |
|
||||
| Game (Unity, GLES) freezes, `zink: DEVICE LOST` | multisampled render-to-texture hangs the GPU | `frame.unity_no_msaa`; if it persists: unfixable → PC version |
|
||||
| Only the Android home screen shows; the log has Unity's VR device as `None` (e.g. Accounting+, Unity 2017) | Unity 2017–2018 built-in Oculus support starts VR only when `com.oculus.systemactivities` is installed; Lepton has no Meta system apps, so Unity falls back to non-VR | `frame.unity_oculus_check`: that package name in libunity.so → `android`, plus `native/ovrpshim` (libfp_ovrp.so): Unity 2017's legacy frame loop (`ovrp_Update2`/`ovrp_BeginFrame`) never calls `ovrp_WaitToBeginFrame`, so without the shim no `xrWaitFrame` happens, `CompositorOpenXR::Update … outside of frame bounds` floods the log and the dashboard freezes. With it: log `ovrp frame loop shim: waited for frame N`, ~71 fps. Accounting+ then stops at "press any button" although its OVRInput gets clean input (`INPUT_PROBE` in the patch logs connected controllers/buttons/input focus per call) — unresolved |
|
||||
| Own-engine game crashes in `libVkLayer_fossilize.so` (Fossilize's recording thread, e.g. Roblox) | same as Deadpool VR: uninitialised pointers in what Fossilize records | `frame.vk_sanitize` now also covers own-engine libraries that load `libvulkan.so` by name |
|
||||
| Crash right after the game gets focus, in `vrclient.so … UpdateActionStateInternal` / `sxr_xrSyncActions` (e.g. Myst) | a race in the Frame runtime's input code on the first sync after focus (not every launch) | adapter `sync_guard` (input syncs one at a time with event polling, paused 250 ms after FOCUSED) |
|
||||
| View jumps sideways / game pauses or freezes for a moment every few seconds (e.g. Blade & Sorcery, BattleGlide) | the Frame drops focus for ~0.5 s (FOCUSED→VISIBLE→SYNCHRONIZED); games pause or re-align the player (`OnVRPresence … Teleport`) | adapter `focus_hold` |
|
||||
| SDL / LÖVE app crashes at start: `NullPointerException … ClipboardManager.addPrimaryClipChangedListener` in `SDLClipboardHandler.<init>` (e.g. Dramatic Shape) | Lepton's Android has no clipboard service (`service check clipboard`: not found) | `frame.sdl_clipboard` (that call → nops in classes.dex, in place, `apk/dex.py`); reproduced and verified with LÖVE for Android 11.5 |
|
||||
| Controllers do nothing (e.g. stuck on a setup screen); log: `xrSuggestInteractionProfileBindings … XR_ERROR_PATH_UNSUPPORTED` | the game only suggests bindings for Meta's newer profiles (Touch Plus / Touch Pro); the Frame's Android runtime knows `oculus/touch_controller`, not those | adapter `profile_remap` (default on): the bindings are suggested again for Touch (log: `controller profile … -> oculus/touch_controller`) |
|
||||
| Unity game hangs or the whole Frame restarts (e.g. in a menu); log: `The current MSAA level is 0, but the recommended MSAA level is 4. Switching to the recommended level.` (e.g. Lucky's Tale) | Meta's OVRManager (`useRecommendedMSAALevel`) turns 4x MSAA on at runtime, past QualitySettings; multisampled render-to-texture on GLES/Zink hangs the GPU | `frame.unity_runtime_msaa_off` (Cpp2IL: `OVRDisplay.get_recommendedMSAALevel` → 0) |
|
||||
| Unity game: one eye shows only effects or grey, the other is fine (e.g. I Am Cat, Oculus XR Plugin on GLES) | the game's single-pass multiview rendering goes wrong for array slice 1 (the adapter submits both slices correctly) | `frame.unity_multipass` (Cpp2IL: `OculusSettings.GetStereoRenderingMode` → MultiPass); `swap_eyes=1` tells whether the game or the adapter is at fault |
|
||||
| Setup/intro loops every launch (Espire 2) | save folders created without write permission | launcher repairs permissions every 2 s (built in) |
|
||||
| VrApi bridge: never enters VR | Frame reaches FOCUSED later than Quest; tracking only when worn | bridge waits 30 s; test in the headset |
|
||||
|
||||
@@ -69,6 +85,12 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
| MR game stuck waiting for room data (Demeter) | no Meta scene API | adapter `scene_emul=1` (+ `frame.meta_permissions`) |
|
||||
| Hand-tracking game janky (Silhouette) | Frame synthesizes hands from controllers | `controller_fix=0` passes hands through; not really fixable |
|
||||
| Eye distortion while moving (Arcsmith, Time Stall) | unknown (not eye swap, tracking, Valve layers, depth or pacing) | unresolved |
|
||||
| One eye grey / only effects (I Am Cat, Unity Oculus XR Plugin on GLES) | the game's multiview pass draws array slice 1 wrong on Zink | `frame.unity_multipass` (also rewrites the getter's inlined read in `OculusLoader.Initialize`; check for two `array=1` eye swapchains) |
|
||||
| View vibrates even when holding still after `frame.unity_multipass` (I Am Cat) | poses/times are consistent, but two passes on Zink make every frame one period late, and the game clamps its physics step to 10 ms | not fixed (scale 0.8 didn't help); next ideas: fix multiview instead, or the game's fixed timestep |
|
||||
| Game freezes / pauses for 1-2 s now and then, no flicker; only some games (Blade & Sorcery) | the headset's wear sensor flickers off while worn (SteamVR vrserver.txt `HMD off, stopping eye tracking` … `HMD on`), the Frame turns it into a focus loss and Quest games that pause on focus loss pause | adapter `focus_hold=1` + `focus_hold_ms=2500` per game; native games don't react, so it's per game |
|
||||
| Minor glitches on some objects (Myst, Unreal Vulkan) | unknown; not application space warp (turning it off changed nothing and ran worse) | unresolved |
|
||||
| Graphics crash in vkCreateInstance with pc == fault address, from the game's own Vulkan hooks (BONELAB `libSLZQuestNative`) | a pointer into memory freed with OVRPlugin's pre-init OpenXR instance; not the runtime (vrclient.so) or Fossilize being unloaded (keeping both loaded with RTLD_NODELETE didn't help) | unresolved |
|
||||
| Own-engine game crashes in `je_free` from its own library on the first frames (Roblox) | the game frees memory it doesn't own; not the Vulkan shim or the format fallback | unsupported |
|
||||
|
||||
## Debugging techniques that worked
|
||||
- A user's problem report: `frameport diag inspect <FramePort-diag-*.zip>` re-triages its launch log with the current
|
||||
@@ -78,6 +100,31 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
- For GLES/GLAD engines, wrap `eglGetProcAddress` to see shader compile errors (build the shim with `-DGLSHIM_TRACE`
|
||||
for per-FBO draw counts and draw-call errors; the bridge has `-DOVP_GL_DIAG` for eye-image readback).
|
||||
- Anything visual needs one headset session per iteration — batch hypotheses into each build.
|
||||
- Headless launch tests never get focus: they prove startup, not play. Crashes right after FOCUSED (Myst), focus
|
||||
dips and judder only show up in a headset session: ask for one, then `frameport diag collect <pkg>` (it contains
|
||||
the headset sessions too, plus this boot's kernel log).
|
||||
- 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:`
|
||||
lines); the cause is on the host: `~/.local/share/Steam/logs/vrserver.txt` (`HMD off/on`, `entering standby`,
|
||||
`SystemButtonDown` in vrclient_vrcompositor.txt) and XRService (`[UserPresence]`, `IMUFallback`). Compare the times
|
||||
(Lepton logs UTC, host logs local time).
|
||||
- A Unity getter patch that changes nothing: the compiler may have inlined it (no `BL` to its address in
|
||||
libil2cpp.so) — patch the field read in the caller (`Il2cppReturnPatch.field_loads`).
|
||||
- Fixes found by users count: a reporter's shader capture (VR4) became the `vk_shader_fix` recipe data (match by size
|
||||
+ SHA-256, insert words); verify on the device that the log shows the module being fixed.
|
||||
- Don't install or test on the Frame while the owner is playing: adding a library entry restarts Steam (FramePort
|
||||
now skips the restart when the shortcut is unchanged and waits while a game runs), and a launch test starts a game.
|
||||
- Catalog YAML: a `: ` inside an unquoted value breaks the file and the loader skipped it silently (the game vanished
|
||||
from the list); `tests/test_catalog_files.py` now catches it.
|
||||
- Keep the known-good APK and roll back if a change regresses (`PATCHED/_known-good-*`).
|
||||
|
||||
## When it can't run on the Frame
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 916 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 643 KiB |
@@ -1,5 +1,9 @@
|
||||
# Native components
|
||||
|
||||
FrameBridge includes automatic metadata retirement for the verified Meta XR Audio
|
||||
Wwise build; see [AUDIO_METADATA.md](../docs/AUDIO_METADATA.md) for its lifetime
|
||||
invariant and regression coverage. It uses the existing adapter installation.
|
||||
|
||||
Sources of the prebuilt binaries in `../artifacts/` (committed, with `SHA256SUMS`). End users never compile anything;
|
||||
developers rebuild with `python native/build.py` (downloads NDK r27c, OpenXR headers at pinned commits, d8 into
|
||||
`native/.cache/`, git-ignored). The adapter, GL shim and platform compat rebuild byte-identically; the VrApi bridge
|
||||
@@ -10,6 +14,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). |
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Meta XR Audio Wwise metadata retirement. Enabled automatically for the
|
||||
// exact verified AArch64 SDK build; unrelated libraries remain untouched.
|
||||
#pragma once
|
||||
#if defined(__aarch64__)
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
#include <time.h>
|
||||
#include <link.h>
|
||||
#include <string.h>
|
||||
static size_t mx_audio_page;
|
||||
static void *mx_audio_detour(unsigned char *address,void *replacement,const uint32_t expected[4]) {
|
||||
if(memcmp(address,expected,16)) return NULL;
|
||||
unsigned char *trampoline=mmap(NULL,mx_audio_page,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0);
|
||||
if(trampoline==MAP_FAILED) return NULL;
|
||||
uint32_t branch[2]={0x58000050u,0xd61f0200u}; // ldr x16, +8; br x16
|
||||
memcpy(trampoline,address,16);
|
||||
memcpy(trampoline+16,branch,8);
|
||||
uintptr_t continuation=(uintptr_t)address+16;
|
||||
memcpy(trampoline+24,&continuation,8);
|
||||
__builtin___clear_cache((char*)trampoline,(char*)trampoline+32);
|
||||
if(mprotect(trampoline,mx_audio_page,PROT_READ|PROT_EXEC)) return NULL;
|
||||
unsigned char *page=(unsigned char*)((uintptr_t)address&~(mx_audio_page-1));
|
||||
if(mprotect(page,mx_audio_page,PROT_READ|PROT_WRITE|PROT_EXEC)) return NULL;
|
||||
memcpy(address,branch,8);
|
||||
memcpy(address+8,&replacement,8);
|
||||
__builtin___clear_cache((char*)address,(char*)address+16);
|
||||
mprotect(page,mx_audio_page,PROT_READ|PROT_EXEC);
|
||||
return trampoline;
|
||||
}
|
||||
#include "audio_metadata_queue.h"
|
||||
typedef struct {float previous,current;} MxAudioRamp;
|
||||
static uintptr_t mx_audio_base;
|
||||
// set once the library was found but isn't the verified build: stop looking (xrPollEvent runs several times a frame)
|
||||
static int mx_audio_checked;
|
||||
static uint64_t (*mx_audio_consume_original)(void*,void*,void*,const void*,MxAudioRamp);
|
||||
static void mx_audio_kill(unsigned experimental) {
|
||||
void *mutex=(void*)(mx_audio_base+(experimental?0x5fe2e0:0x5fe380));
|
||||
int (*trylock)(void*)=(void*)(mx_audio_base+0x5b369c);
|
||||
void (*unlock)(void*)=(void*)(mx_audio_base+0x5b36bc);
|
||||
if(!trylock(mutex))return;
|
||||
mx_audio_drain((void**)(mx_audio_base+(experimental?0x5fe2d8:0x5fe378)),experimental?40:24);
|
||||
unlock(mutex);
|
||||
}
|
||||
static void mx_audio_kill_experimental(void) {mx_audio_kill(1);}
|
||||
static void mx_audio_kill_regular(void) {mx_audio_kill(0);}
|
||||
static uint64_t mx_audio_consume(void *sink,void *main_mix,void *passthrough,const void *objects,MxAudioRamp ramp) {
|
||||
const unsigned char *previous=mx_audio_objects;mx_audio_objects=objects;
|
||||
// An audio thread can enter just after its prologue was patched, before
|
||||
// the installing thread publishes the completed trampoline.
|
||||
uint64_t (*original)(void*,void*,void*,const void*,MxAudioRamp);
|
||||
while(!(original=__atomic_load_n(&mx_audio_consume_original,__ATOMIC_ACQUIRE)))sched_yield();
|
||||
uint64_t result=original(sink,main_mix,passthrough,objects,ramp);
|
||||
mx_audio_objects=previous;return result;
|
||||
}
|
||||
static int mx_audio_find(struct dl_phdr_info *info,size_t size,void *unused) {
|
||||
(void)size;(void)unused;
|
||||
if(!strstr(info->dlpi_name,"/libMetaXRAudioWwise.so"))return 0;
|
||||
if(mx_audio_base)return 1;
|
||||
const unsigned char id[20]={0xe1,0x61,0x9e,0x7f,0xb8,0x39,0xba,0xdf,0x0e,0xa5,0xec,0xc2,0x2d,0x9f,0x02,0x8d,0x0b,0x17,0xc3,0x4d};
|
||||
int match=0;
|
||||
for(unsigned i=0;i<info->dlpi_phnum;i++)if(info->dlpi_phdr[i].p_type==PT_NOTE) {
|
||||
const unsigned char *p=(void*)(info->dlpi_addr+info->dlpi_phdr[i].p_vaddr);
|
||||
const unsigned char *end=p+info->dlpi_phdr[i].p_memsz;
|
||||
while(p+sizeof(Elf64_Nhdr)<=end) {
|
||||
const Elf64_Nhdr *note=(void*)p;
|
||||
const unsigned char *name=p+sizeof(*note),*desc=name+((note->n_namesz+3)&~3u);
|
||||
const unsigned char *next=desc+((note->n_descsz+3)&~3u);
|
||||
if(next>end || next<=p)break;
|
||||
if(note->n_type==NT_GNU_BUILD_ID && note->n_namesz==4 && !memcmp(name,"GNU",4) && note->n_descsz==20 && !memcmp(desc,id,20))match=1;
|
||||
p=next;
|
||||
}
|
||||
}
|
||||
if(!match){__atomic_store_n(&mx_audio_checked,1,__ATOMIC_RELEASE);return 1;}
|
||||
const uint32_t consume[4]={0xd10743ff,0x6d1623e9,0xa9177bfd,0xa9186ffc};
|
||||
const uint32_t kill[4]={0xa9bd7bfd,0xf9000bf5,0xa9024ff4,0x910003fd};
|
||||
unsigned char *base=(void*)info->dlpi_addr;
|
||||
if(memcmp(base+0x2c8fac,consume,16) || memcmp(base+0x2be2c0,kill,16) || memcmp(base+0x2be7b0,kill,16)) {
|
||||
__atomic_store_n(&mx_audio_checked,1,__ATOMIC_RELEASE);return 1;
|
||||
}
|
||||
__atomic_store_n(&mx_audio_base,info->dlpi_addr,__ATOMIC_RELEASE);
|
||||
void *original=mx_audio_detour(base+0x2c8fac,(void*)mx_audio_consume,consume);
|
||||
__atomic_store_n(&mx_audio_consume_original,original,__ATOMIC_RELEASE);
|
||||
if(!__atomic_load_n(&mx_audio_consume_original,__ATOMIC_ACQUIRE)) {
|
||||
__atomic_store_n(&mx_audio_base,0,__ATOMIC_RELEASE);return 1;
|
||||
}
|
||||
if(!mx_audio_detour(base+0x2be2c0,(void*)mx_audio_kill_experimental,kill) || !mx_audio_detour(base+0x2be7b0,(void*)mx_audio_kill_regular,kill)) {
|
||||
LOG("FrameBridge audio metadata: incomplete installation");return 1;
|
||||
}
|
||||
LOG("FrameBridge audio metadata: metadata reclamation follows current audio-frame references; Meta audio base=%p",base);
|
||||
return 1;
|
||||
}
|
||||
static pthread_mutex_t mx_audio_install_mutex=PTHREAD_MUTEX_INITIALIZER;
|
||||
static void mx_audio_initialize(void) {
|
||||
if(__atomic_load_n(&mx_audio_base,__ATOMIC_ACQUIRE) || __atomic_load_n(&mx_audio_checked,__ATOMIC_ACQUIRE))return;
|
||||
// until the game loads the library: look at most once a second (dl_iterate_phdr takes the linker's lock)
|
||||
static _Atomic long mx_audio_last_scan;
|
||||
struct timespec now;clock_gettime(CLOCK_MONOTONIC,&now);
|
||||
if(now.tv_sec==mx_audio_last_scan)return;
|
||||
mx_audio_last_scan=now.tv_sec;
|
||||
if(pthread_mutex_trylock(&mx_audio_install_mutex))return;
|
||||
if(!mx_audio_page)mx_audio_page=(size_t)sysconf(_SC_PAGESIZE);
|
||||
if(!mx_audio_base)dl_iterate_phdr(mx_audio_find,NULL);
|
||||
pthread_mutex_unlock(&mx_audio_install_mutex);
|
||||
}
|
||||
#else
|
||||
static void mx_audio_initialize(void) {}
|
||||
#endif
|
||||
@@ -0,0 +1,47 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
// Experimental lifetime repair for the pinned Meta XR Audio Wwise build.
|
||||
// A queued metadata object must not be reclaimed while the current immutable
|
||||
// AkAudioObjects snapshot still references it. Preserve the SDK's queue mutex,
|
||||
// virtual destructor, list linkage, audio processing, and dirty-flag writes.
|
||||
static _Thread_local const unsigned char *mx_audio_objects;
|
||||
static unsigned mx_audio_held,mx_audio_reclaimed;
|
||||
static int mx_audio_referenced(const void *pointer) {
|
||||
if(!mx_audio_objects)return 0;
|
||||
uint32_t count;memcpy(&count,mx_audio_objects,4);
|
||||
const unsigned char *const *objects;memcpy(&objects,mx_audio_objects+16,8);
|
||||
// Refuse to reclaim on an unrecognised snapshot rather than dereferencing
|
||||
// unbounded arrays. These bounds exceed the game's ordinary voice counts.
|
||||
if(count>4096 || (count && !objects))return 1;
|
||||
for(unsigned i=0;i<count;i++) {
|
||||
const unsigned char *object=objects[i];if(!object)continue;
|
||||
uint32_t metadata_count;const unsigned char *metadata;
|
||||
memcpy(&metadata,object+104,8);memcpy(&metadata_count,object+112,4);
|
||||
if(metadata_count>4096 || (metadata_count && !metadata))return 1;
|
||||
for(unsigned j=0;j<metadata_count;j++) {
|
||||
const void *parameter;memcpy(¶meter,metadata+(size_t)j*24+8,8);
|
||||
if(parameter==pointer)return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// Caller holds the original queue's mutex, just as ExecuteKillList did.
|
||||
static void mx_audio_drain(void **head,size_t next_offset) {
|
||||
void **link=head;
|
||||
while(*link) {
|
||||
void *pointer=*link;void **next=(void**)((unsigned char*)pointer+next_offset);
|
||||
if(mx_audio_referenced(pointer)) {
|
||||
link=next;
|
||||
unsigned held=__atomic_fetch_add(&mx_audio_held,1,__ATOMIC_RELAXED);
|
||||
if(held<8)LOG("FrameBridge audio metadata: queued metadata=%p still referenced by audio frame; retained",pointer);
|
||||
} else {
|
||||
*link=*next;
|
||||
void (**table)(void*)=*(void (***)(void*))pointer;
|
||||
table[1](pointer);
|
||||
__atomic_fetch_add(&mx_audio_reclaimed,1,__ATOMIC_RELAXED);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -45,17 +45,50 @@
|
||||
#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__)
|
||||
#include "audio_metadata.h"
|
||||
|
||||
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;
|
||||
// hide XR_FB_space_warp: games then render every frame themselves (UE5 Application SpaceWarp flickered on the Frame,
|
||||
// e.g. Into The Radius 2; OVRPort's patch_disable_space_warp doesn't reach UE5's OpenXR plugin)
|
||||
static int hide_space_warp = 0;
|
||||
static int controller_fix = 1;
|
||||
static int swapchain_fix = 1;
|
||||
static int rect_clamp = 1; // clamp submitted image rects to their swapchain (SteamVR rejects a 1 px overrun)
|
||||
static int layer_fix = 1;
|
||||
static int mutable_fix = 0;
|
||||
static int swap_eyes = 0;
|
||||
@@ -76,9 +109,12 @@ static int no_equirect, no_equirect2, no_cylinder, no_cube;
|
||||
static int runtime_has_fb_passthrough, emulate_passthrough, alpha_blend_failed;
|
||||
static int controller_models; // serve Frame controller models via XR_FB_render_model (render_model.c)
|
||||
// Per-game settings, all off by default (session_fixes.c, layer_emul_gl.c).
|
||||
static int sync_guard; // xrSyncActions one at a time with xrPollEvent, paused briefly after focus returns
|
||||
static int profile_remap = 1; // Meta's newer controller profiles (rejected by the Frame) -> oculus/touch_controller
|
||||
static int layer_debug; // diagnostics: layers, swapchains, session states, spaces, aim/grip, refresh rates
|
||||
static int stable_local; // keep every LOCAL space the app creates on the session-start origin
|
||||
static int focus_hold; // hide brief focus dips once the session has been focused for a while
|
||||
static float focus_hold_ms = 1000; // longest focus dip focus_hold hides
|
||||
static float aim_pitch, aim_yaw, aim_forward; // aim pose correction (degrees, degrees, metres)
|
||||
static float refresh_rate; // requested display refresh rate (Hz), 0 = the app's choice
|
||||
static int equirect_emul; // show 360 layers as cube faces (GLES)
|
||||
@@ -98,8 +134,10 @@ static void read_settings(const char *path) {
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
if (sscanf(line, "scale=%f", &value) == 1 && value >= 0.5f && value <= 2.0f) scale = value;
|
||||
if (sscanf(line, "foveation_fix=%f", &value) == 1) foveation_fix = value != 0;
|
||||
if (sscanf(line, "hide_space_warp=%f", &value) == 1) hide_space_warp = value != 0;
|
||||
if (sscanf(line, "controller_fix=%f", &value) == 1) controller_fix = value != 0;
|
||||
if (sscanf(line, "swapchain_fix=%f", &value) == 1) swapchain_fix = value != 0;
|
||||
if (sscanf(line, "rect_clamp=%f", &value) == 1) rect_clamp = value != 0;
|
||||
if (sscanf(line, "layer_fix=%f", &value) == 1) layer_fix = value != 0;
|
||||
if (sscanf(line, "mutable_fix=%f", &value) == 1) mutable_fix = value != 0;
|
||||
if (sscanf(line, "swap_eyes=%f", &value) == 1) swap_eyes = value != 0;
|
||||
@@ -115,8 +153,14 @@ 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;
|
||||
if (sscanf(line, "focus_hold=%f", &value) == 1) focus_hold = value != 0;
|
||||
if (sscanf(line, "focus_hold_ms=%f", &value) == 1 && value >= 100 && value <= 5000) focus_hold_ms = value;
|
||||
if (sscanf(line, "aim_pitch=%f", &value) == 1 && fabsf(value) <= 90) aim_pitch = value;
|
||||
if (sscanf(line, "aim_yaw=%f", &value) == 1 && fabsf(value) <= 90) aim_yaw = value;
|
||||
if (sscanf(line, "aim_forward=%f", &value) == 1 && fabsf(value) <= 0.5f) aim_forward = value;
|
||||
@@ -163,6 +207,13 @@ 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 (hide_space_warp) LOG("per-game: hide_space_warp=1 (XR_FB_space_warp hidden, space warp info removed)");
|
||||
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",
|
||||
@@ -193,7 +244,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;
|
||||
|
||||
@@ -223,6 +277,10 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info
|
||||
int supported = !available; // if we could not enumerate, pass everything through
|
||||
for (uint32_t j = 0; available && j < available_count && !supported; ++j)
|
||||
supported = !strcmp(available[j].extensionName, ext);
|
||||
if (hide_space_warp && !strcmp(ext, "XR_FB_space_warp")) {
|
||||
LOG("hide_space_warp: XR_FB_space_warp not enabled");
|
||||
continue;
|
||||
}
|
||||
if (supported) names[kept++] = ext;
|
||||
else if (scene_emul && is_scene_extension(ext)) {
|
||||
if (!emulate_scene) LOG("emulating Meta scene/spatial-entity extensions from the guardian bounds");
|
||||
@@ -259,10 +317,11 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info
|
||||
}
|
||||
no_equirect = !has_equirect; no_equirect2 = !has_equirect2; no_cylinder = !has_cylinder; no_cube = !has_cube;
|
||||
free(available);
|
||||
mx_audio_initialize();
|
||||
XrResult result = fn(&fixed, instance);
|
||||
free(names);
|
||||
LOG("xrCreateInstance result=%d", result);
|
||||
if (XR_SUCCEEDED(result)) active_instance = *instance;
|
||||
if (XR_SUCCEEDED(result)) { active_instance = *instance; mx_audio_initialize(); }
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -333,6 +392,45 @@ static void remember_swapchain(XrSwapchain handle) {
|
||||
pthread_mutex_unlock(&swapchains_lock);
|
||||
}
|
||||
|
||||
// Swapchain sizes, to keep submitted image rects inside them (rect_clamp).
|
||||
#define MAX_SIZES 256
|
||||
static struct { XrSwapchain handle; uint32_t w, h; } sizes[MAX_SIZES];
|
||||
static pthread_mutex_t sizes_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static void note_swapchain_size(XrSwapchain handle, uint32_t w, uint32_t h) {
|
||||
pthread_mutex_lock(&sizes_lock);
|
||||
int slot = -1;
|
||||
for (int i = 0; i < MAX_SIZES; ++i) {
|
||||
if (sizes[i].handle == handle) { slot = i; break; }
|
||||
if (slot < 0 && sizes[i].handle == XR_NULL_HANDLE) slot = i;
|
||||
}
|
||||
if (slot >= 0) { sizes[slot].handle = handle; sizes[slot].w = w; sizes[slot].h = h; }
|
||||
pthread_mutex_unlock(&sizes_lock);
|
||||
}
|
||||
|
||||
static int swapchain_size(XrSwapchain handle, uint32_t *w, uint32_t *h) {
|
||||
int found = 0;
|
||||
pthread_mutex_lock(&sizes_lock);
|
||||
for (int i = 0; i < MAX_SIZES && !found; ++i)
|
||||
if (sizes[i].handle == handle && handle != XR_NULL_HANDLE) { *w = sizes[i].w; *h = sizes[i].h; found = 1; }
|
||||
pthread_mutex_unlock(&sizes_lock);
|
||||
return found;
|
||||
}
|
||||
|
||||
// Clamp `r` to a w x h image; returns whether it changed.
|
||||
static int clamp_rect(XrRect2Di *r, uint32_t w, uint32_t h) {
|
||||
XrRect2Di c = *r;
|
||||
if (c.offset.x < 0) { c.extent.width += c.offset.x; c.offset.x = 0; }
|
||||
if (c.offset.y < 0) { c.extent.height += c.offset.y; c.offset.y = 0; }
|
||||
if ((uint32_t)c.offset.x >= w || (uint32_t)c.offset.y >= h) return 0; // nothing sensible to keep: leave it
|
||||
if ((int64_t)c.offset.x + c.extent.width > (int64_t)w) c.extent.width = (int32_t)(w - (uint32_t)c.offset.x);
|
||||
if ((int64_t)c.offset.y + c.extent.height > (int64_t)h) c.extent.height = (int32_t)(h - (uint32_t)c.offset.y);
|
||||
if (c.extent.width <= 0 || c.extent.height <= 0) return 0;
|
||||
int changed = memcmp(&c, r, sizeof c) != 0;
|
||||
*r = c;
|
||||
return changed;
|
||||
}
|
||||
|
||||
static void forget_swapchain(XrSwapchain handle) {
|
||||
pthread_mutex_lock(&swapchains_lock);
|
||||
for (size_t i = 0; i < swapchain_count; ++i)
|
||||
@@ -382,6 +480,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchain(XrSession session, const XrSwap
|
||||
(unsigned long long)fixed.usageFlags, (unsigned long long)fixed.createFlags, result);
|
||||
if (XR_SUCCEEDED(result)) {
|
||||
remember_swapchain(*swapchain);
|
||||
note_swapchain_size(*swapchain, fixed.width, fixed.height);
|
||||
flip_on_create_swapchain(*swapchain, &fixed);
|
||||
emul_on_create_swapchain(*swapchain, &fixed);
|
||||
return result;
|
||||
@@ -404,6 +503,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchain(XrSession session, const XrSwap
|
||||
}
|
||||
if (XR_SUCCEEDED(result)) {
|
||||
remember_swapchain(*swapchain);
|
||||
note_swapchain_size(*swapchain, fixed.width, fixed.height);
|
||||
flip_on_create_swapchain(*swapchain, &fixed);
|
||||
emul_on_create_swapchain(*swapchain, &fixed);
|
||||
}
|
||||
@@ -414,6 +514,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; }
|
||||
@@ -667,6 +768,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");
|
||||
@@ -720,6 +823,7 @@ static XrSession focused_session = XR_NULL_HANDLE;
|
||||
static int kicks_pending = -1; // -1: not yet armed
|
||||
|
||||
XRAPI_ATTR XrResult XRAPI_CALL xrPollEvent(XrInstance instance, XrEventDataBuffer *event) {
|
||||
mx_audio_initialize();
|
||||
PFN_xrPollEvent fn = (PFN_xrPollEvent)lookup(instance, "xrPollEvent");
|
||||
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
|
||||
if (emulate_scene && event) {
|
||||
@@ -728,7 +832,13 @@ XRAPI_ATTR XrResult XRAPI_CALL xrPollEvent(XrInstance instance, XrEventDataBuffe
|
||||
pthread_mutex_unlock(&scene_lock);
|
||||
if (got) return XR_SUCCESS;
|
||||
}
|
||||
if (sync_guard) pthread_mutex_lock(&sync_lock);
|
||||
XrResult result = focus_hold && event ? focus_hold_poll(fn, instance, event) : fn(instance, event);
|
||||
if (sync_guard) {
|
||||
if (result == XR_SUCCESS && event && session_state_of(event) == XR_SESSION_STATE_FOCUSED)
|
||||
sync_resume_at = monotonic_ns() + SYNC_GUARD_PAUSE_NS;
|
||||
pthread_mutex_unlock(&sync_lock);
|
||||
}
|
||||
if (result == XR_SUCCESS && event && (layer_debug || stable_local)) {
|
||||
if (event->type == XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED && layer_debug)
|
||||
LOG("layer_debug: session state %d at %.3f", ((const XrEventDataSessionStateChanged *)event)->state,
|
||||
@@ -852,6 +962,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;
|
||||
@@ -867,6 +978,12 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
|
||||
if (elapsed >= 5.0) {
|
||||
LOG("pacing: %.1f fps, displayTime vs predicted: avg %.2f ms, max %.2f ms", frames / elapsed,
|
||||
drift_sum / (double)frames / 1e6, drift_max / 1e6);
|
||||
if (layer_debug)
|
||||
LOG("layer_debug: input: %d xrSyncActions (%d ok, last %d), %d bool reads, %d pressed",
|
||||
__atomic_exchange_n(&input_syncs, 0, __ATOMIC_RELAXED),
|
||||
__atomic_exchange_n(&input_sync_ok, 0, __ATOMIC_RELAXED), input_last_sync_result,
|
||||
__atomic_exchange_n(&input_bool_reads, 0, __ATOMIC_RELAXED),
|
||||
__atomic_exchange_n(&input_bool_true, 0, __ATOMIC_RELAXED));
|
||||
frames = 0; drift_sum = drift_max = 0;
|
||||
}
|
||||
}
|
||||
@@ -951,6 +1068,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]);
|
||||
@@ -987,6 +1111,31 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
|
||||
if (!logged++) LOG("strip_depth: removed depth info from projection layer");
|
||||
++swapped;
|
||||
}
|
||||
if (hide_space_warp && layer->type == XR_TYPE_COMPOSITION_LAYER_PROJECTION &&
|
||||
((const XrCompositionLayerProjection *)layer)->viewCount == 2) {
|
||||
// The game may still attach XrCompositionLayerSpaceWarpInfoFB (1000171000) to its views: OVRPort's
|
||||
// dispatcher offers XR_FB_space_warp itself even when hidden here. Unlink it (keeping what follows when
|
||||
// it heads the chain, else the whole chain) so the runtime never uses the motion vectors.
|
||||
const XrCompositionLayerProjection *src = (const XrCompositionLayerProjection *)layer;
|
||||
int found = 0;
|
||||
for (uint32_t v = 0; v < 2; ++v)
|
||||
for (const XrBaseInStructure *n = (const XrBaseInStructure *)src->views[v].next; n; n = n->next)
|
||||
found |= n->type == 1000171000;
|
||||
if (found) {
|
||||
if (layer != (const XrCompositionLayerBaseHeader *)&projections[count]) projections[count] = *src;
|
||||
for (uint32_t v = 0; v < 2; ++v) {
|
||||
views[count][v] = src->views[v];
|
||||
const XrBaseInStructure *head = (const XrBaseInStructure *)src->views[v].next;
|
||||
if (head && head->type == 1000171000) views[count][v].next = head->next;
|
||||
else if (head) views[count][v].next = NULL;
|
||||
}
|
||||
projections[count].views = views[count];
|
||||
layer = (const XrCompositionLayerBaseHeader *)&projections[count];
|
||||
static int logged;
|
||||
if (!logged++) LOG("hide_space_warp: removed space warp info from the eye images");
|
||||
++swapped;
|
||||
}
|
||||
}
|
||||
if (swap_eyes && layer->type == XR_TYPE_COMPOSITION_LAYER_PROJECTION &&
|
||||
((const XrCompositionLayerProjection *)layer)->viewCount == 2) {
|
||||
// Show each eye the image the game rendered for it: keep poses/FOVs, swap sub-images.
|
||||
@@ -1004,6 +1153,51 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
|
||||
layer = (const XrCompositionLayerBaseHeader *)&projections[count];
|
||||
++swapped;
|
||||
}
|
||||
if (rect_clamp) {
|
||||
// Keep every image rect inside its swapchain: Unity/OVRPlugin can size the eye area a few pixels past
|
||||
// the image on some Frames (PowerWash Simulator: rect 268+1656 on a 1920 wide swapchain) and SteamVR
|
||||
// then rejects every frame with XR_ERROR_SWAPCHAIN_RECT_INVALID (-25) (GitHub #39).
|
||||
uint32_t w, h;
|
||||
if (layer->type == XR_TYPE_COMPOSITION_LAYER_PROJECTION &&
|
||||
((const XrCompositionLayerProjection *)layer)->viewCount <= 2) {
|
||||
const XrCompositionLayerProjection *cur = (const XrCompositionLayerProjection *)layer;
|
||||
int over = 0;
|
||||
for (uint32_t v = 0; v < cur->viewCount; ++v) {
|
||||
XrRect2Di r = cur->views[v].subImage.imageRect;
|
||||
if (swapchain_size(cur->views[v].subImage.swapchain, &w, &h) && clamp_rect(&r, w, h)) over = 1;
|
||||
}
|
||||
if (over) {
|
||||
if (layer != (const XrCompositionLayerBaseHeader *)&projections[count]) projections[count] = *cur;
|
||||
if (projections[count].views != views[count])
|
||||
for (uint32_t v = 0; v < cur->viewCount; ++v) views[count][v] = cur->views[v];
|
||||
for (uint32_t v = 0; v < cur->viewCount; ++v)
|
||||
if (swapchain_size(views[count][v].subImage.swapchain, &w, &h) &&
|
||||
clamp_rect(&views[count][v].subImage.imageRect, w, h)) {
|
||||
static int logged;
|
||||
if (logged++ < 3)
|
||||
LOG("rect_clamp: view %u image rect clamped to %dx%d at %d,%d (swapchain %ux%u)", v,
|
||||
views[count][v].subImage.imageRect.extent.width,
|
||||
views[count][v].subImage.imageRect.extent.height,
|
||||
views[count][v].subImage.imageRect.offset.x,
|
||||
views[count][v].subImage.imageRect.offset.y, w, h);
|
||||
}
|
||||
projections[count].views = views[count];
|
||||
layer = (const XrCompositionLayerBaseHeader *)&projections[count];
|
||||
++swapped;
|
||||
}
|
||||
} else if (layer->type == XR_TYPE_COMPOSITION_LAYER_QUAD) {
|
||||
const XrCompositionLayerQuad *q = (const XrCompositionLayerQuad *)layer;
|
||||
XrRect2Di r = q->subImage.imageRect;
|
||||
if (swapchain_size(q->subImage.swapchain, &w, &h) && clamp_rect(&r, w, h)) {
|
||||
if (layer != (const XrCompositionLayerBaseHeader *)&quads[count]) quads[count] = *q;
|
||||
quads[count].subImage.imageRect = r;
|
||||
layer = (const XrCompositionLayerBaseHeader *)&quads[count];
|
||||
++swapped;
|
||||
static int logged;
|
||||
if (!logged++) LOG("rect_clamp: quad image rect clamped (swapchain %ux%u)", w, h);
|
||||
}
|
||||
}
|
||||
}
|
||||
kept[count++] = layer;
|
||||
}
|
||||
XrFrameEndInfo fixed = *info;
|
||||
@@ -1079,6 +1273,18 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetCurrentInteractionProfile(XrSession session,
|
||||
(PFN_xrGetCurrentInteractionProfile)lookup(active_instance, "xrGetCurrentInteractionProfile");
|
||||
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
|
||||
XrResult result = fn(session, user, state);
|
||||
if (layer_debug && active_instance) { // which device each hand has, as the runtime reports it
|
||||
PFN_xrPathToString str = (PFN_xrPathToString)lookup(active_instance, "xrPathToString");
|
||||
char who[XR_MAX_PATH_LENGTH] = "?", what[XR_MAX_PATH_LENGTH] = "(none)";
|
||||
uint32_t n = 0;
|
||||
if (str) {
|
||||
str(active_instance, user, sizeof(who), &n, who);
|
||||
if (XR_SUCCEEDED(result) && state && state->interactionProfile)
|
||||
str(active_instance, state->interactionProfile, sizeof(what), &n, what);
|
||||
}
|
||||
static int logged;
|
||||
if (logged++ < 40) LOG("layer_debug: interaction profile of %s: %s (result %d)", who, what, result);
|
||||
}
|
||||
if (!controller_fix || XR_FAILED(result) || !state || !state->interactionProfile || !active_instance)
|
||||
return result;
|
||||
PFN_xrPathToString to_string = (PFN_xrPathToString)lookup(active_instance, "xrPathToString");
|
||||
@@ -1098,7 +1304,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateInstanceExtensionProperties(const char
|
||||
XR_NULL_HANDLE, "xrEnumerateInstanceExtensionProperties");
|
||||
if (!fn) return XR_ERROR_INITIALIZATION_FAILED;
|
||||
if (!count) return XR_ERROR_VALIDATION_FAILURE;
|
||||
if ((!foveation_fix && !passthrough_emul && !scene_emul && !controller_models) || layer)
|
||||
if ((!foveation_fix && !hide_space_warp && !passthrough_emul && !scene_emul && !controller_models) || layer)
|
||||
return fn(layer, capacity, count, properties);
|
||||
|
||||
uint32_t total = 0;
|
||||
@@ -1115,6 +1321,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateInstanceExtensionProperties(const char
|
||||
if (!strcmp(all[i].extensionName, "XR_FB_passthrough")) runtime_has_fb_passthrough = 1;
|
||||
if (!strcmp(all[i].extensionName, XR_FB_RENDER_MODEL_EXTENSION_NAME)) runtime_has_render_model = 1;
|
||||
if (foveation_fix && strstr(all[i].extensionName, "foveation")) continue;
|
||||
if (hide_space_warp && !strcmp(all[i].extensionName, "XR_FB_space_warp")) continue;
|
||||
if (properties && kept < capacity) properties[kept] = all[i];
|
||||
++kept;
|
||||
}
|
||||
@@ -1211,8 +1418,13 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr(XrInstance instance, const
|
||||
if (layer_debug || refresh_rate > 0) {
|
||||
HOOK_AS(xrRequestDisplayRefreshRateFB, hook_request_refresh_rate)
|
||||
}
|
||||
if (layer_debug || aim_correction_on()) {
|
||||
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)
|
||||
HOOK_AS(xrSuggestInteractionProfileBindings, hook_xrSuggestInteractionProfileBindings)
|
||||
if (layer_debug || aim_correction_on()) {
|
||||
HOOK_AS(xrCreateActionSpace, hook_xrCreateActionSpace)
|
||||
}
|
||||
#undef HOOK_AS
|
||||
|
||||
@@ -95,9 +95,55 @@ static void debug_reference_space(XrSession session, const XrReferenceSpaceCreat
|
||||
LOG("layer_debug: that LOCAL space can't be located yet (no tracking)");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- sync_guard
|
||||
// The Frame's runtime crashed in xrSyncActions right after focus returned (SIGSEGV in vrclient.so
|
||||
// CVRInputLatest::UpdateActionStateInternal, Myst; a race inside the runtime, not every launch). sync_guard runs
|
||||
// xrSyncActions one at a time with xrPollEvent and skips it for a moment after FOCUSED arrives (XR_SESSION_NOT_FOCUSED
|
||||
// is a success code every app handles: no input for those few frames).
|
||||
#define SYNC_GUARD_PAUSE_NS 250000000ll
|
||||
static pthread_mutex_t sync_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int64_t sync_resume_at;
|
||||
|
||||
// layer_debug input counters, logged with the pacing line: were actions synced, did any button read as pressed?
|
||||
static int input_syncs, input_sync_ok, input_bool_reads, input_bool_true, input_last_sync_result;
|
||||
|
||||
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrSyncActions(XrSession session, const XrActionsSyncInfo *info) {
|
||||
PFN_xrSyncActions fn = (PFN_xrSyncActions)lookup(active_instance, "xrSyncActions");
|
||||
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
|
||||
if (!sync_guard) { // installed for layer_debug only: count
|
||||
XrResult r = fn(session, info);
|
||||
__atomic_add_fetch(&input_syncs, 1, __ATOMIC_RELAXED);
|
||||
if (r == XR_SUCCESS) __atomic_add_fetch(&input_sync_ok, 1, __ATOMIC_RELAXED);
|
||||
input_last_sync_result = r;
|
||||
return r;
|
||||
}
|
||||
pthread_mutex_lock(&sync_lock);
|
||||
int64_t wait = sync_resume_at - monotonic_ns();
|
||||
XrResult r = wait > 0 ? XR_SESSION_NOT_FOCUSED : fn(session, info);
|
||||
pthread_mutex_unlock(&sync_lock);
|
||||
static int logged;
|
||||
if (wait > 0 && logged++ < 5) LOG("sync_guard: input paused for %.0f ms after focus returned", wait / 1e6);
|
||||
return r;
|
||||
}
|
||||
|
||||
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrGetActionStateBoolean(XrSession session, const XrActionStateGetInfo *info,
|
||||
XrActionStateBoolean *state) {
|
||||
PFN_xrGetActionStateBoolean fn = (PFN_xrGetActionStateBoolean)lookup(active_instance, "xrGetActionStateBoolean");
|
||||
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
|
||||
XrResult r = fn(session, info, state);
|
||||
__atomic_add_fetch(&input_bool_reads, 1, __ATOMIC_RELAXED);
|
||||
if (r == XR_SUCCESS && state && state->isActive && state->currentState)
|
||||
__atomic_add_fetch(&input_bool_true, 1, __ATOMIC_RELAXED);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- focus_hold
|
||||
#define FOCUS_HOLD_MIN_FOCUSED_NS 3000000000ll // only after this long in FOCUSED (start-up transitions untouched)
|
||||
#define FOCUS_HOLD_MAX_DIP_NS 600000000ll // dips longer than this are delivered (late, in order)
|
||||
#define FOCUS_HOLD_MIN_FOCUSED_NS 1000000000ll // only after this long in FOCUSED (start-up transitions untouched;
|
||||
// 3 s let a 27 ms dip through in Blade & Sorcery)
|
||||
// dips longer than focus_hold_ms (setting, default 1000) are delivered (late, in order): taking the headset off or the
|
||||
// system menu must still pause the game. A longer limit is for headsets whose wear sensor flickers ("HMD off" for
|
||||
// 0.5-2 s while worn; Blade & Sorcery pauses on each)
|
||||
#define FOCUS_HOLD_MAX_DIP_NS ((int64_t)(focus_hold_ms * 1000000.0f))
|
||||
static struct {
|
||||
XrEventDataBuffer events[6];
|
||||
int count, holding, delivering;
|
||||
@@ -131,7 +177,7 @@ static XrResult focus_hold_poll(PFN_xrPollEvent fn, XrInstance instance, XrEvent
|
||||
if (result != XR_SUCCESS) {
|
||||
if (held.holding && now - held.since > FOCUS_HOLD_MAX_DIP_NS) {
|
||||
LOG("focus_hold: focus lost for > %lld ms, delivering %d state change(s)",
|
||||
FOCUS_HOLD_MAX_DIP_NS / 1000000, held.count);
|
||||
(long long)(FOCUS_HOLD_MAX_DIP_NS / 1000000), held.count);
|
||||
held.holding = 0; held.delivering = 1;
|
||||
continue;
|
||||
}
|
||||
@@ -195,20 +241,100 @@ static int pose_action_kind(XrAction action) { // 1 aim, 0 grip, -1 unknown
|
||||
return kind;
|
||||
}
|
||||
|
||||
// Meta's newer controller profiles, which the Frame's runtime doesn't know (it has oculus/touch_controller). An app
|
||||
// that suggests bindings only for these gets XR_ERROR_PATH_UNSUPPORTED and no input (e.g. a setup screen that can't be
|
||||
// passed); its bindings are suggested again for Touch, keeping the components Touch controllers have.
|
||||
static const char *const NEWER_TOUCH[] = {"/interaction_profiles/meta/touch_controller_plus",
|
||||
"/interaction_profiles/meta/touch_plus_controller",
|
||||
"/interaction_profiles/facebook/touch_controller_pro",
|
||||
"/interaction_profiles/meta/touch_pro_controller",
|
||||
"/interaction_profiles/meta/touch_controller_rift_cv1",
|
||||
"/interaction_profiles/meta/touch_controller_quest_1_rift_s",
|
||||
"/interaction_profiles/meta/touch_controller_quest_2"};
|
||||
static const char *const TOUCH_PROFILE = "/interaction_profiles/oculus/touch_controller";
|
||||
// oculus/touch_controller components (OpenXR spec), after /user/hand/<left|right>/
|
||||
static const char *const TOUCH_COMMON[] = {"input/squeeze/value", "input/trigger/value", "input/trigger/touch",
|
||||
"input/thumbstick", "input/thumbstick/x", "input/thumbstick/y", "input/thumbstick/click",
|
||||
"input/thumbstick/touch", "input/thumbrest/touch", "input/grip/pose", "input/aim/pose", "output/haptic"};
|
||||
static const char *const TOUCH_LEFT[] = {"input/x/click", "input/x/touch", "input/y/click", "input/y/touch",
|
||||
"input/menu/click"};
|
||||
static const char *const TOUCH_RIGHT[] = {"input/a/click", "input/a/touch", "input/b/click", "input/b/touch",
|
||||
"input/system/click"};
|
||||
static int app_suggested_touch;
|
||||
|
||||
static int in_list(const char *s, const char *const *list, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
if (!strcmp(s, list[i])) return 1;
|
||||
return 0;
|
||||
}
|
||||
#define IN(s, list) in_list(s, list, sizeof(list) / sizeof(*list))
|
||||
|
||||
// 1 if the binding path exists on oculus/touch_controller
|
||||
static int touch_has(const char *path) {
|
||||
const char *left = "/user/hand/left/", *right = "/user/hand/right/";
|
||||
if (!strncmp(path, left, strlen(left))) {
|
||||
path += strlen(left);
|
||||
return IN(path, TOUCH_COMMON) || IN(path, TOUCH_LEFT);
|
||||
}
|
||||
if (!strncmp(path, right, strlen(right))) {
|
||||
path += strlen(right);
|
||||
return IN(path, TOUCH_COMMON) || IN(path, TOUCH_RIGHT);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static XrResult remap_to_touch(XrInstance instance, PFN_xrSuggestInteractionProfileBindings fn,
|
||||
PFN_xrPathToString to_string, const XrInteractionProfileSuggestedBinding *suggested,
|
||||
const char *profile) {
|
||||
PFN_xrStringToPath to_path = (PFN_xrStringToPath)lookup(instance, "xrStringToPath");
|
||||
XrPath touch;
|
||||
if (!to_path || XR_FAILED(to_path(instance, TOUCH_PROFILE, &touch))) return XR_ERROR_PATH_UNSUPPORTED;
|
||||
uint32_t n = suggested->countSuggestedBindings, kept = 0;
|
||||
XrActionSuggestedBinding *b = calloc(n ? n : 1, sizeof(*b));
|
||||
if (!b) return XR_ERROR_OUT_OF_MEMORY;
|
||||
for (uint32_t i = 0; i < n; ++i) {
|
||||
char path[XR_MAX_PATH_LENGTH];
|
||||
uint32_t size = 0;
|
||||
if (XR_SUCCEEDED(to_string(instance, suggested->suggestedBindings[i].binding, sizeof(path), &size, path))
|
||||
&& touch_has(path))
|
||||
b[kept++] = suggested->suggestedBindings[i];
|
||||
}
|
||||
XrInteractionProfileSuggestedBinding copy = *suggested;
|
||||
copy.interactionProfile = touch;
|
||||
copy.countSuggestedBindings = kept;
|
||||
copy.suggestedBindings = b;
|
||||
XrResult r = kept ? fn(instance, ©) : XR_ERROR_PATH_UNSUPPORTED;
|
||||
free(b);
|
||||
LOG("controller profile %s -> oculus/touch_controller (%u bindings, %u dropped): %d", profile + 22, kept,
|
||||
n - kept, r);
|
||||
return r;
|
||||
}
|
||||
|
||||
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrSuggestInteractionProfileBindings(XrInstance instance,
|
||||
const XrInteractionProfileSuggestedBinding *suggested) {
|
||||
PFN_xrSuggestInteractionProfileBindings fn =
|
||||
(PFN_xrSuggestInteractionProfileBindings)lookup(instance, "xrSuggestInteractionProfileBindings");
|
||||
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
|
||||
PFN_xrPathToString to_string = (PFN_xrPathToString)lookup(instance, "xrPathToString");
|
||||
if (suggested && to_string)
|
||||
if (suggested && to_string && (layer_debug || aim_correction_on()))
|
||||
for (uint32_t i = 0; i < suggested->countSuggestedBindings; ++i) {
|
||||
char path[XR_MAX_PATH_LENGTH];
|
||||
uint32_t size = 0;
|
||||
if (XR_SUCCEEDED(to_string(instance, suggested->suggestedBindings[i].binding, sizeof(path), &size, path)))
|
||||
note_pose_binding(suggested->suggestedBindings[i].action, path);
|
||||
}
|
||||
return fn(instance, suggested);
|
||||
XrResult r = fn(instance, suggested);
|
||||
if (!profile_remap || !suggested || !to_string) return r;
|
||||
char profile[XR_MAX_PATH_LENGTH] = {0};
|
||||
uint32_t size = 0;
|
||||
if (XR_FAILED(to_string(instance, suggested->interactionProfile, sizeof(profile), &size, profile))) return r;
|
||||
if (!strcmp(profile, TOUCH_PROFILE)) {
|
||||
if (XR_SUCCEEDED(r)) app_suggested_touch = 1; // the app's own Touch bindings win over a remap
|
||||
return r;
|
||||
}
|
||||
if (r != XR_ERROR_PATH_UNSUPPORTED || app_suggested_touch || !IN(profile, NEWER_TOUCH)) return r;
|
||||
XrResult remapped = remap_to_touch(instance, fn, to_string, suggested, profile);
|
||||
return XR_SUCCEEDED(remapped) ? XR_SUCCESS : r;
|
||||
}
|
||||
|
||||
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrCreateActionSpace(XrSession session, const XrActionSpaceCreateInfo *info,
|
||||
|
||||
@@ -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, ©);
|
||||
}
|
||||
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);
|
||||
}
|
||||
+34
-5
@@ -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,vrsettings] [--ndk PATH]
|
||||
python native/build.py [--only adapter,bridge,compat,langpack,glshim,eglfmt,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",
|
||||
@@ -230,6 +239,16 @@ def build_glshim(tc: Path):
|
||||
"-Wl,-z,max-page-size=16384", "glshim.c", "-ldl", "-llog", "-o", ART / "arm64-v8a/libglshim.so"], cwd=src)
|
||||
|
||||
|
||||
def build_eglfmt(tc: Path):
|
||||
"""Depth-format shim (see glshim/eglfmt.c) that GL-to-GLES wrappers (QuestCraft's LTW) load in place of libEGL.so.
|
||||
Named libfpg.so: no longer than "libEGL.so", whose dlopen string in the wrapper is rewritten in place. Linked to
|
||||
libEGL so a dlsym on its handle still finds every EGL function."""
|
||||
src = HERE / "glshim"
|
||||
run([exe(tc, "aarch64-linux-android29-clang"), "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror",
|
||||
"-fvisibility=hidden", "-Wl,-soname,libfpg.so", "-Wl,-z,max-page-size=16384", "eglfmt.c",
|
||||
"-Wl,--no-as-needed", "-lEGL", "-Wl,--as-needed", "-ldl", "-llog", "-o", ART / "arm64-v8a/libfpg.so"], cwd=src)
|
||||
|
||||
|
||||
def build_xrshim(tc: Path):
|
||||
"""FrameBridge extension shim (see xrshim/xrshim.c): DT_NEEDED-injected in front of overport's libopenxr_loader.so."""
|
||||
src = HERE / "xrshim"
|
||||
@@ -247,6 +266,14 @@ def build_vkshim(tc: Path):
|
||||
cwd=src)
|
||||
|
||||
|
||||
def build_ovrpshim(tc: Path):
|
||||
"""OVRPlugin frame-loop shim (see ovrpshim/ovrpshim.c) for Unity 2017-2018 built-in Oculus support."""
|
||||
src = HERE / "ovrpshim"
|
||||
run([exe(tc, "aarch64-linux-android29-clang"), "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror",
|
||||
"-fvisibility=hidden", "-Wl,-soname,libfp_ovrp.so", "-Wl,-z,max-page-size=16384", "ovrpshim.c", "-ldl",
|
||||
"-llog", "-o", ART / "arm64-v8a/libfp_ovrp.so"], cwd=src)
|
||||
|
||||
|
||||
def build_dex():
|
||||
javac = shutil.which("javac")
|
||||
if not javac:
|
||||
@@ -291,7 +318,7 @@ def write_sums():
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--only", default="adapter,bridge,compat,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,vrsettings")
|
||||
ap.add_argument("--only", default="adapter,bridge,compat,langpack,glshim,eglfmt,dex,xrlayer,oculushmd,xrshim,vkshim,ovrpshim,vrsettings")
|
||||
ap.add_argument("--ndk")
|
||||
args = ap.parse_args()
|
||||
parts = set(args.only.split(","))
|
||||
@@ -299,10 +326,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),
|
||||
"glshim": lambda: build_glshim(tc), "xrshim": lambda: build_xrshim(tc), "dex": build_dex, "xrlayer": lambda: build_xrlayer(tc),
|
||||
"langpack": lambda: build_langpack(tc),
|
||||
"glshim": lambda: build_glshim(tc), "eglfmt": lambda: build_eglfmt(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", "dex", "xrlayer", "oculushmd", "vrsettings"):
|
||||
for name in ("adapter", "bridge", "compat", "langpack", "glshim", "eglfmt", "xrshim", "vkshim", "ovrpshim", "dex", "xrlayer", "oculushmd", "vrsettings"):
|
||||
if name in parts:
|
||||
log(f"build {name}")
|
||||
steps[name]()
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// FramePort depth-format shim for GL-to-GLES wrappers (QuestCraft's LTW): desktop OpenGL's sized depth format
|
||||
// GL_DEPTH_COMPONENT32 doesn't exist in OpenGL ES. Qualcomm's Quest driver accepts it anyway; the Frame's Mesa (Zink)
|
||||
// rejects it (GL_INVALID_OPERATION in glTexImage2D), so Minecraft's depth textures never exist, every framebuffer that
|
||||
// uses them is incomplete and the picture stays black. LTW resolves every GLES function through eglGetProcAddress from
|
||||
// a libEGL it dlopens itself; FramePort points that dlopen string at this library (patches/frame/ltw_depth.py), which
|
||||
// hands back wrappers for the texture/renderbuffer allocation functions and the real functions for everything else:
|
||||
// GL_DEPTH_COMPONENT32 -> GL_DEPTH_COMPONENT32F (GL_DEPTH_COMPONENT24 when pixel data comes as GL_UNSIGNED_INT),
|
||||
// unsized GL_DEPTH_COMPONENT with GL_FLOAT data -> GL_DEPTH_COMPONENT32F.
|
||||
#define _GNU_SOURCE
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl32.h>
|
||||
#include <android/log.h>
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <string.h>
|
||||
|
||||
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "FrameBridge", __VA_ARGS__)
|
||||
#define EXPORT __attribute__((visibility("default")))
|
||||
#ifndef GL_DEPTH_COMPONENT32
|
||||
#define GL_DEPTH_COMPONENT32 0x81A7
|
||||
#endif
|
||||
|
||||
typedef __eglMustCastToProperFunctionPointerType FnPtr;
|
||||
static FnPtr (*real_gpa)(const char *);
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
static int logged;
|
||||
|
||||
static void init(void) {
|
||||
void *egl = dlopen("libEGL.so", RTLD_NOW | RTLD_LOCAL);
|
||||
real_gpa = egl ? (FnPtr (*)(const char *))dlsym(egl, "eglGetProcAddress") : NULL;
|
||||
LOG("depth format shim: libEGL.so %s", real_gpa ? "OK" : "MISSING");
|
||||
}
|
||||
|
||||
// the ES internal format for a desktop depth request (`type` = the pixel data type, 0 when there is none)
|
||||
static GLint fix(GLint internal, GLenum type, const char *fn) {
|
||||
GLint out = internal;
|
||||
if (internal == GL_DEPTH_COMPONENT32) out = type == GL_UNSIGNED_INT ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT32F;
|
||||
else if (internal == GL_DEPTH_COMPONENT && type == GL_FLOAT) out = GL_DEPTH_COMPONENT32F;
|
||||
if (out != internal && logged < 8) {
|
||||
logged++;
|
||||
LOG("depth format shim: %s 0x%x -> 0x%x", fn, internal, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static PFNGLTEXIMAGE2DPROC r_ti2;
|
||||
static PFNGLTEXIMAGE3DPROC r_ti3;
|
||||
static PFNGLTEXSTORAGE2DPROC r_ts2;
|
||||
static PFNGLTEXSTORAGE3DPROC r_ts3;
|
||||
static PFNGLTEXSTORAGE2DMULTISAMPLEPROC r_ts2ms;
|
||||
static PFNGLTEXSTORAGE3DMULTISAMPLEPROC r_ts3ms;
|
||||
static PFNGLRENDERBUFFERSTORAGEPROC r_rbs;
|
||||
static PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC r_rbsms;
|
||||
|
||||
static void GL_APIENTRY w_ti2(GLenum t, GLint l, GLint i, GLsizei w, GLsizei h, GLint b, GLenum f, GLenum ty, const void *d) {
|
||||
r_ti2(t, l, fix(i, ty, "glTexImage2D"), w, h, b, f, ty, d);
|
||||
}
|
||||
static void GL_APIENTRY w_ti3(GLenum t, GLint l, GLint i, GLsizei w, GLsizei h, GLsizei dp, GLint b, GLenum f, GLenum ty,
|
||||
const void *d) {
|
||||
r_ti3(t, l, fix(i, ty, "glTexImage3D"), w, h, dp, b, f, ty, d);
|
||||
}
|
||||
static void GL_APIENTRY w_ts2(GLenum t, GLsizei l, GLenum i, GLsizei w, GLsizei h) {
|
||||
r_ts2(t, l, (GLenum)fix((GLint)i, 0, "glTexStorage2D"), w, h);
|
||||
}
|
||||
static void GL_APIENTRY w_ts3(GLenum t, GLsizei l, GLenum i, GLsizei w, GLsizei h, GLsizei d) {
|
||||
r_ts3(t, l, (GLenum)fix((GLint)i, 0, "glTexStorage3D"), w, h, d);
|
||||
}
|
||||
static void GL_APIENTRY w_ts2ms(GLenum t, GLsizei s, GLenum i, GLsizei w, GLsizei h, GLboolean fl) {
|
||||
r_ts2ms(t, s, (GLenum)fix((GLint)i, 0, "glTexStorage2DMultisample"), w, h, fl);
|
||||
}
|
||||
static void GL_APIENTRY w_ts3ms(GLenum t, GLsizei s, GLenum i, GLsizei w, GLsizei h, GLsizei d, GLboolean fl) {
|
||||
r_ts3ms(t, s, (GLenum)fix((GLint)i, 0, "glTexStorage3DMultisample"), w, h, d, fl);
|
||||
}
|
||||
static void GL_APIENTRY w_rbs(GLenum t, GLenum i, GLsizei w, GLsizei h) {
|
||||
r_rbs(t, (GLenum)fix((GLint)i, 0, "glRenderbufferStorage"), w, h);
|
||||
}
|
||||
static void GL_APIENTRY w_rbsms(GLenum t, GLsizei s, GLenum i, GLsizei w, GLsizei h) {
|
||||
r_rbsms(t, s, (GLenum)fix((GLint)i, 0, "glRenderbufferStorageMultisample"), w, h);
|
||||
}
|
||||
|
||||
EXPORT FnPtr eglGetProcAddress(const char *name) {
|
||||
pthread_once(&once, init);
|
||||
FnPtr fn = real_gpa && name ? real_gpa(name) : NULL;
|
||||
if (!fn) return fn;
|
||||
#define WRAP(sym, real, w) if (!strcmp(name, sym)) { real = (void *)fn; return (FnPtr)w; }
|
||||
WRAP("glTexImage2D", r_ti2, w_ti2)
|
||||
WRAP("glTexImage3D", r_ti3, w_ti3)
|
||||
WRAP("glTexStorage2D", r_ts2, w_ts2)
|
||||
WRAP("glTexStorage3D", r_ts3, w_ts3)
|
||||
WRAP("glTexStorage2DMultisample", r_ts2ms, w_ts2ms)
|
||||
WRAP("glTexStorage3DMultisample", r_ts3ms, w_ts3ms)
|
||||
WRAP("glRenderbufferStorage", r_rbs, w_rbs)
|
||||
WRAP("glRenderbufferStorageMultisample", r_rbsms, w_rbsms)
|
||||
#undef WRAP
|
||||
return fn;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// FramePort OVRPlugin frame-loop shim for Unity 2017-2018 built-in Oculus support.
|
||||
//
|
||||
// That Unity drives OVRPlugin with the legacy frame loop: ovrp_Update2(render step, frame index, ...) on the main
|
||||
// thread, then ovrp_BeginFrame / ovrp_EndFrame on the render thread. It never calls ovrp_WaitToBeginFrame, which
|
||||
// newer OVRPlugin builds (OVRPort's OpenXR OVRPlugin) need to call xrWaitFrame: no frame ever begins, OVRPlugin logs
|
||||
// "CompositorOpenXR::Update called for frame N outside of frame bounds" thousands of times a second and the Frame's
|
||||
// dashboard freezes (Accounting+, Unity 2017.4).
|
||||
//
|
||||
// FramePort renames the "ovrp_Update2" lookup in libunity.so to "fpov_Update2" (same length) and adds this library to
|
||||
// libOVRPlugin.so's DT_NEEDED, so Unity's dlsym on the plugin finds this function: it waits for the frame first (once
|
||||
// per frame index, render step only), then calls the real ovrp_Update2.
|
||||
#include <android/log.h>
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#define TAG "FrameBridge"
|
||||
#define EXPORT __attribute__((visibility("default")))
|
||||
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
||||
|
||||
typedef int (*PFN_Update2)(int step, int frame_index, double prediction_seconds);
|
||||
typedef int (*PFN_WaitToBeginFrame)(int frame_index);
|
||||
|
||||
static PFN_Update2 real_update2;
|
||||
static PFN_WaitToBeginFrame real_wait;
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
|
||||
static void init(void) {
|
||||
void *ovrp = dlopen("libOVRPlugin.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
if (!ovrp) ovrp = dlopen("libOVRPlugin.so", RTLD_NOW);
|
||||
if (ovrp) {
|
||||
real_update2 = (PFN_Update2)dlsym(ovrp, "ovrp_Update2");
|
||||
real_wait = (PFN_WaitToBeginFrame)dlsym(ovrp, "ovrp_WaitToBeginFrame");
|
||||
}
|
||||
LOG("ovrp frame loop shim: ovrp_Update2 %s, ovrp_WaitToBeginFrame %s", real_update2 ? "OK" : "MISSING",
|
||||
real_wait ? "OK" : "MISSING");
|
||||
}
|
||||
|
||||
#define STEP_RENDER (-1) // ovrpStep_Render
|
||||
|
||||
EXPORT int fpov_Update2(int step, int frame_index, double prediction_seconds) {
|
||||
pthread_once(&once, init);
|
||||
static int last_waited = -1, logged;
|
||||
if (step == STEP_RENDER && real_wait && frame_index != last_waited) {
|
||||
last_waited = frame_index;
|
||||
int r = real_wait(frame_index);
|
||||
if (logged++ < 3) LOG("ovrp frame loop shim: waited for frame %d: %d", frame_index, r);
|
||||
}
|
||||
return real_update2 ? real_update2(step, frame_index, prediction_seconds) : -1000; // ovrpFailure
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- input diagnostics (pass-through)
|
||||
// The game's C# input (OVRInput) asks OVRPlugin which controllers are connected and for their button state. These
|
||||
// wrappers return exactly what OVRPlugin returns and log the connected mask and every change of the button bits, to
|
||||
// see whether presses reach the game (Accounting+ stuck at "press any button" while the runtime reports presses).
|
||||
typedef struct { unsigned int words[3]; } State; // the common start: ConnectedControllers, Buttons, Touches
|
||||
// ovrpControllerState2 is returned by value (through x8): the type must have its exact size, 64 bytes (4 uint32,
|
||||
// IndexTrigger[2], HandTrigger[2], Thumbstick[2] and Touchpad[2] as float pairs)
|
||||
typedef struct { unsigned int words[16]; } State2;
|
||||
_Static_assert(sizeof(State2) == 64, "ovrpControllerState2 is 64 bytes");
|
||||
typedef unsigned int (*PFN_GetConnected)(void);
|
||||
typedef int (*PFN_GetState4)(unsigned int mask, State *state); // (written by OVRPlugin; only the start is read)
|
||||
typedef State2 (*PFN_GetState2)(unsigned int mask);
|
||||
static PFN_GetConnected real_connected;
|
||||
static PFN_GetState4 real_state4;
|
||||
static PFN_GetState2 real_state2;
|
||||
static pthread_once_t input_once = PTHREAD_ONCE_INIT;
|
||||
|
||||
static void input_init(void) {
|
||||
void *ovrp = dlopen("libOVRPlugin.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
if (!ovrp) return;
|
||||
real_connected = (PFN_GetConnected)dlsym(ovrp, "ovrp_GetConnectedControllers");
|
||||
real_state4 = (PFN_GetState4)dlsym(ovrp, "ovrp_GetControllerState4");
|
||||
real_state2 = (PFN_GetState2)dlsym(ovrp, "ovrp_GetControllerState2");
|
||||
}
|
||||
|
||||
// per requested controller mask (the game may ask for Touch, Remote, Gamepad... separately)
|
||||
static struct { unsigned int mask, connected, buttons; int seen; } masks[8];
|
||||
static int changes;
|
||||
|
||||
// Face buttons on the Frame's controllers can read as clicked while only touched (Accounting+: buttons == touches ==
|
||||
// A|B|X|Y held for seconds). A button held for more than STUCK_NS is reported released until it really lets go, so
|
||||
// real presses (short) still register as a change.
|
||||
#include <time.h>
|
||||
#define STUCK_NS 2000000000ll
|
||||
static long long held_since[32];
|
||||
static unsigned int suppressed;
|
||||
|
||||
static long long now_ns(void) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return t.tv_sec * 1000000000ll + t.tv_nsec;
|
||||
}
|
||||
|
||||
static unsigned int unstick(unsigned int buttons) {
|
||||
long long now = now_ns();
|
||||
for (int b = 0; b < 32; b++) {
|
||||
unsigned int bit = 1u << b;
|
||||
if (!(buttons & bit)) {
|
||||
held_since[b] = 0;
|
||||
suppressed &= ~bit;
|
||||
continue;
|
||||
}
|
||||
if (!held_since[b]) held_since[b] = now;
|
||||
if (now - held_since[b] > STUCK_NS && !(suppressed & bit)) {
|
||||
suppressed |= bit;
|
||||
static int logged;
|
||||
if (logged++ < 20) LOG("ovrp input: button 0x%x held for > 2 s: reported released until let go", bit);
|
||||
}
|
||||
}
|
||||
return buttons & ~suppressed;
|
||||
}
|
||||
|
||||
static void note_state(const char *which, unsigned int mask, const State *s) {
|
||||
int i = 0;
|
||||
while (i < 8 && masks[i].seen && masks[i].mask != mask) i++;
|
||||
if (i == 8) return;
|
||||
if (!masks[i].seen || masks[i].buttons != s->words[1] || masks[i].connected != s->words[0]) {
|
||||
if (changes++ < 120)
|
||||
LOG("ovrp input: %s(mask 0x%x): connected 0x%x buttons 0x%x touches 0x%x%s", which, mask, s->words[0],
|
||||
s->words[1], s->words[2], masks[i].seen ? "" : " (first call with this mask)");
|
||||
masks[i].seen = 1;
|
||||
masks[i].mask = mask;
|
||||
masks[i].connected = s->words[0];
|
||||
masks[i].buttons = s->words[1];
|
||||
}
|
||||
}
|
||||
|
||||
EXPORT unsigned int fpov_GetConnectedControllers(void) {
|
||||
pthread_once(&input_once, input_init);
|
||||
unsigned int c = real_connected ? real_connected() : 0;
|
||||
static unsigned int last = 0xffffffffu;
|
||||
static int logged;
|
||||
if (c != last && logged++ < 20) LOG("ovrp input: connected controllers 0x%x", c);
|
||||
last = c;
|
||||
return c;
|
||||
}
|
||||
|
||||
EXPORT int fpov_GetControllerState4(unsigned int mask, State *state) {
|
||||
pthread_once(&input_once, input_init);
|
||||
int r = real_state4 ? real_state4(mask, state) : -1000;
|
||||
if (state) {
|
||||
note_state("State4", mask, state);
|
||||
state->words[1] = unstick(state->words[1]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
EXPORT State2 fpov_GetControllerState2(unsigned int mask) {
|
||||
pthread_once(&input_once, input_init);
|
||||
State2 s = {{0}};
|
||||
if (real_state2) s = real_state2(mask);
|
||||
note_state("State2", mask, (const State *)&s);
|
||||
s.words[1] = unstick(s.words[1]);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Unity's own input (libunity.so: Input.GetKey/anyKey on the Oculus device) reads ovrp_GetControllerState (v1,
|
||||
// returned by value, 48 bytes: 4 uint32, IndexTrigger[2], HandTrigger[2], Thumbstick[2]) and ovrp_GetControllerState2
|
||||
typedef struct { unsigned int words[12]; } State1;
|
||||
_Static_assert(sizeof(State1) == 48, "ovrpControllerState is 48 bytes");
|
||||
typedef State1 (*PFN_GetState1)(unsigned int mask);
|
||||
static PFN_GetState1 real_state1;
|
||||
|
||||
EXPORT State1 fpov_GetControllerState(unsigned int mask) {
|
||||
pthread_once(&input_once, input_init);
|
||||
if (!real_state1) {
|
||||
void *ovrp = dlopen("libOVRPlugin.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
if (ovrp) real_state1 = (PFN_GetState1)dlsym(ovrp, "ovrp_GetControllerState");
|
||||
}
|
||||
State1 s = {{0}};
|
||||
if (real_state1) s = real_state1(mask);
|
||||
note_state("State1(unity)", mask, (const State *)&s);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Oculus Utilities (1.3x) ignores every button unless OVRPlugin reports input focus; with Unity 2017's legacy frame
|
||||
// loop on OVRPort's OVRPlugin that may never be true. Report it as true (the session's own focus still pauses the game)
|
||||
// and log what OVRPlugin said.
|
||||
typedef int (*PFN_GetInputFocus)(int *has_focus);
|
||||
static PFN_GetInputFocus real_input_focus;
|
||||
|
||||
EXPORT int fpov_GetAppHasInputFocus(int *has_focus) {
|
||||
pthread_once(&input_once, input_init);
|
||||
if (!real_input_focus) {
|
||||
void *ovrp = dlopen("libOVRPlugin.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
if (ovrp) real_input_focus = (PFN_GetInputFocus)dlsym(ovrp, "ovrp_GetAppHasInputFocus");
|
||||
}
|
||||
int value = 0, r = real_input_focus ? real_input_focus(&value) : -1000;
|
||||
static int last = -2, logged;
|
||||
if ((r < 0 ? -1 : value) != last && logged++ < 20) LOG("ovrp input: OVRPlugin input focus %d (result %d)", value, r);
|
||||
last = r < 0 ? -1 : value;
|
||||
if (has_focus) *has_focus = 1;
|
||||
return 0; // ovrpSuccess
|
||||
}
|
||||
+492
-10
@@ -8,6 +8,26 @@
|
||||
// at this shim (patches/frame/vk_sanitize.py). dlsym on the shim finds the functions below first and every other
|
||||
// symbol in its dependency, the real libvulkan.so. Valid pointers are kept; a pointer is dropped only when it isn't
|
||||
// readable memory or doesn't point at a structure type the parent may chain.
|
||||
//
|
||||
// Shader fixes (adapter setting vk_shader_fix, from a game's recipe): a SPIR-V module whose size and SHA-256 match is
|
||||
// copied with extra 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). Every other module passes through unchanged.
|
||||
// Format: vk_shader_fix=<size>:<sha256 hex>:<byte offset>:<word>,<word>,...[;<next fix>]
|
||||
//
|
||||
// Query slots (adapter setting vk_query_slots=2, per game): with multiview, Vulkan counts a query that runs in a
|
||||
// multiview render pass as one query per view (N consecutive indices). Mesa's drivers (the Frame's Turnip) write a
|
||||
// zero result into the extra views' slots; Meta's Quest driver doesn't. Engines that allocate one slot per query
|
||||
// (Into The Radius 2, Unreal 5) then have the next object's occlusion query overwritten with "0 samples" and cull it:
|
||||
// models pop in and out. With the setting, occlusion pools get N slots per query; query i uses slot N*i, so the extra
|
||||
// views land in N*i+1.., and results are read from slot N*i only (view 0's count; Turnip counts every view there).
|
||||
//
|
||||
// Spec fixes (vk_spec_fixes=1, per game; found with the validation layer in Into The Radius 2, Unreal 5):
|
||||
// * depth/stencil images created without VK_IMAGE_USAGE_TRANSFER_DST_BIT are cleared with vkCmdClearDepthStencilImage
|
||||
// (VUID-vkCmdClearDepthStencilImage-pRanges-02659); Mesa's Turnip picks the image's compression from its usage, so
|
||||
// the flag is added at vkCreateImage.
|
||||
// * subpasses with Qualcomm's shader resolve (VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM) also name a depth
|
||||
// resolve attachment for a single-sampled depth attachment (VUID-VkSubpassDescription2-flags-04908, -03179): the
|
||||
// resolve is dropped (there is nothing to resolve from one sample).
|
||||
#define _GNU_SOURCE
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <android/log.h>
|
||||
@@ -27,14 +47,177 @@ static void *real_vk;
|
||||
static PFN_vkGetInstanceProcAddr real_gipa;
|
||||
static PFN_vkGetDeviceProcAddr real_gdpa;
|
||||
static PFN_vkCreateRenderPass2 real_rp2_trampoline;
|
||||
static PFN_vkCreateShaderModule real_csm_trampoline;
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
|
||||
// ---------------------------------------------------------------- shader fixes (settings)
|
||||
|
||||
#define MAX_FIXES 16
|
||||
#define MAX_WORDS 64
|
||||
static struct {
|
||||
size_t size, offset;
|
||||
uint8_t sha[32];
|
||||
uint32_t words[MAX_WORDS];
|
||||
int nwords;
|
||||
} fixes[MAX_FIXES];
|
||||
static int nfixes;
|
||||
|
||||
static int hexval(char c) {
|
||||
return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
|
||||
}
|
||||
|
||||
static void parse_fixes(char *v) {
|
||||
for (char *save = NULL, *item = strtok_r(v, ";", &save); item && nfixes < MAX_FIXES; item = strtok_r(NULL, ";", &save)) {
|
||||
char *f[4] = {0}, *save2 = NULL;
|
||||
int n = 0;
|
||||
for (char *t = strtok_r(item, ":", &save2); t && n < 4; t = strtok_r(NULL, ":", &save2)) f[n++] = t;
|
||||
if (n != 4 || strlen(f[1]) != 64) continue;
|
||||
int ok = 1;
|
||||
for (int i = 0; i < 32 && ok; i++) {
|
||||
int hi = hexval(f[1][2 * i]), lo = hexval(f[1][2 * i + 1]);
|
||||
if (hi < 0 || lo < 0) ok = 0; else fixes[nfixes].sha[i] = (uint8_t)(hi << 4 | lo);
|
||||
}
|
||||
fixes[nfixes].size = strtoul(f[0], NULL, 0);
|
||||
fixes[nfixes].offset = strtoul(f[2], NULL, 0);
|
||||
int nw = 0;
|
||||
for (char *save3 = NULL, *w = strtok_r(f[3], ",", &save3); w && nw < MAX_WORDS; w = strtok_r(NULL, ",", &save3))
|
||||
fixes[nfixes].words[nw++] = (uint32_t)strtoul(w, NULL, 0);
|
||||
fixes[nfixes].nwords = nw;
|
||||
if (ok && nw && fixes[nfixes].size % 4 == 0 && fixes[nfixes].offset % 4 == 0 &&
|
||||
fixes[nfixes].offset >= 20 && fixes[nfixes].offset <= fixes[nfixes].size)
|
||||
nfixes++;
|
||||
}
|
||||
}
|
||||
|
||||
static int query_slots = 1; // vk_query_slots: slots per occlusion query (1 = untouched)
|
||||
static int spec_fixes; // vk_spec_fixes: make two Unreal habits valid Vulkan (depth clears, depth resolves)
|
||||
#define VALIDATION_LAYER "VK_LAYER_KHRONOS_validation"
|
||||
static int validation; // vk_validation: add Khronos' validation layer (bundled in the APK) to the instance
|
||||
|
||||
static void read_settings(const char *path) {
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return;
|
||||
char line[4096];
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
line[strcspn(line, "\r\n")] = 0;
|
||||
if (!strncmp(line, "vk_validation=", 14)) validation = atoi(line + 14) != 0;
|
||||
if (!strncmp(line, "vk_spec_fixes=", 14)) spec_fixes = atoi(line + 14) != 0;
|
||||
if (!strncmp(line, "vk_query_slots=", 15)) {
|
||||
int v = atoi(line + 15);
|
||||
query_slots = v == 1 ? 2 : v >= 2 && v <= 4 ? v : 1; // 1 = on (the settings dialog's switch) = 2 slots
|
||||
}
|
||||
if (!strncmp(line, "vk_shader_fix=", 14)) {
|
||||
nfixes = 0; // later sources override earlier ones (as for the adapter's settings)
|
||||
parse_fixes(line + 14);
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void read_all_settings(void) {
|
||||
char path[600];
|
||||
Dl_info info;
|
||||
if (dladdr((void *)read_all_settings, &info) && info.dli_fname) {
|
||||
const char *slash = strrchr(info.dli_fname, '/');
|
||||
if (slash && slash - info.dli_fname < 500) {
|
||||
snprintf(path, sizeof path, "%.*s/libframe_settings.so", (int)(slash - info.dli_fname), info.dli_fname);
|
||||
read_settings(path);
|
||||
}
|
||||
}
|
||||
char pkg[256] = {0};
|
||||
FILE *f = fopen("/proc/self/cmdline", "r");
|
||||
if (f) {
|
||||
size_t n = fread(pkg, 1, sizeof pkg - 1, f);
|
||||
pkg[n] = 0;
|
||||
fclose(f);
|
||||
}
|
||||
char *colon = strchr(pkg, ':');
|
||||
if (colon) *colon = 0;
|
||||
if (*pkg && !strchr(pkg, '/')) {
|
||||
snprintf(path, sizeof path, "/sdcard/Android/data/%s/files/framebridge.conf", pkg);
|
||||
read_settings(path);
|
||||
}
|
||||
const char *env = getenv("FRAMEBRIDGE_CONFIG");
|
||||
if (env && *env) read_settings(env);
|
||||
}
|
||||
|
||||
// SHA-256 (FIPS 180-4), only run for modules whose size matches a fix
|
||||
static const uint32_t K[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
|
||||
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
|
||||
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
||||
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
|
||||
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
|
||||
|
||||
static void sha256_block(uint32_t h[8], const uint8_t *p) {
|
||||
uint32_t w[64];
|
||||
for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4 * i] << 24 | (uint32_t)p[4 * i + 1] << 16 | (uint32_t)p[4 * i + 2] << 8 | p[4 * i + 3];
|
||||
for (int i = 16; i < 64; i++) {
|
||||
uint32_t s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
uint32_t s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t t1 = hh + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i];
|
||||
uint32_t t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
|
||||
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
|
||||
static void sha256(const uint8_t *data, size_t len, uint8_t out[32]) {
|
||||
uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
size_t i = 0;
|
||||
for (; i + 64 <= len; i += 64) sha256_block(h, data + i);
|
||||
uint8_t tail[128] = {0};
|
||||
size_t rest = len - i;
|
||||
memcpy(tail, data + i, rest);
|
||||
tail[rest] = 0x80;
|
||||
size_t blocks = rest + 9 > 64 ? 2 : 1;
|
||||
uint64_t bits = (uint64_t)len * 8;
|
||||
for (int b = 0; b < 8; b++) tail[blocks * 64 - 1 - b] = (uint8_t)(bits >> (8 * b));
|
||||
for (size_t b = 0; b < blocks; b++) sha256_block(h, tail + 64 * b);
|
||||
for (int b = 0; b < 8; b++) {
|
||||
out[4 * b] = h[b] >> 24; out[4 * b + 1] = h[b] >> 16; out[4 * b + 2] = h[b] >> 8; out[4 * b + 3] = h[b];
|
||||
}
|
||||
}
|
||||
|
||||
// The fixed copy of `code` (caller frees) and its size, or NULL when no fix matches.
|
||||
static uint32_t *fixed_shader(const uint32_t *code, size_t size, size_t *out_size) {
|
||||
for (int i = 0; i < nfixes; i++) {
|
||||
if (fixes[i].size != size) continue;
|
||||
uint8_t digest[32];
|
||||
sha256((const uint8_t *)code, size, digest);
|
||||
if (memcmp(digest, fixes[i].sha, 32)) continue;
|
||||
size_t extra = (size_t)fixes[i].nwords * 4;
|
||||
uint32_t *copy = malloc(size + extra);
|
||||
if (!copy) return NULL;
|
||||
memcpy(copy, code, fixes[i].offset);
|
||||
memcpy((uint8_t *)copy + fixes[i].offset, fixes[i].words, extra);
|
||||
memcpy((uint8_t *)copy + fixes[i].offset + extra, (const uint8_t *)code + fixes[i].offset, size - fixes[i].offset);
|
||||
*out_size = size + extra;
|
||||
return copy;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void init(void) {
|
||||
read_all_settings();
|
||||
if (nfixes) LOG("vk shim: %d shader fix(es) configured", nfixes);
|
||||
if (query_slots > 1) LOG("vk shim: %d slots per occlusion query", query_slots);
|
||||
if (validation) LOG("vk shim: adding %s to the instance", VALIDATION_LAYER);
|
||||
if (spec_fixes) LOG("vk shim: Vulkan spec fixes on (depth images can be cleared, no depth resolve in shader-resolve "
|
||||
"subpasses)");
|
||||
real_vk = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (real_vk) {
|
||||
real_gipa = (PFN_vkGetInstanceProcAddr)dlsym(real_vk, "vkGetInstanceProcAddr");
|
||||
real_gdpa = (PFN_vkGetDeviceProcAddr)dlsym(real_vk, "vkGetDeviceProcAddr");
|
||||
real_rp2_trampoline = (PFN_vkCreateRenderPass2)dlsym(real_vk, "vkCreateRenderPass2");
|
||||
real_csm_trampoline = (PFN_vkCreateShaderModule)dlsym(real_vk, "vkCreateShaderModule");
|
||||
}
|
||||
LOG("vk shim: libvulkan.so %s", real_gipa && real_gdpa ? "OK" : "MISSING");
|
||||
}
|
||||
@@ -165,6 +348,8 @@ static const void *clean_chain(Arena *a, const void *head, int *fixes) {
|
||||
return first;
|
||||
}
|
||||
|
||||
static int resolves_logged;
|
||||
|
||||
static VkRenderPassCreateInfo2 clean_create_info(Arena *a, const VkRenderPassCreateInfo2 *ci, int *fixes) {
|
||||
VkRenderPassCreateInfo2 out = *ci;
|
||||
out.pNext = clean_chain(a, ci->pNext, fixes);
|
||||
@@ -189,6 +374,27 @@ static VkRenderPassCreateInfo2 clean_create_info(Arena *a, const VkRenderPassCre
|
||||
out.pSubpasses = sp;
|
||||
}
|
||||
}
|
||||
if (spec_fixes && out.pSubpasses) {
|
||||
VkSubpassDescription2 *sp = (VkSubpassDescription2 *)out.pSubpasses;
|
||||
for (uint32_t i = 0; i < ci->subpassCount; i++) {
|
||||
if (!(sp[i].flags & 0x8 /* VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM */) || !sp[i].pDepthStencilAttachment)
|
||||
continue;
|
||||
uint32_t att = sp[i].pDepthStencilAttachment->attachment;
|
||||
if (att == VK_ATTACHMENT_UNUSED || att >= ci->attachmentCount || !ci->pAttachments ||
|
||||
ci->pAttachments[att].samples != VK_SAMPLE_COUNT_1_BIT)
|
||||
continue;
|
||||
for (VkBaseOutStructure *n = (VkBaseOutStructure *)sp[i].pNext; n; n = n->pNext) {
|
||||
if (n->sType != VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE) continue;
|
||||
VkSubpassDescriptionDepthStencilResolve *r = (void *)n;
|
||||
if (r->pDepthStencilResolveAttachment &&
|
||||
r->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) {
|
||||
r->pDepthStencilResolveAttachment = NULL;
|
||||
(*fixes)++;
|
||||
if (resolves_logged++ < 5) LOG("vk shim: dropped the depth resolve of shader-resolve subpass %u", i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ci->pDependencies && ci->dependencyCount) {
|
||||
VkSubpassDependency2 *dep = arena_dup(a, ci->pDependencies, sizeof *dep * ci->dependencyCount);
|
||||
if (dep) {
|
||||
@@ -203,17 +409,29 @@ static VkRenderPassCreateInfo2 clean_create_info(Arena *a, const VkRenderPassCre
|
||||
// ---------------------------------------------------------------- entry points
|
||||
|
||||
#define MAX_DEVICES 8
|
||||
static struct { VkDevice device; PFN_vkCreateRenderPass2 rp2, rp2khr; } devices[MAX_DEVICES];
|
||||
enum { FN_RP2, FN_RP2KHR, FN_CSM, FN_CIMG, FN_CQP, FN_DQP, FN_BQ, FN_EQ, FN_CRQP, FN_RQP, FN_RQPEXT, FN_GQPR, FN_CCQPR, FN_COUNT };
|
||||
static const char *const FN_NAMES[FN_COUNT] = {
|
||||
"vkCreateRenderPass2", "vkCreateRenderPass2KHR", "vkCreateShaderModule", "vkCreateImage", "vkCreateQueryPool", "vkDestroyQueryPool",
|
||||
"vkCmdBeginQuery", "vkCmdEndQuery", "vkCmdResetQueryPool", "vkResetQueryPool", "vkResetQueryPoolEXT",
|
||||
"vkGetQueryPoolResults", "vkCmdCopyQueryPoolResults"};
|
||||
static struct { VkDevice device; PFN_vkVoidFunction fn[FN_COUNT]; } devices[MAX_DEVICES];
|
||||
static PFN_vkCreateRenderPass2 fallback_rp2khr; // from vkGetInstanceProcAddr
|
||||
static pthread_mutex_t dev_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static PFN_vkCreateRenderPass2 real_for(VkDevice device, int khr) {
|
||||
PFN_vkCreateRenderPass2 fn = NULL;
|
||||
// The next implementation of a wrapped device function: the one vkGetDeviceProcAddr returned for this device, else
|
||||
// a fresh lookup, else the loader's trampoline.
|
||||
static PFN_vkVoidFunction device_fn(VkDevice device, int which) {
|
||||
PFN_vkVoidFunction fn = NULL;
|
||||
pthread_mutex_lock(&dev_lock);
|
||||
for (int i = 0; i < MAX_DEVICES; i++)
|
||||
if (devices[i].device == device) { fn = khr ? devices[i].rp2khr : devices[i].rp2; break; }
|
||||
if (devices[i].device == device) { fn = devices[i].fn[which]; break; }
|
||||
pthread_mutex_unlock(&dev_lock);
|
||||
if (!fn && real_gdpa) fn = (PFN_vkCreateRenderPass2)real_gdpa(device, khr ? "vkCreateRenderPass2KHR" : "vkCreateRenderPass2");
|
||||
if (!fn && real_gdpa) fn = real_gdpa(device, FN_NAMES[which]);
|
||||
return fn;
|
||||
}
|
||||
|
||||
static PFN_vkCreateRenderPass2 real_for(VkDevice device, int khr) {
|
||||
PFN_vkCreateRenderPass2 fn = (PFN_vkCreateRenderPass2)device_fn(device, khr ? FN_RP2KHR : FN_RP2);
|
||||
if (!fn) fn = khr ? fallback_rp2khr : real_rp2_trampoline;
|
||||
return fn;
|
||||
}
|
||||
@@ -246,10 +464,270 @@ static VKAPI_ATTR VkResult VKAPI_CALL create_render_pass2_khr(VkDevice device, c
|
||||
return create_render_pass2(device, ci, alloc, rp, 1);
|
||||
}
|
||||
|
||||
static int fixes_applied;
|
||||
|
||||
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *ci,
|
||||
const VkAllocationCallbacks *alloc, VkShaderModule *module) {
|
||||
pthread_once(&once, init);
|
||||
PFN_vkCreateShaderModule real = (PFN_vkCreateShaderModule)device_fn(device, FN_CSM);
|
||||
if (!real) real = real_csm_trampoline;
|
||||
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
|
||||
size_t size = 0;
|
||||
uint32_t *code = nfixes && ci && ci->pCode ? fixed_shader(ci->pCode, ci->codeSize, &size) : NULL;
|
||||
if (!code) return real(device, ci, alloc, module);
|
||||
VkShaderModuleCreateInfo copy = *ci; // the caller's create info and code stay untouched
|
||||
copy.codeSize = size;
|
||||
copy.pCode = code;
|
||||
VkResult r = real(device, ©, alloc, module);
|
||||
free(code);
|
||||
if (fixes_applied++ < 20) LOG("vk shim: fixed shader module (%zu -> %zu bytes): %d", ci->codeSize, size, r);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- query slots
|
||||
|
||||
// Command buffer functions carry no VkDevice: their next implementation is the one the (single) game device got.
|
||||
static PFN_vkVoidFunction cmd_fn[FN_COUNT];
|
||||
static PFN_vkVoidFunction any_fn(VkDevice device, int which) {
|
||||
PFN_vkVoidFunction fn = device ? device_fn(device, which) : NULL;
|
||||
if (!fn) fn = cmd_fn[which];
|
||||
if (!fn && real_vk) fn = (PFN_vkVoidFunction)dlsym(real_vk, FN_NAMES[which]);
|
||||
return fn;
|
||||
}
|
||||
|
||||
#define MAX_POOLS 4096
|
||||
static uint64_t occlusion_pools[MAX_POOLS]; // open addressing; 0 = empty, 1 = deleted
|
||||
static pthread_mutex_t pool_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int pools_logged;
|
||||
|
||||
static unsigned pool_hash(uint64_t h) { return (unsigned)((h * 0x9E3779B97F4A7C15ull) >> 52) % MAX_POOLS; }
|
||||
|
||||
static void pool_add(VkQueryPool pool) {
|
||||
uint64_t h = (uint64_t)pool;
|
||||
pthread_mutex_lock(&pool_lock);
|
||||
for (unsigned i = pool_hash(h), n = 0; n < MAX_POOLS; i = (i + 1) % MAX_POOLS, n++)
|
||||
if (occlusion_pools[i] <= 1) { occlusion_pools[i] = h; break; }
|
||||
pthread_mutex_unlock(&pool_lock);
|
||||
}
|
||||
|
||||
static int pool_slot(VkQueryPool pool, int remove) {
|
||||
uint64_t h = (uint64_t)pool;
|
||||
if (h <= 1) return 0;
|
||||
int found = 0;
|
||||
pthread_mutex_lock(&pool_lock);
|
||||
for (unsigned i = pool_hash(h), n = 0; n < MAX_POOLS && occlusion_pools[i]; i = (i + 1) % MAX_POOLS, n++)
|
||||
if (occlusion_pools[i] == h) {
|
||||
found = 1;
|
||||
if (remove) occlusion_pools[i] = 1;
|
||||
break;
|
||||
}
|
||||
pthread_mutex_unlock(&pool_lock);
|
||||
return found;
|
||||
}
|
||||
|
||||
// the remapped first query of `pool` (unchanged for pools that aren't remapped)
|
||||
static uint32_t q(VkQueryPool pool, uint32_t query) { return pool_slot(pool, 0) ? query * (uint32_t)query_slots : query; }
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL create_query_pool(VkDevice device, const VkQueryPoolCreateInfo *ci,
|
||||
const VkAllocationCallbacks *alloc, VkQueryPool *pool) {
|
||||
PFN_vkCreateQueryPool real = (PFN_vkCreateQueryPool)any_fn(device, FN_CQP);
|
||||
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
|
||||
if (!ci || ci->queryType != VK_QUERY_TYPE_OCCLUSION || query_slots < 2) return real(device, ci, alloc, pool);
|
||||
VkQueryPoolCreateInfo copy = *ci;
|
||||
copy.queryCount = ci->queryCount * (uint32_t)query_slots;
|
||||
VkResult r = real(device, ©, alloc, pool);
|
||||
if (r == VK_SUCCESS) {
|
||||
pool_add(*pool);
|
||||
if (pools_logged++ < 5)
|
||||
LOG("vk shim: occlusion query pool %u -> %u slots", ci->queryCount, copy.queryCount);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL destroy_query_pool(VkDevice device, VkQueryPool pool, const VkAllocationCallbacks *alloc) {
|
||||
PFN_vkDestroyQueryPool real = (PFN_vkDestroyQueryPool)any_fn(device, FN_DQP);
|
||||
pool_slot(pool, 1);
|
||||
if (real) real(device, pool, alloc);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cmd_begin_query(VkCommandBuffer cb, VkQueryPool pool, uint32_t query,
|
||||
VkQueryControlFlags flags) {
|
||||
PFN_vkCmdBeginQuery real = (PFN_vkCmdBeginQuery)any_fn(NULL, FN_BQ);
|
||||
if (real) real(cb, pool, q(pool, query), flags);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cmd_end_query(VkCommandBuffer cb, VkQueryPool pool, uint32_t query) {
|
||||
PFN_vkCmdEndQuery real = (PFN_vkCmdEndQuery)any_fn(NULL, FN_EQ);
|
||||
if (real) real(cb, pool, q(pool, query));
|
||||
}
|
||||
|
||||
static uint32_t span(VkQueryPool pool, uint32_t count) { return pool_slot(pool, 0) ? count * (uint32_t)query_slots : count; }
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cmd_reset_query_pool(VkCommandBuffer cb, VkQueryPool pool, uint32_t first, uint32_t count) {
|
||||
PFN_vkCmdResetQueryPool real = (PFN_vkCmdResetQueryPool)any_fn(NULL, FN_CRQP);
|
||||
if (real) real(cb, pool, q(pool, first), span(pool, count));
|
||||
}
|
||||
|
||||
static void reset_query_pool(VkDevice device, VkQueryPool pool, uint32_t first, uint32_t count, int ext) {
|
||||
PFN_vkResetQueryPool real = (PFN_vkResetQueryPool)any_fn(device, ext ? FN_RQPEXT : FN_RQP);
|
||||
if (real) real(device, pool, q(pool, first), span(pool, count));
|
||||
}
|
||||
static VKAPI_ATTR void VKAPI_CALL host_reset_query_pool(VkDevice d, VkQueryPool p, uint32_t f, uint32_t c) { reset_query_pool(d, p, f, c, 0); }
|
||||
static VKAPI_ATTR void VKAPI_CALL host_reset_query_pool_ext(VkDevice d, VkQueryPool p, uint32_t f, uint32_t c) { reset_query_pool(d, p, f, c, 1); }
|
||||
|
||||
// Results come from slot N*i of each query, one query at a time: the extra slots are only written in multiview passes,
|
||||
// so reading them (with VK_QUERY_RESULT_WAIT_BIT) could wait forever.
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL get_query_pool_results(VkDevice device, VkQueryPool pool, uint32_t first, uint32_t count,
|
||||
size_t size, void *data, VkDeviceSize stride,
|
||||
VkQueryResultFlags flags) {
|
||||
PFN_vkGetQueryPoolResults real = (PFN_vkGetQueryPoolResults)any_fn(device, FN_GQPR);
|
||||
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
|
||||
if (!pool_slot(pool, 0) || !count) return real(device, pool, first, count, size, data, stride, flags);
|
||||
VkResult result = VK_SUCCESS;
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
size_t offset = (size_t)(i * stride);
|
||||
if (offset >= size) break;
|
||||
VkResult r = real(device, pool, (first + i) * (uint32_t)query_slots, 1, size - offset, (uint8_t *)data + offset,
|
||||
stride, flags);
|
||||
if (r < 0) return r;
|
||||
if (r == VK_NOT_READY) result = VK_NOT_READY;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cmd_copy_query_pool_results(VkCommandBuffer cb, VkQueryPool pool, uint32_t first,
|
||||
uint32_t count, VkBuffer buffer, VkDeviceSize offset,
|
||||
VkDeviceSize stride, VkQueryResultFlags flags) {
|
||||
PFN_vkCmdCopyQueryPoolResults real = (PFN_vkCmdCopyQueryPoolResults)any_fn(NULL, FN_CCQPR);
|
||||
if (!real) return;
|
||||
if (!pool_slot(pool, 0)) { real(cb, pool, first, count, buffer, offset, stride, flags); return; }
|
||||
for (uint32_t i = 0; i < count; i++)
|
||||
real(cb, pool, (first + i) * (uint32_t)query_slots, 1, buffer, offset + i * stride, stride, flags);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- spec fixes: depth images
|
||||
|
||||
static int is_depth_format(VkFormat f) {
|
||||
return f == VK_FORMAT_D16_UNORM || f == VK_FORMAT_X8_D24_UNORM_PACK32 || f == VK_FORMAT_D32_SFLOAT ||
|
||||
f == VK_FORMAT_S8_UINT || f == VK_FORMAT_D16_UNORM_S8_UINT || f == VK_FORMAT_D24_UNORM_S8_UINT ||
|
||||
f == VK_FORMAT_D32_SFLOAT_S8_UINT;
|
||||
}
|
||||
static int images_logged;
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice device, const VkImageCreateInfo *ci,
|
||||
const VkAllocationCallbacks *alloc, VkImage *image) {
|
||||
PFN_vkCreateImage real = (PFN_vkCreateImage)any_fn(device, FN_CIMG);
|
||||
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
|
||||
if (!spec_fixes || !ci || !is_depth_format(ci->format) || !(ci->usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ||
|
||||
(ci->usage & (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT))) // transient: no
|
||||
return real(device, ci, alloc, image);
|
||||
VkImageCreateInfo copy = *ci;
|
||||
copy.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
VkResult r = real(device, ©, alloc, image);
|
||||
if (images_logged++ < 5) LOG("vk shim: depth image %ux%u format %d can be cleared now: %d", ci->extent.width,
|
||||
ci->extent.height, ci->format, r);
|
||||
if (r != VK_SUCCESS) r = real(device, ci, alloc, image); // the flag isn't allowed here: as the game asked
|
||||
return r;
|
||||
}
|
||||
|
||||
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateImage(VkDevice d, const VkImageCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkImage *img) {
|
||||
pthread_once(&once, init);
|
||||
return create_image(d, ci, a, img);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- validation (diagnostics)
|
||||
|
||||
static PFN_vkCreateInstance real_ci;
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkInstance *inst) {
|
||||
if (!real_ci && real_vk) real_ci = (PFN_vkCreateInstance)dlsym(real_vk, "vkCreateInstance");
|
||||
if (!real_ci) return VK_ERROR_INITIALIZATION_FAILED;
|
||||
if (!validation || !ci) return real_ci(ci, a, inst);
|
||||
for (uint32_t i = 0; i < ci->enabledLayerCount; i++)
|
||||
if (!strcmp(ci->ppEnabledLayerNames[i], VALIDATION_LAYER)) return real_ci(ci, a, inst);
|
||||
const char **names = malloc(sizeof(char *) * (ci->enabledLayerCount + 1));
|
||||
if (!names) return real_ci(ci, a, inst);
|
||||
for (uint32_t i = 0; i < ci->enabledLayerCount; i++) names[i] = ci->ppEnabledLayerNames[i];
|
||||
names[ci->enabledLayerCount] = VALIDATION_LAYER;
|
||||
VkInstanceCreateInfo copy = *ci;
|
||||
copy.enabledLayerCount = ci->enabledLayerCount + 1;
|
||||
copy.ppEnabledLayerNames = names;
|
||||
VkResult r = real_ci(©, a, inst);
|
||||
LOG("vk shim: vkCreateInstance with %s: %d", VALIDATION_LAYER, r);
|
||||
if (r == VK_ERROR_LAYER_NOT_PRESENT) r = real_ci(ci, a, inst); // not bundled: start without it
|
||||
free(names);
|
||||
return r;
|
||||
}
|
||||
|
||||
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateInstance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkInstance *inst) {
|
||||
pthread_once(&once, init);
|
||||
return create_instance(ci, a, inst);
|
||||
}
|
||||
|
||||
// The same entry points for engines that dlsym them from the shim instead of asking vkGet*ProcAddr
|
||||
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateQueryPool(VkDevice d, const VkQueryPoolCreateInfo *ci,
|
||||
const VkAllocationCallbacks *a, VkQueryPool *p) {
|
||||
pthread_once(&once, init);
|
||||
return create_query_pool(d, ci, a, p);
|
||||
}
|
||||
EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyQueryPool(VkDevice d, VkQueryPool p, const VkAllocationCallbacks *a) {
|
||||
pthread_once(&once, init);
|
||||
destroy_query_pool(d, p, a);
|
||||
}
|
||||
EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdBeginQuery(VkCommandBuffer cb, VkQueryPool p, uint32_t i, VkQueryControlFlags f) {
|
||||
pthread_once(&once, init);
|
||||
cmd_begin_query(cb, p, i, f);
|
||||
}
|
||||
EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdEndQuery(VkCommandBuffer cb, VkQueryPool p, uint32_t i) {
|
||||
pthread_once(&once, init);
|
||||
cmd_end_query(cb, p, i);
|
||||
}
|
||||
EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdResetQueryPool(VkCommandBuffer cb, VkQueryPool p, uint32_t f, uint32_t c) {
|
||||
pthread_once(&once, init);
|
||||
cmd_reset_query_pool(cb, p, f, c);
|
||||
}
|
||||
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkGetQueryPoolResults(VkDevice d, VkQueryPool p, uint32_t f, uint32_t c, size_t s,
|
||||
void *data, VkDeviceSize st, VkQueryResultFlags fl) {
|
||||
pthread_once(&once, init);
|
||||
return get_query_pool_results(d, p, f, c, s, data, st, fl);
|
||||
}
|
||||
EXPORT VKAPI_ATTR void VKAPI_CALL vkCmdCopyQueryPoolResults(VkCommandBuffer cb, VkQueryPool p, uint32_t f, uint32_t c,
|
||||
VkBuffer b, VkDeviceSize o, VkDeviceSize st,
|
||||
VkQueryResultFlags fl) {
|
||||
pthread_once(&once, init);
|
||||
cmd_copy_query_pool_results(cb, p, f, c, b, o, st, fl);
|
||||
}
|
||||
|
||||
static int wrapped_index(const char *name) {
|
||||
for (int i = 0; i < FN_COUNT; i++)
|
||||
if (!strcmp(name, FN_NAMES[i])) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static PFN_vkVoidFunction wrap(const char *name) {
|
||||
if (!strcmp(name, "vkCreateRenderPass2")) return (PFN_vkVoidFunction)vkCreateRenderPass2;
|
||||
if (!strcmp(name, "vkCreateRenderPass2KHR")) return (PFN_vkVoidFunction)create_render_pass2_khr;
|
||||
return NULL;
|
||||
switch (wrapped_index(name)) {
|
||||
case FN_RP2: return (PFN_vkVoidFunction)vkCreateRenderPass2;
|
||||
case FN_RP2KHR: return (PFN_vkVoidFunction)create_render_pass2_khr;
|
||||
case FN_CSM: return nfixes ? (PFN_vkVoidFunction)vkCreateShaderModule : NULL; // nothing to fix: no detour
|
||||
case FN_CIMG: return spec_fixes ? (PFN_vkVoidFunction)create_image : NULL;
|
||||
default: break;
|
||||
}
|
||||
if (query_slots < 2) return NULL; // no query remapping: no detours
|
||||
switch (wrapped_index(name)) {
|
||||
case FN_CQP: return (PFN_vkVoidFunction)create_query_pool;
|
||||
case FN_DQP: return (PFN_vkVoidFunction)destroy_query_pool;
|
||||
case FN_BQ: return (PFN_vkVoidFunction)cmd_begin_query;
|
||||
case FN_EQ: return (PFN_vkVoidFunction)cmd_end_query;
|
||||
case FN_CRQP: return (PFN_vkVoidFunction)cmd_reset_query_pool;
|
||||
case FN_RQP: return (PFN_vkVoidFunction)host_reset_query_pool;
|
||||
case FN_RQPEXT: return (PFN_vkVoidFunction)host_reset_query_pool_ext;
|
||||
case FN_GQPR: return (PFN_vkVoidFunction)get_query_pool_results;
|
||||
case FN_CCQPR: return (PFN_vkVoidFunction)cmd_copy_query_pool_results;
|
||||
default: return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *name) {
|
||||
@@ -258,7 +736,7 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev
|
||||
PFN_vkVoidFunction fn = real_gdpa(device, name);
|
||||
PFN_vkVoidFunction w = fn ? wrap(name) : NULL;
|
||||
if (!w) return fn;
|
||||
int khr = name[strlen(name) - 1] == 'R';
|
||||
int which = wrapped_index(name);
|
||||
pthread_mutex_lock(&dev_lock);
|
||||
int slot = -1;
|
||||
for (int i = 0; i < MAX_DEVICES; i++) {
|
||||
@@ -267,8 +745,9 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev
|
||||
}
|
||||
if (slot >= 0) {
|
||||
devices[slot].device = device;
|
||||
if (khr) devices[slot].rp2khr = (PFN_vkCreateRenderPass2)fn; else devices[slot].rp2 = (PFN_vkCreateRenderPass2)fn;
|
||||
devices[slot].fn[which] = fn;
|
||||
}
|
||||
cmd_fn[which] = fn;
|
||||
pthread_mutex_unlock(&dev_lock);
|
||||
return w;
|
||||
}
|
||||
@@ -278,9 +757,12 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance
|
||||
if (!real_gipa || !name) return NULL;
|
||||
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
|
||||
if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)vkGetInstanceProcAddr;
|
||||
if (!strcmp(name, "vkCreateInstance") && validation) return (PFN_vkVoidFunction)vkCreateInstance;
|
||||
PFN_vkVoidFunction fn = real_gipa(instance, name);
|
||||
PFN_vkVoidFunction w = fn ? wrap(name) : NULL;
|
||||
if (!w) return fn;
|
||||
if (!strcmp(name, "vkCreateRenderPass2KHR")) fallback_rp2khr = (PFN_vkCreateRenderPass2)fn;
|
||||
int which = wrapped_index(name);
|
||||
if (which >= FN_CQP && !cmd_fn[which]) cmd_fn[which] = fn;
|
||||
return w;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
- **Windows:** unzip `FramePort-windows-x64.zip`, run `FramePort.exe` (warning → **More info → Run anyway**).
|
||||
- **macOS:** unzip `FramePort-macos-arm64.zip`, right-click `FramePort.app` → **Open**.
|
||||
- **Linux:** `tar xzf FramePort-linux-x64.tar.gz && ./FramePort/FramePort`.
|
||||
- **Linux:** `tar xzf FramePort-linux-x64.tar.gz && ./FramePort/FramePort` (ARM64: `FramePort-linux-arm64.tar.gz`).
|
||||
|
||||
Full guide: [docs/INSTALL.md](https://github.com/spoopyghosty0/frameport/blob/main/docs/INSTALL.md) · checksums in
|
||||
`SHA256SUMS.txt`.
|
||||
+4
-1
@@ -79,10 +79,13 @@ company = "FramePort"
|
||||
path = "src"
|
||||
module = "main"
|
||||
|
||||
[tool.flet.macos]
|
||||
entitlement."com.apple.security.files.user-selected.read-write" = true
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py311"
|
||||
extend-exclude = ["native", "src/frameport/_data"]
|
||||
extend-exclude = ["native", "src/frameport/_data", ".claude"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "W", "I", "B", "UP"]
|
||||
|
||||
@@ -21,7 +21,10 @@ from frameport.recommend.catalog import CatalogEntry, to_yaml # noqa: E402
|
||||
|
||||
PKG_RE = re.compile(r"^(rift\.[a-z0-9_]{1,80}|[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+){1,8})$")
|
||||
STATUSES = {"works", "issues", "unsupported", "unknown"}
|
||||
LIST_FIELDS = {"overport_extra", "overport_remove", "alt_overport", "frame", "frame_remove", "pcvr", "pcvr_remove"}
|
||||
LIST_FIELDS = {"overport_extra", "overport_remove", "alt_overport", "frame", "frame_remove", "pcvr", "pcvr_remove",
|
||||
"device"}
|
||||
# FramePort's own patch ids must exist (OVRPort's are listed by its CLI at runtime, so not checked here)
|
||||
OWN_PATCH_FIELDS = ("frame", "frame_remove", "pcvr", "pcvr_remove", "device")
|
||||
DICT_FIELDS = {"adapter", "device_files", "lepton_env", "proton_env", "verified"}
|
||||
ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,80}$")
|
||||
|
||||
@@ -64,6 +67,13 @@ def validate(d: dict) -> CatalogEntry:
|
||||
for k in LIST_FIELDS & set(d):
|
||||
if not isinstance(d[k], list) or not all(isinstance(x, str) and ID_RE.match(x) for x in d[k]):
|
||||
raise Invalid(f"{k} must be a list of patch ids")
|
||||
from frameport.patches import base
|
||||
|
||||
base.load_all()
|
||||
for k in OWN_PATCH_FIELDS:
|
||||
unknown_ids = [x for x in d.get(k) or [] if x not in base.REGISTRY]
|
||||
if unknown_ids:
|
||||
raise Invalid(f"{k}: unknown patch id(s) {', '.join(unknown_ids)}")
|
||||
for k in DICT_FIELDS & set(d):
|
||||
if not isinstance(d[k], dict):
|
||||
raise Invalid(f"{k} must be a mapping")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Write docs/GAMES.md: the tested games from the bundled catalog as a simple table to share.
|
||||
Run after catalog changes: python scripts/compat_list.py"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
|
||||
from frameport.recommend import catalog # noqa: E402
|
||||
|
||||
STATUS = {"works": "✅ Works", "issues": "⚠️ Works with issues", "unsupported": "❌ Doesn't run"}
|
||||
ORDER = {"works": 0, "issues": 1, "unsupported": 2}
|
||||
ISSUES = "https://github.com/spoopyghosty0/frameport/issues/new?template="
|
||||
SHARE, REPORT = ISSUES + "working-config.yml", ISSUES + "bug-report.yml"
|
||||
|
||||
|
||||
def short(note: str) -> str:
|
||||
"""The note's first sentence, without technical asides."""
|
||||
first = re.split(r"(?<=[.!?])\s", " ".join((note or "").split()), maxsplit=1)[0]
|
||||
return first if len(first) <= 160 else first[:157].rstrip() + "…"
|
||||
|
||||
|
||||
def render() -> str:
|
||||
# the repo's own recipes only (a local user catalog would replace or hide entries)
|
||||
bundled = catalog._load_dir(catalog.catalog_dir() / "games", "bundled")
|
||||
entries = [e for e in bundled.values() if e.status in STATUS]
|
||||
entries.sort(key=lambda e: (ORDER[e.status], e.title.lower()))
|
||||
rows = ["| Game | Platform | Status | Notes |", "|---|---|---|---|"]
|
||||
for e in entries:
|
||||
platform = "PC VR" if e.kind == "rift" else "Quest"
|
||||
note = "" if e.status == "works" else short(e.notes).replace("|", "/")
|
||||
rows.append(f"| {e.title} | {platform} | {STATUS[e.status]} | {note} |")
|
||||
return ("# Tested games\n\n"
|
||||
"Games tested on the Steam Frame with FramePort's recipes. Games not listed here may work too: FramePort "
|
||||
"suggests patches for them, and a working config can be shared from the app (**Share working config…**).\n"
|
||||
f"Tested a game? [Share a working config]({SHARE}) or [report a problem]({REPORT}) (in the app: the game's "
|
||||
"**…** menu does both and fills in the details).\n"
|
||||
"Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.\n\n"
|
||||
+ "\n".join(rows) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
out = ROOT / "docs" / "GAMES.md"
|
||||
out.write_text(render(), encoding="utf-8")
|
||||
print(f"wrote {out}")
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stamp a dev build's version into src/frameport/_version.py (CI only; never committed): the next patch release plus
|
||||
.dev<build number>, e.g. 0.9.0 -> 0.9.1.dev57. It sorts above the current release and below the next one, so
|
||||
testers on a dev build get the next release offered as a normal update.
|
||||
|
||||
python scripts/dev_version.py <build number> # prints the stamped version
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
VERSION_FILE = Path(__file__).resolve().parents[1] / "src/frameport/_version.py"
|
||||
|
||||
|
||||
def dev_version(current: str, build: int) -> str:
|
||||
base = re.match(r"(\d+)\.(\d+)\.(\d+)", current)
|
||||
if not base:
|
||||
raise ValueError(f"unexpected version {current!r}")
|
||||
major, minor, patch = (int(x) for x in base.groups())
|
||||
return f"{major}.{minor}.{patch + 1}.dev{int(build)}"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
text = VERSION_FILE.read_text(encoding="utf-8")
|
||||
current = re.search(r'__version__\s*=\s*"([^"]+)"', text).group(1)
|
||||
version = dev_version(current, int(sys.argv[1]))
|
||||
VERSION_FILE.write_text(text.replace(f'"{current}"', f'"{version}"', 1), encoding="utf-8")
|
||||
print(version)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -70,6 +70,8 @@ def main() -> int:
|
||||
# translations (data files PyInstaller doesn't pick up from the imports)
|
||||
"--add-data", f"{ROOT / 'src/frameport/locales'}{sep}frameport/locales",
|
||||
"--distpath", str(ROOT / "dist"), "--yes"]
|
||||
if TARGET == "linux":
|
||||
cmd.append("--onedir") # a folder: the bundle check sees the agent source, the archive the app
|
||||
else:
|
||||
# --yes: install the Flutter SDK etc. without prompting; --no-rich-output: plain logs (CI, Windows consoles)
|
||||
cmd = ["flet", "build", TARGET, str(ROOT), "--project", "FramePort", "--product", "FramePort",
|
||||
|
||||
+211
-4
@@ -3,6 +3,9 @@
|
||||
Chromium (Playwright). Any exception in a view shows up on stdout; screenshots land in --out.
|
||||
|
||||
FRAMEPORT_HOME=<a test data dir> python scripts/ui_smoke.py --out /tmp/shots [--game <package>]
|
||||
|
||||
--linux adds two pretend arm64 Linux apps (an AppImage and a VR folder app, tiny fake ELF files in FRAMEPORT_HOME)
|
||||
and renders their pages; with --fake-frame the AppImage is "installed" with a missing library.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -21,7 +24,7 @@ import flet as ft # noqa: E402
|
||||
from frameport.core import library # noqa: E402
|
||||
from frameport.ui.app import FramePortApp # noqa: E402
|
||||
|
||||
PORT = 8557
|
||||
PORT = int(os.environ.get("FRAMEPORT_SMOKE_PORT", "8557")) # two smoke runs at once need different ports
|
||||
ERRORS: list[str] = []
|
||||
|
||||
|
||||
@@ -44,12 +47,65 @@ class FakeFS:
|
||||
else:
|
||||
with open(os.path.join(base, n), "wb") as f:
|
||||
f.truncate(sizes.get(os.path.splitext(n)[1], 48_000)) # sparse: no real disk use
|
||||
self.shots = self._screenshots()
|
||||
|
||||
def _screenshots(self) -> list[dict]:
|
||||
"""Sample Steam screenshots for the Screenshots tab, two days, a few games + SteamVR: crops of the games' own
|
||||
store art (hero/landscape) when the library has some (docs screenshots), else colour gradients."""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from frameport.artwork import fetch
|
||||
|
||||
folder = os.path.join(self.home, "shots")
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
games = []
|
||||
for g in library.games():
|
||||
if g.get("kind") == "rift":
|
||||
continue
|
||||
# the store's own screenshots look like real captures; else hero/wide art
|
||||
shots_art = sorted(fetch.artwork_dir(g["package"]).glob("shot_*.jpg"))
|
||||
games.append((g, shots_art or [p for p in fetch.files(g["package"]) if p.stem in ("hero", "landscape")],
|
||||
bool(shots_art)))
|
||||
games.sort(key=lambda ga: (not ga[2], -len(ga[1])))
|
||||
owners = [(g["package"], g.get("title") or g["package"], arts) for g, arts, _real in games[:3]]
|
||||
spare = games[3][1] if len(games) > 3 else [] # SteamVR's own shots (taken outside a FramePort game)
|
||||
owners.append((None, "SteamVR", spare))
|
||||
now, shots = time.time(), []
|
||||
for i in range(10):
|
||||
t = now - i * 2400 - (86400 if i >= 6 else 0)
|
||||
name = time.strftime("%Y%m%d%H%M%S", time.localtime(t)) + "_1.jpg"
|
||||
path = os.path.join(folder, name)
|
||||
pkg, title, arts = owners[i % len(owners)]
|
||||
if arts: # a different crop of the game's art per shot, so they don't all look alike
|
||||
with Image.open(arts[i % len(arts)]) as src:
|
||||
src = src.convert("RGB")
|
||||
zoom = 1.0 + 0.15 * (i % 3) * (src.width < 2 * src.height)
|
||||
w, h = int(src.width / zoom), int(src.height / zoom)
|
||||
x, y = (src.width - w) * (i % 2), (src.height - h) // 2
|
||||
im = ImageOps.fit(src.crop((x, y, x + w, y + h)), (1280, 720))
|
||||
else:
|
||||
im = Image.linear_gradient("L").resize((640, 360)).convert("RGB")
|
||||
im = Image.merge("RGB", (im.getchannel(0).point(lambda v, i=i: (v + 40 * i) % 256),
|
||||
im.getchannel(1).point(lambda v: 255 - v), im.getchannel(2)))
|
||||
im.save(path, "JPEG", quality=85)
|
||||
shots.append({"path": path, "thumb": None, "time": int(t), "width": 1920, "height": 1080,
|
||||
"size": os.path.getsize(path), "account": "1", "appid": "250820", "package": pkg,
|
||||
"title": title})
|
||||
return shots
|
||||
|
||||
def agent(self, command, **args):
|
||||
if command == "storage_targets":
|
||||
return {"targets": [{"id": n.lower(), "path": os.path.join(self.home, n), "android": a, "shared": True}
|
||||
for n, a in (("Videos", "/sdcard/Movies"), ("Downloads", "/sdcard/Download"),
|
||||
("Documents", "/sdcard/Documents"))]}
|
||||
if command == "list_screenshots":
|
||||
want = args.get("package")
|
||||
shots = [s for s in self.shots if want is None or (s["package"] or "") == want]
|
||||
games = {}
|
||||
for s in self.shots:
|
||||
games.setdefault(s["package"] or "", {"package": s["package"], "title": s["title"], "count": 0})
|
||||
games[s["package"] or ""]["count"] += 1
|
||||
return {"shots": shots, "total": len(shots), "games": list(games.values())}
|
||||
raise RuntimeError(f"fake Frame: {command} not available")
|
||||
|
||||
@property
|
||||
@@ -67,6 +123,11 @@ class FakeFS:
|
||||
|
||||
def stat(self, path):
|
||||
return paramiko.SFTPAttributes.from_stat(os.stat(path))
|
||||
|
||||
def get(self, remote, local, callback=None):
|
||||
import shutil
|
||||
|
||||
shutil.copyfile(remote, local)
|
||||
return SFTP()
|
||||
|
||||
|
||||
@@ -86,6 +147,11 @@ class FakeTarget:
|
||||
self.games = [{"package": g["package"], "kind": "quest", "title": g.get("title"),
|
||||
"apk_size": (g.get("data_bytes") or 0) + 2**28, "sha256": g["build"]["sha256"],
|
||||
"recipe": {"patches": (g.get("recipe") or {}).get("patches", [])}} for g in works[:count]]
|
||||
# --linux: the AppImage is on the Frame, but SteamOS lacks one of its libraries
|
||||
self.games += [{"package": g["package"], "kind": "linux", "title": g.get("title"), "apk_size": 2**26,
|
||||
"apk_present": True, "recipe": None, "exe": g.get("exe"),
|
||||
"missing_libraries": ["libwebkit2gtk-4.1.so.0"]}
|
||||
for g in library.games() if g.get("kind") == "linux" and g["package"] == LINUX_APPIMAGE]
|
||||
|
||||
def describe(self) -> dict:
|
||||
return {"hostname": "steamframe", "os": "SteamOS", "os_version": "3.8", "build_id": "20260922",
|
||||
@@ -129,6 +195,36 @@ def open_type_dialog(app: FramePortApp) -> None:
|
||||
listener.on_key_down(SimpleNamespace(key="Enter"))
|
||||
|
||||
|
||||
LINUX_APPIMAGE = "linux.venera" # --linux's packages
|
||||
LINUX_FOLDER = "linux.matineevr"
|
||||
|
||||
|
||||
def _elf(machine: int = 183, appimage: bool = False, extra: bytes = b"") -> bytes:
|
||||
"""A minimal ELF header (183 = aarch64): enough for FramePort's Linux app detection."""
|
||||
head = bytearray(64)
|
||||
head[:4], head[4], head[5] = b"\x7fELF", 2, 1
|
||||
if appimage:
|
||||
head[8:11] = b"AI\x02"
|
||||
head[18:20] = machine.to_bytes(2, "little")
|
||||
return bytes(head) + extra
|
||||
|
||||
|
||||
def add_fake_linux_apps() -> None:
|
||||
"""--linux: an AppImage and a VR app folder (with a helper program, so "Change program…" shows) in the library."""
|
||||
from frameport import pipeline
|
||||
from frameport.core.paths import user_data_dir
|
||||
|
||||
base = user_data_dir() / "smoke-linux"
|
||||
app = base / "MatineeVR"
|
||||
(app / "lib").mkdir(parents=True, exist_ok=True)
|
||||
(base / "Venera-2.4.2-aarch64.AppImage").write_bytes(_elf(appimage=True, extra=b"\0" * 4096))
|
||||
(app / "MatineeVR").write_bytes(_elf(extra=b"\0" * 8192))
|
||||
(app / "crashpad_handler").write_bytes(_elf())
|
||||
(app / "lib" / "libopenxr_loader.so.1").write_bytes(_elf(extra=b"xrCreateInstance"))
|
||||
pipeline.add_linux_app(base / "Venera-2.4.2-aarch64.AppImage")
|
||||
pipeline.add_linux_app(app)
|
||||
|
||||
|
||||
STEP_SECONDS = 4 # per screen (the screenshot is taken ~3 s in)
|
||||
|
||||
|
||||
@@ -143,6 +239,35 @@ def driver(app: FramePortApp, steps: list[tuple[str, callable]], ready: threadin
|
||||
time.sleep(STEP_SECONDS)
|
||||
|
||||
|
||||
def find_button(root, text: str):
|
||||
"""The first button under `root` whose label is `text` (walks Flet's control tree)."""
|
||||
seen, stack = set(), [root]
|
||||
while stack:
|
||||
c = stack.pop()
|
||||
if c is None or id(c) in seen:
|
||||
continue
|
||||
seen.add(id(c))
|
||||
label = getattr(c, "content", None)
|
||||
if (label == text or getattr(c, "text", None) == text) and getattr(c, "on_click", None):
|
||||
return c
|
||||
for attr in ("controls", "content", "actions"):
|
||||
v = getattr(c, attr, None)
|
||||
if isinstance(v, list):
|
||||
stack.extend(v)
|
||||
elif v is not None and not isinstance(v, str):
|
||||
stack.append(v)
|
||||
return None
|
||||
|
||||
|
||||
def click_usb_setup(app) -> None:
|
||||
app.navigate(1)
|
||||
time.sleep(2)
|
||||
button = find_button(app.body, "Set up with a USB cable")
|
||||
print(f"usb button found: {button is not None}", flush=True)
|
||||
if button:
|
||||
button.on_click(None)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", type=Path, required=True)
|
||||
@@ -157,8 +282,15 @@ def main() -> int:
|
||||
ap.add_argument("--install-questions", nargs="+", metavar="PKG", default=None,
|
||||
help="open the install questions for these games, then click each dialog's main button twice "
|
||||
"(a double click must not duplicate dialogs); nothing is installed")
|
||||
ap.add_argument("--usb-setup", action="store_true", help="click 'Set up with a USB cable' on the connect page "
|
||||
"(a Frame cabled to this PC) and screenshot what follows")
|
||||
ap.add_argument("--docs", action="store_true", help="only the screens used in the docs (Library, --game, Frame)")
|
||||
ap.add_argument("--gestures", action="store_true", help="with --fake-frame: real mouse drags (drag-select) and "
|
||||
"right-clicks (menus) in Files, Screenshots and the Library; prints what got selected")
|
||||
ap.add_argument("--linux", action="store_true", help="add two pretend arm64 Linux apps and render their pages")
|
||||
args = ap.parse_args()
|
||||
if args.linux:
|
||||
add_fake_linux_apps()
|
||||
global STEP_SECONDS
|
||||
if args.hover:
|
||||
STEP_SECONDS = 7
|
||||
@@ -169,12 +301,14 @@ def main() -> int:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
game = args.game or (library.games()[0]["package"] if library.games() else None)
|
||||
steps = [("library", lambda a: a.navigate(0)), ("frame", lambda a: a.navigate(1)),
|
||||
("files", lambda a: a.go("files")), ("tools", lambda a: a.go("settings"))]
|
||||
("files", lambda a: a.go("files")), ("screenshots", lambda a: a.go("screenshots")),
|
||||
("live", lambda a: a.go("live")), ("tools", lambda a: a.go("settings"))]
|
||||
if game:
|
||||
steps.insert(1, ("game", lambda a: a.open_game(game)))
|
||||
steps.insert(2, ("game-customize", lambda a: a.open_game(game, advanced=True)))
|
||||
steps += [("share-dialog", lambda a: a.share_config_dialog(game)),
|
||||
("report-dialog", lambda a: (a.page.pop_dialog(), a.report_problem_dialog(game)))]
|
||||
("report-dialog", lambda a: (a.page.pop_dialog(), a.report_problem_dialog(game))),
|
||||
("custom-art-dialog", lambda a: (a.page.pop_dialog(), a.custom_artwork(game)))]
|
||||
# last: the right-click menu stays open over whatever comes next
|
||||
steps.append(("library-menu", lambda a: (a.page.pop_dialog(), a.navigate(0), time.sleep(3),
|
||||
a.library_view.open_menu(game))))
|
||||
@@ -187,7 +321,75 @@ def main() -> int:
|
||||
steps.append(("files", lambda a: a.go("files")))
|
||||
steps.append(("files-select", lambda a: [a.files_view._toggle(e.path, True)
|
||||
for e in a.files_view.entries[1:3]]))
|
||||
steps.append(("type-on-frame", open_type_dialog))
|
||||
steps.append(("screenshots", lambda a: a.go("screenshots")))
|
||||
steps.append(("screenshot-viewer", lambda a: a.screenshots_view.viewer(0)))
|
||||
steps.append(("type-on-frame", lambda a: (a.page.pop_dialog(), open_type_dialog(a))))
|
||||
steps.append(("power-confirm", lambda a: (a.page.pop_dialog(), a.frame_power("restart"))))
|
||||
mouse: dict[str, callable] = {} # step name -> mouse actions (Playwright page) after its screenshot
|
||||
if args.gestures:
|
||||
STEP_SECONDS = 14 # the mouse actions run after each step's screenshot, before the next step
|
||||
|
||||
def drag(*points):
|
||||
def run(page):
|
||||
page.mouse.move(*points[0])
|
||||
time.sleep(0.5)
|
||||
page.mouse.down()
|
||||
for pt in points[1:]:
|
||||
page.mouse.move(*pt, steps=25)
|
||||
time.sleep(0.4)
|
||||
page.mouse.up()
|
||||
return run
|
||||
|
||||
def right_click(x, y):
|
||||
return lambda page: (page.mouse.move(x, y), time.sleep(0.5), page.mouse.click(x, y, button="right"))
|
||||
|
||||
def report(label, view, extra=""):
|
||||
def run(a):
|
||||
v = getattr(a, view)
|
||||
print(f"GESTURE {label}: selected={sorted(v.selected)} {extra and eval(extra)}", flush=True)
|
||||
return run
|
||||
|
||||
def escape(page):
|
||||
page.keyboard.press("Escape")
|
||||
steps = [("files", lambda a: a.go("files")),
|
||||
("files-dragged", report("files drag", "files_view")),
|
||||
("files-menu", lambda a: None),
|
||||
("files-space-menu", lambda a: None),
|
||||
("screenshots", lambda a: a.go("screenshots")),
|
||||
("screenshots-dragged", report("screenshots drag", "screenshots_view")),
|
||||
("screenshots-menu", lambda a: None),
|
||||
("library", lambda a: a.navigate(0)),
|
||||
("library-dragged", report("library drag", "library_view", "a.library_view.select_mode")),
|
||||
("library-undrag", report("library drag back", "library_view"))]
|
||||
mouse = {"files": drag((900, 268), (900, 320), (900, 372)), # the folder + 2 files
|
||||
"files-dragged": right_click(900, 320), # a selected one: "… 3 items"
|
||||
"files-menu": lambda page: (escape(page), time.sleep(0.5), right_click(900, 600)(page)),
|
||||
"files-space-menu": escape,
|
||||
"screenshots": drag((680, 280), (950, 280), (950, 430)), # 3 shots
|
||||
"screenshots-dragged": right_click(950, 430),
|
||||
"screenshots-menu": escape,
|
||||
"library": drag((360, 300), (560, 300), (760, 300)), # 3 cards, select mode on
|
||||
"library-dragged": drag((560, 300), (760, 300))} # from a selected card: deselects 2
|
||||
if args.linux:
|
||||
def linux_filter(a, value):
|
||||
a.navigate(0)
|
||||
time.sleep(2)
|
||||
a.library_view._set("platform", value)
|
||||
steps = [("library", lambda a: a.navigate(0)), ("library-linux", lambda a: linux_filter(a, "linux")),
|
||||
("linux-appimage", lambda a: (a.library_view._set("platform", "all"), a.open_game(LINUX_APPIMAGE))),
|
||||
("linux-folder", lambda a: a.open_game(LINUX_FOLDER)),
|
||||
("linux-folder-customize", lambda a: a.open_game(LINUX_FOLDER, advanced=True)),
|
||||
("linux-change-program", lambda a: a.choose_exe(LINUX_FOLDER)),
|
||||
("frame", lambda a: (a.page.pop_dialog(), a.navigate(1))),
|
||||
("linux-menu", lambda a: (a.navigate(0), time.sleep(3), a.library_view.open_menu(LINUX_APPIMAGE)))]
|
||||
if args.usb_setup:
|
||||
def continue_usb(a):
|
||||
dialog = [d for d in a.page._dialogs.controls if d.open and type(d).__name__ == "AlertDialog"][-1]
|
||||
button = find_button(dialog, "Done: look for the cable") or dialog.actions[-1] # (label inside a Row)
|
||||
print(f"dialog button found: {button is not None}", flush=True)
|
||||
button.on_click(None)
|
||||
steps = [("usb-explain", click_usb_setup), ("usb-continue", continue_usb),
|
||||
("usb-wait", lambda a: time.sleep(8)), ("usb-after", lambda a: time.sleep(10))]
|
||||
if args.install_questions:
|
||||
queued: list[str] = []
|
||||
|
||||
@@ -279,6 +481,11 @@ def main() -> int:
|
||||
time.sleep(1.5)
|
||||
page.screenshot(path=str(args.out / f"{shot:02d}-{name}.png"))
|
||||
shot += 1
|
||||
if name in mouse:
|
||||
mouse[name](page)
|
||||
time.sleep(2)
|
||||
page.screenshot(path=str(args.out / f"{shot:02d}-{name}-mouse.png"))
|
||||
shot += 1
|
||||
browser.close()
|
||||
except Exception: # noqa: BLE001
|
||||
ERRORS.append("browser: " + traceback.format_exc())
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
# ruff: noqa: E501 (the shell snippet for the Frame keeps its lines whole)
|
||||
"""Autonomous USB-cable test (Frame cabled to this PC): everything needed to decide on a "Connect with a USB cable"
|
||||
setup option, in one run, without touching the headset. Writes a Markdown report.
|
||||
|
||||
uv run python scripts/usb_autotest.py --out <report.md> [--no-speed]
|
||||
|
||||
Checks: Windows (via powershell.exe from WSL, or directly): new network adapters, Valve USB devices (VID 28DE), the
|
||||
driver Windows bound and the USB class codes (NCM 02/0D, ECM 02/06, RNDIS E0 or EF/04); the adapter's IPv4 and
|
||||
network category; Frame side (over the normal connection): agent `usb_link`, the systemd units / NetworkManager
|
||||
connection behind usb0 (does it depend on Developer Mode?); Frame -> PC over the cable (the setup direction: a
|
||||
temporary listener on a pairing port); PC -> Frame SSH over the cable (same host key); upload speed USB vs normal.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
PS_PATHS = ("/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", "powershell.exe", "powershell")
|
||||
LISTEN_PORT = 8766 # in FramePort's pairing range (8765-8767)
|
||||
|
||||
|
||||
def powershell() -> str | None:
|
||||
for p in PS_PATHS:
|
||||
if os.path.exists(p) or shutil.which(p):
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def ps(script: str, timeout: int = 60) -> str:
|
||||
exe = powershell()
|
||||
if not exe:
|
||||
return "(no PowerShell)"
|
||||
env = {k: v for k, v in os.environ.items() if k != "PSModulePath"}
|
||||
try:
|
||||
p = subprocess.run([exe, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True,
|
||||
text=True, timeout=timeout, env=env)
|
||||
return (p.stdout + p.stderr).replace("\r", "").strip()
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
return f"(powershell failed: {exc})"
|
||||
|
||||
|
||||
WINDOWS = r"""
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
'== adapters'
|
||||
Get-NetAdapter -IncludeHidden | Select-Object Name,InterfaceDescription,Status,LinkSpeed,MacAddress |
|
||||
Format-Table -AutoSize | Out-String -Width 250
|
||||
'== Valve USB devices (VID 28DE)'
|
||||
Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match 'VID_28DE' } | ForEach-Object {
|
||||
$d = $_
|
||||
$compat = (Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_CompatibleIds').Data -join ' '
|
||||
$svc = (Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_Service').Data
|
||||
$drv = (Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_DriverDesc').Data
|
||||
"{0} | {1} | status={2} | class={3} | service={4} | driver={5} | compat={6}" -f $d.FriendlyName, $d.InstanceId,
|
||||
$d.Status, $d.Class, $svc, $drv, $compat
|
||||
}
|
||||
'== problem devices'
|
||||
Get-PnpDevice -PresentOnly | Where-Object { $_.Status -ne 'OK' -and $_.InstanceId -match 'USB' } |
|
||||
Select-Object FriendlyName,Status,InstanceId | Format-Table -AutoSize | Out-String -Width 250
|
||||
'== IPv4 on 10.86.200.*'
|
||||
Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -like '10.86.200.*' } |
|
||||
Select-Object InterfaceAlias,IPAddress,PrefixLength,PrefixOrigin | Format-Table | Out-String
|
||||
'== network profiles'
|
||||
Get-NetConnectionProfile | Select-Object InterfaceAlias,NetworkCategory | Format-Table | Out-String
|
||||
'== SSH to the Frame over the cable (from Windows)'
|
||||
(Test-NetConnection 10.86.200.233 -Port 22 -WarningAction SilentlyContinue).TcpTestSucceeded
|
||||
'== FramePort firewall rules'
|
||||
Get-NetFirewallRule -DisplayName '*FramePort*' | Select-Object DisplayName,Enabled,Profile,Direction |
|
||||
Format-Table | Out-String
|
||||
"""
|
||||
|
||||
FRAME_UNITS = r"""
|
||||
echo "== units mentioning usb/gadget"; systemctl list-units --all --no-pager 2>/dev/null | grep -i -E 'gadget|usb' | head -20
|
||||
for u in $(systemctl list-unit-files --no-pager 2>/dev/null | grep -i -E 'gadget|usb' | awk '{print $1}' | head -8); do
|
||||
echo "== $u"; systemctl cat "$u" --no-pager 2>/dev/null | grep -v '^#' | grep -v '^$' | head -30; done
|
||||
echo "== NetworkManager usb0"; nmcli -f GENERAL.CONNECTION,IP4.ADDRESS device show usb0 2>/dev/null
|
||||
c=$(nmcli -g GENERAL.CONNECTION device show usb0 2>/dev/null); [ -n "$c" ] && nmcli -f ipv4.method,ipv4.addresses,connection.autoconnect connection show "$c" 2>/dev/null
|
||||
echo "== configfs"; ls -la /sys/kernel/config/usb_gadget/ 2>&1 | head; ls /sys/kernel/config/usb_gadget/*/functions/ 2>&1 | head
|
||||
echo "== udc"; for u in /sys/class/udc/*; do echo "$u $(cat $u/current_speed 2>/dev/null) $(cat $u/state 2>/dev/null)"; done
|
||||
echo "== devkit"; ls -la /etc/steamos-devkit-enabled 2>&1
|
||||
"""
|
||||
|
||||
|
||||
def frame_to_pc(frame, pc_ips: list[str]) -> list[str]:
|
||||
"""Can the Frame open a TCP connection to this PC over the cable (what the setup step needs)?"""
|
||||
lines, got = [], []
|
||||
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
srv.bind(("0.0.0.0", LISTEN_PORT))
|
||||
except OSError as exc:
|
||||
return [f"couldn't listen on {LISTEN_PORT}: {exc}"]
|
||||
srv.listen(4)
|
||||
srv.settimeout(1)
|
||||
|
||||
def accept():
|
||||
end = time.time() + 20
|
||||
while time.time() < end:
|
||||
try:
|
||||
conn, addr = srv.accept()
|
||||
got.append(addr[0])
|
||||
conn.sendall(b"HTTP/1.0 200 OK\r\n\r\nframeport-usb-ok\n")
|
||||
conn.close()
|
||||
except OSError:
|
||||
continue
|
||||
t = threading.Thread(target=accept, daemon=True)
|
||||
t.start()
|
||||
for ip in pc_ips:
|
||||
code, out, err = frame.run(f"curl -s --max-time 6 http://{ip}:{LISTEN_PORT}/ping || echo FAILED", timeout=20)
|
||||
lines.append(f"Frame -> {ip}:{LISTEN_PORT}: {(out or err).strip()[:80]}")
|
||||
t.join(timeout=22)
|
||||
srv.close()
|
||||
lines.append(f"connections seen from: {got or 'none'}")
|
||||
return lines
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", type=Path, default=Path("usb-autotest.md"))
|
||||
ap.add_argument("--no-speed", action="store_true")
|
||||
args = ap.parse_args()
|
||||
from frameport.frame import usb
|
||||
from frameport.frame.connection import saved_targets
|
||||
from frameport.targets.frame_lepton import FrameLeptonTarget
|
||||
|
||||
report = [f"# USB cable autotest {time.strftime('%Y-%m-%d %H:%M')}", ""]
|
||||
|
||||
def section(title, text):
|
||||
report.extend([f"## {title}", "```", text.strip() or "(nothing)", "```", ""])
|
||||
print(f"--- {title}\n{text.strip()[:3000]}\n", flush=True)
|
||||
|
||||
section("Windows", ps(WINDOWS, timeout=120))
|
||||
wsl = subprocess.run(["ip", "-4", "-o", "addr", "show"], capture_output=True, text=True).stdout
|
||||
section("This side (WSL/Linux) IPv4", wsl)
|
||||
frame = FrameLeptonTarget(saved_targets()[0], None).connect().frame
|
||||
section("Frame units / NetworkManager / configfs", frame.run(FRAME_UNITS, timeout=60)[1])
|
||||
result = usb.check(frame, measure=not args.no_speed)
|
||||
section("frameport frame usb-check", json.dumps(result, indent=1, default=str))
|
||||
ips = result.get("pc_addresses") or []
|
||||
section("Frame -> PC over the cable (setup direction)", "\n".join(frame_to_pc(frame, ips)) if ips else
|
||||
"skipped: this side has no address on the Frame's USB network")
|
||||
args.out.write_text("\n".join(report), encoding="utf-8")
|
||||
print(f"report: {args.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,2 +1,2 @@
|
||||
# The FramePort version: the single source (pyproject reads it via hatch; CI checks a release tag matches it).
|
||||
__version__ = "0.6.0"
|
||||
__version__ = "0.10.0"
|
||||
@@ -93,6 +93,9 @@ def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Ana
|
||||
abi = next((a for a in ("arm64-v8a", "armeabi-v7a") if a in abis), None)
|
||||
prefix = f"lib/{abi}/" if abi else None
|
||||
libs = sorted(n[len(prefix):] for n in names if prefix and n.startswith(prefix) and n.endswith(".so"))
|
||||
# SDL's Java side (SDL2 / LÖVE apps): crashes in Lepton without a clipboard service (frame.sdl_clipboard)
|
||||
sdl_java = any(b"Lorg/libsdl/app/SDLClipboardHandler;" in z.read(n) for n in names
|
||||
if n.startswith("classes") and n.endswith(".dex"))
|
||||
manifest = z.read("AndroidManifest.xml")
|
||||
lib_bytes = {}
|
||||
if deep and prefix:
|
||||
@@ -193,6 +196,14 @@ def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Ana
|
||||
"split_apk": bool({"isSplitRequired", "requiredSplitTypes"} & set(manifest_strings)),
|
||||
# Unity (IL2CPP) text fields: they close at once on the Frame (frame.unity_text_input)
|
||||
"text_fields": unity_text_fields(il2cpp_meta) if il2cpp_meta else [],
|
||||
# Meta's OVRManager raises MSAA at runtime (frame.unity_runtime_msaa_off); Oculus XR Plugin (multiview)
|
||||
"ovr_runtime_msaa": bool(il2cpp_meta) and b"\0useRecommendedMSAALevel\0" in il2cpp_meta,
|
||||
"sdl_java": sdl_java,
|
||||
"oculus_xr_plugin": bool(il2cpp_meta) and b"\0m_StereoRenderingModeAndroid\0" in il2cpp_meta,
|
||||
# Unity's built-in Oculus support checks for Meta's system apps before VR (frame.unity_oculus_check)
|
||||
"unity_oculus_check": b"\0com.oculus.systemactivities\0" in lib_bytes.get("libunity.so", b""),
|
||||
# a 2D launcher activity that starts a separate VR activity (frame.start_activity)
|
||||
"vr_activity": axml.vr_activity(manifest),
|
||||
"unity_version": unity_version(ggm, lib_bytes.get("libunity.so")) if engine == "Unity" else None,
|
||||
},
|
||||
)
|
||||
@@ -238,7 +249,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()
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
in its "diffable C#" output with the attribute injector). Offset is the method's position in the libil2cpp.so FILE
|
||||
(not the virtual address: those differ, e.g. by 0x4000 in Stremio VR's library), which is what a byte patch needs.
|
||||
|
||||
Results are cached per libil2cpp.so (sha256), so a rebuild of the same game doesn't run Cpp2IL again."""
|
||||
Results are cached per game build (its global-metadata.dat), so a rebuild of the same game doesn't run Cpp2IL again,
|
||||
and neither does the next patch of the same build (an earlier one has already changed libil2cpp.so's bytes, never its
|
||||
layout)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
@@ -18,9 +20,15 @@ _ADDRESS = re.compile(r'Offset = "0x([0-9A-Fa-f]+)", Length = "0x([0-9A-Fa-f]+)"
|
||||
|
||||
|
||||
def parse_methods(cs_text: str, names: list[str]) -> dict[str, tuple[int, int]]:
|
||||
"""{method name: (file offset, length)} for the named methods of one Cpp2IL diffable-C# class file."""
|
||||
"""{method name: (file offset, length)} for the named methods of one Cpp2IL diffable-C# class file. A name
|
||||
"field:<f>" gives the instance field's offset instead: (offset, 0)."""
|
||||
lines = cs_text.splitlines()
|
||||
found: dict[str, tuple[int, int]] = {}
|
||||
for name in [n for n in names if n.startswith("field:")]:
|
||||
m = re.search(rf"\s{re.escape(name[6:])};\s*//Field offset: 0x([0-9A-Fa-f]+)", cs_text)
|
||||
if m:
|
||||
found[name] = (int(m.group(1), 16), 0)
|
||||
names = [n for n in names if not n.startswith("field:")]
|
||||
for i, line in enumerate(lines):
|
||||
for name in names:
|
||||
if name in found or not re.search(rf"\s{re.escape(name)}\s*\(", line) or "Token" in line:
|
||||
@@ -33,14 +41,22 @@ def parse_methods(cs_text: str, names: list[str]) -> dict[str, tuple[int, int]]:
|
||||
return found
|
||||
|
||||
|
||||
def _last_error(output: str) -> str:
|
||||
"""The exception line of Cpp2IL's output (its stack trace isn't useful to a user)."""
|
||||
lines = [ln.strip() for ln in output.splitlines() if ln.strip()]
|
||||
msg = next((ln for ln in reversed(lines) if "Exception" in ln and not ln.startswith("at ")), None)
|
||||
return (msg or (lines[-1] if lines else "no output"))[:300]
|
||||
|
||||
|
||||
def _plain_version(version: str) -> str:
|
||||
"""6000.2.7f2 -> 6000.2.7 (what Cpp2IL's --force-unity-version takes)."""
|
||||
m = re.match(r"\d+\.\d+\.\d+", version)
|
||||
return m.group(0) if m else version
|
||||
|
||||
|
||||
def _cache_file(lib: bytes) -> Path:
|
||||
return cache_dir() / "il2cpp" / (hashlib.sha256(lib).hexdigest()[:32] + ".json")
|
||||
def _cache_file(lib: bytes, metadata: bytes) -> Path:
|
||||
key = hashlib.sha256(metadata + len(lib).to_bytes(8, "little")).hexdigest()[:32]
|
||||
return cache_dir() / "il2cpp" / (key + ".json")
|
||||
|
||||
|
||||
def find_methods(lib: bytes, metadata: bytes, unity_version: str, wanted: dict[str, list[str]],
|
||||
@@ -48,9 +64,11 @@ def find_methods(lib: bytes, metadata: bytes, unity_version: str, wanted: dict[s
|
||||
"""wanted: {class file (relative to Cpp2IL's DiffableCs folder, e.g. "Unity.TextMeshPro/TMPro/TMP_InputField.cs"):
|
||||
[method names]} -> {class file: {method: (file offset, length)}}; classes or methods not in the game are left
|
||||
out."""
|
||||
cache_file = _cache_file(lib)
|
||||
cache_file = _cache_file(lib, metadata)
|
||||
try:
|
||||
cached = json.loads(cache_file.read_text())
|
||||
if cached.get("error"): # Cpp2IL can't read this build (e.g. an old Unity): don't run it again per patch
|
||||
raise RuntimeError(cached["error"])
|
||||
if all(cls in cached.get("classes", {}) or cls in cached.get("missing", []) for cls in wanted):
|
||||
return {cls: {m: tuple(v) for m, v in cached["classes"][cls].items() if m in names}
|
||||
for cls, names in wanted.items() if cls in cached.get("classes", {})}
|
||||
@@ -72,7 +90,10 @@ def find_methods(lib: bytes, metadata: bytes, unity_version: str, wanted: dict[s
|
||||
timeout=timeout, cwd=tmp)
|
||||
root = t / "out" / "DiffableCs"
|
||||
if not root.is_dir():
|
||||
raise RuntimeError("Cpp2IL couldn't read this game's code: " + (proc.stdout + proc.stderr)[-400:].strip())
|
||||
error = "Cpp2IL couldn't read this game's code: " + _last_error(proc.stdout + proc.stderr)
|
||||
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
cache_file.write_text(json.dumps({"unity_version": unity_version, "error": error}))
|
||||
raise RuntimeError(error)
|
||||
out, missing = {}, []
|
||||
for cls, names in wanted.items():
|
||||
f = root / cls
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Native arm64 Linux apps for the Frame (GitHub #31): an AppImage, a folder, or a .zip/.tar.* archive with an
|
||||
aarch64 program. Finds the program to start, checks the CPU architecture (x86_64 builds can't run natively) and
|
||||
whether it's an OpenXR (VR) app. Archives are unpacked once into FramePort's data folder, so installs upload a
|
||||
plain folder like PC VR games do."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import shutil
|
||||
import tarfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from ..core.paths import user_data_dir
|
||||
|
||||
EM_AARCH64, EM_X86_64 = 183, 62
|
||||
ARCHIVES = (".zip", ".tar.gz", ".tgz", ".tar.xz", ".txz", ".tar.bz2", ".tar")
|
||||
OPENXR_MARKERS = (b"libopenxr_loader.so", b"xrCreateInstance")
|
||||
MAX_SCAN = 256 << 20 # don't read huge files looking for OpenXR markers
|
||||
|
||||
|
||||
def elf_machine(path: Path) -> int | None:
|
||||
"""e_machine of an ELF file (183 = aarch64, 62 = x86_64), None if it isn't ELF."""
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(20)
|
||||
except OSError:
|
||||
return None
|
||||
if head[:4] != b"\x7fELF" or len(head) < 20:
|
||||
return None
|
||||
return int.from_bytes(head[18:20], "little" if head[5] == 1 else "big")
|
||||
|
||||
|
||||
def is_appimage(path: Path) -> bool:
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(11)
|
||||
except OSError:
|
||||
return False
|
||||
return head[:4] == b"\x7fELF" and head[8:11] == b"AI\x02"
|
||||
|
||||
|
||||
def is_archive(path: Path) -> bool:
|
||||
return path.is_file() and path.name.lower().endswith(ARCHIVES)
|
||||
|
||||
|
||||
def looks_like_linux_app(path: Path) -> bool:
|
||||
"""For the file picker / drag-and-drop: something this module can add."""
|
||||
path = Path(path)
|
||||
return path.is_dir() or is_archive(path) or is_appimage(path) or elf_machine(path) is not None
|
||||
|
||||
|
||||
def slug(name: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")[:48] or "app"
|
||||
|
||||
|
||||
def clean_title(name: str) -> str:
|
||||
"""'Venera-Prime-2.4.2-aarch64.AppImage' -> 'Venera Prime'."""
|
||||
stem = re.sub(r"(\.AppImage|\.tar\.\w+|\.tgz|\.txz|\.zip)$", "", name, flags=re.I)
|
||||
stem = re.split(r"[-_ .]v?\d+(\.\d+)+", stem, maxsplit=1)[0]
|
||||
stem = re.sub(r"[-_ .](linux|aarch64|arm64|x86_64|amd64)\b.*$", "", stem, flags=re.I)
|
||||
return re.sub(r"[-_.]+", " ", stem).strip() or name
|
||||
|
||||
|
||||
def unpack(archive: Path) -> Path:
|
||||
"""Unpack an archive into <data>/linux-apps/<slug>-<hash>/ (once per archive version)."""
|
||||
st = archive.stat()
|
||||
key = hashlib.sha1(f"{archive.resolve()}:{st.st_size}:{st.st_mtime_ns}".encode()).hexdigest()[:8]
|
||||
dest = user_data_dir() / "linux-apps" / f"{slug(clean_title(archive.name))}-{key}"
|
||||
done = dest / ".unpacked"
|
||||
if done.exists():
|
||||
return dest
|
||||
shutil.rmtree(dest, ignore_errors=True)
|
||||
dest.mkdir(parents=True)
|
||||
if archive.name.lower().endswith(".zip"):
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
for info in z.infolist():
|
||||
target = (dest / info.filename).resolve()
|
||||
if not str(target).startswith(str(dest.resolve())):
|
||||
raise ValueError(f"unsafe path in archive: {info.filename}")
|
||||
z.extractall(dest)
|
||||
else:
|
||||
with tarfile.open(archive) as t:
|
||||
t.extractall(dest, filter="data")
|
||||
done.write_text(archive.name, encoding="utf-8")
|
||||
return dest
|
||||
|
||||
|
||||
def _desktop_exec(root: Path) -> str | None:
|
||||
for desktop in sorted(root.rglob("*.desktop"))[:5]:
|
||||
m = re.search(r"^Exec=(\S+)", desktop.read_text(encoding="utf-8", errors="replace"), re.M)
|
||||
if m:
|
||||
return Path(m.group(1).strip('"')).name
|
||||
return None
|
||||
|
||||
|
||||
def _desktop_name(root: Path) -> str | None:
|
||||
for desktop in sorted(root.rglob("*.desktop"))[:5]:
|
||||
m = re.search(r"^Name=(.+)$", desktop.read_text(encoding="utf-8", errors="replace"), re.M)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
return None
|
||||
|
||||
|
||||
def rank_programs(root: Path) -> list[tuple[Path, int]]:
|
||||
"""(ELF program, machine) candidates, best first: the .desktop Exec= name, then a name like the folder's, then
|
||||
shallow and big ones. Libraries (*.so*) are never programs."""
|
||||
wanted = _desktop_exec(root)
|
||||
folder = slug(root.name.split("-")[0])
|
||||
found = []
|
||||
for p in root.rglob("*"):
|
||||
if not p.is_file() or ".so" in p.name or p.suffix in (".py", ".pyc", ".txt", ".json"):
|
||||
continue
|
||||
machine = elf_machine(p)
|
||||
if machine is None:
|
||||
continue
|
||||
rel_depth = len(p.relative_to(root).parts)
|
||||
score = (100 if wanted and p.name == wanted else 0) + (30 if slug(p.stem) and slug(p.stem) in folder else 0) \
|
||||
+ (20 if folder and folder in slug(p.stem) else 0) - 5 * rel_depth
|
||||
found.append((score, p.stat().st_size, p, machine))
|
||||
found.sort(key=lambda t: (-t[0], -t[1]))
|
||||
return [(p, m) for _s, _size, p, m in found]
|
||||
|
||||
|
||||
def app_libraries(root: Path, exe: Path) -> list[Path]:
|
||||
"""Libraries the program loads: next to it, in a lib*/ folder beside it, or the app's usr/lib*. Libraries deep
|
||||
in data folders don't count (FramePort's own build ships FrameBridge's OpenXR loader as data and isn't VR)."""
|
||||
dirs = {exe.parent}
|
||||
for base in (exe.parent, root, root / "usr"):
|
||||
dirs.update(d for d in base.glob("lib*") if d.is_dir())
|
||||
out = []
|
||||
for d in dirs:
|
||||
out += [p for p in d.glob("*.so*") if p.is_file()]
|
||||
return sorted(out)[:200]
|
||||
|
||||
|
||||
def uses_openxr(paths: list[Path]) -> bool:
|
||||
for p in paths:
|
||||
try:
|
||||
if p.stat().st_size > MAX_SCAN:
|
||||
continue
|
||||
data = p.read_bytes()
|
||||
except OSError:
|
||||
continue
|
||||
if any(m in data for m in OPENXR_MARKERS):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def inspect(path: Path) -> dict:
|
||||
"""{root, exe (relative to root), appimage, machine, arch_ok, openxr, title, candidates} for an AppImage, a
|
||||
folder or an archive. Raises ValueError when there's no Linux program in it."""
|
||||
path = Path(path)
|
||||
if path.is_file() and is_archive(path):
|
||||
root = unpack(path)
|
||||
subdirs = [d for d in root.iterdir() if not d.name.startswith(".")]
|
||||
if len(subdirs) == 1 and subdirs[0].is_dir(): # the usual single top folder
|
||||
pass
|
||||
title = clean_title(path.name)
|
||||
elif path.is_file():
|
||||
root = path.parent
|
||||
title = clean_title(path.name)
|
||||
else:
|
||||
root = path
|
||||
title = clean_title(path.name)
|
||||
if path.is_file() and not is_archive(path):
|
||||
machine = elf_machine(path)
|
||||
if machine is None:
|
||||
raise ValueError(f"{path.name} isn't a Linux program (AppImage or ELF)")
|
||||
appimage = is_appimage(path)
|
||||
return {"root": str(path.parent), "exe": path.name, "files": [path.name], "appimage": appimage,
|
||||
"machine": machine, "arch_ok": machine == EM_AARCH64, "openxr": uses_openxr([path]),
|
||||
"title": title, "candidates": [path.name]}
|
||||
programs = rank_programs(root)
|
||||
if not programs:
|
||||
raise ValueError(f"no Linux program found in {path.name}")
|
||||
appimages = [p for p, _m in programs if is_appimage(p)]
|
||||
exe, machine = (appimages[0], elf_machine(appimages[0])) if appimages else programs[0]
|
||||
libs = app_libraries(root, exe)
|
||||
title = _desktop_name(root) or title
|
||||
return {"root": str(root), "exe": exe.relative_to(root).as_posix(), "files": None,
|
||||
"appimage": is_appimage(exe), "machine": machine, "arch_ok": machine == EM_AARCH64,
|
||||
"openxr": uses_openxr([exe] + libs), "title": title,
|
||||
"candidates": [p.relative_to(root).as_posix() for p, m in programs[:20] if m == EM_AARCH64]}
|
||||
@@ -18,6 +18,10 @@ TYPE_INT_BOOLEAN = 0x12
|
||||
ANDROID_NS = "http://schemas.android.com/apk/res/android"
|
||||
LAUNCHER = "android.intent.category.LAUNCHER"
|
||||
INFO = "android.intent.category.INFO"
|
||||
MAIN = "android.intent.action.MAIN"
|
||||
DEFAULT = "android.intent.category.DEFAULT"
|
||||
VR_CATEGORY = "com.oculus.intent.category.VR"
|
||||
COMPONENTS = ("activity", "activity-alias", "service", "receiver", "provider")
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -226,6 +230,81 @@ def fix_launcher(manifest: bytes) -> bytes | None:
|
||||
return x.bytes() if x.retarget("category", info, launcher) else None
|
||||
|
||||
|
||||
def component_filters(manifest: bytes) -> list[tuple[str, str, list[tuple[str, int, int]]]]:
|
||||
"""[(element, component name, [(element, attr offset, string index)])] for each component's intent-filter
|
||||
children (action/category), in file order. Children follow their component's start element, so the last
|
||||
component seen owns them."""
|
||||
x = Axml(manifest)
|
||||
names = x.strings()
|
||||
out: list = []
|
||||
for el in x.elements():
|
||||
if el.name in COMPONENTS:
|
||||
out.append((el.name, x.attr_str(el, "name") or "", []))
|
||||
elif el.name in ("action", "category") and out:
|
||||
for a in el.attrs:
|
||||
if a.name < len(names) and names[a.name] == "name":
|
||||
idx = a.raw if a.raw < len(names) else a.value
|
||||
out[-1][2].append((el.name, a.offset, idx))
|
||||
return out
|
||||
|
||||
|
||||
def vr_activity(manifest: bytes) -> str | None:
|
||||
"""The activity with Meta's VR category when it isn't the launcher activity (a 2D launcher that starts the VR
|
||||
part, e.g. WiiCompiled's LauncherActivity -> QuestActivity)."""
|
||||
x = Axml(manifest)
|
||||
names = x.strings()
|
||||
vr = launcher = None
|
||||
for el, name, items in component_filters(manifest):
|
||||
cats = {names[i] for kind, _, i in items if kind == "category" and i < len(names)}
|
||||
if el == "activity" and VR_CATEGORY in cats:
|
||||
vr = vr or name
|
||||
if LAUNCHER in cats:
|
||||
launcher = launcher or name
|
||||
return vr if vr and vr != launcher else None
|
||||
|
||||
|
||||
def set_start_activity(manifest: bytes, activity: str) -> bytes | None:
|
||||
"""Make `activity` the one Lepton starts: its MAIN intent-filter gets category LAUNCHER (in place of its VR or
|
||||
DEFAULT category), every other component's LAUNCHER category becomes INFO. Only those attribute values change
|
||||
(per element, not every use of the string). None when `activity` has no MAIN filter or already is the only
|
||||
launcher."""
|
||||
filters = component_filters(manifest)
|
||||
x = Axml(manifest)
|
||||
names = x.strings()
|
||||
short = activity.rsplit(".", 1)[-1]
|
||||
target = next((f for f in filters if f[0] in ("activity", "activity-alias")
|
||||
and (f[1] == activity or f[1].rsplit(".", 1)[-1] == short)), None)
|
||||
if target is None or not any(k == "action" and names[i] == MAIN for k, _, i in target[2] if i < len(names)):
|
||||
return None
|
||||
cats = [(off, names[i]) for k, off, i in target[2] if k == "category" and i < len(names)]
|
||||
others = [off for f in filters if f is not target for k, off, i in f[2]
|
||||
if k == "category" and i < len(names) and names[i] == LAUNCHER]
|
||||
if any(c == LAUNCHER for _, c in cats) and not others:
|
||||
return None
|
||||
pick = next((off for off, c in cats if c == VR_CATEGORY), None) or next(
|
||||
(off for off, c in cats if c == DEFAULT), None) or next((off for off, c in cats if c != LAUNCHER), None)
|
||||
if pick is None and not any(c == LAUNCHER for _, c in cats):
|
||||
return None
|
||||
|
||||
def index(s: str) -> int:
|
||||
i = x.index(s)
|
||||
return i if i is not None else x.append_string(s)
|
||||
launcher, info = index(LAUNCHER), index(INFO)
|
||||
# append_string rebuilds the pool: offsets of attribute records move by the same amount for all of them
|
||||
shift = len(x.data) - len(manifest)
|
||||
for off in others:
|
||||
_set_string_attr(x, off + shift, info)
|
||||
if pick is not None and not any(c == LAUNCHER for _, c in cats):
|
||||
_set_string_attr(x, pick + shift, launcher)
|
||||
return x.bytes()
|
||||
|
||||
|
||||
def _set_string_attr(x: Axml, offset: int, index: int) -> None:
|
||||
struct.pack_into("<I", x.data, offset + 8, index)
|
||||
if x.data[offset + 15] == TYPE_STRING:
|
||||
struct.pack_into("<I", x.data, offset + 16, index)
|
||||
|
||||
|
||||
def set_bool_attr(manifest: bytes, element: str, attr: str, value: bool) -> bytes | None:
|
||||
x = Axml(manifest)
|
||||
return x.bytes() if x.set_bool(element, attr, value) else None
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Minimal in-place dex edits: find one method's bytecode and turn a call in it into no-ops (same length), then fix the
|
||||
header's SHA-1 signature and Adler-32 checksum. Nothing moves, so the rest of classes.dex stays byte-identical (no
|
||||
smali round trip)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
INVOKE_VIRTUAL, INVOKE_VIRTUAL_RANGE = 0x6E, 0x74 # 35c / 3rc: 3 code units, method index in the second
|
||||
|
||||
|
||||
def _uleb(data: bytes, pos: int) -> tuple[int, int]:
|
||||
value = shift = 0
|
||||
while True:
|
||||
b = data[pos]
|
||||
pos += 1
|
||||
value |= (b & 0x7F) << shift
|
||||
if not b & 0x80:
|
||||
return value, pos
|
||||
shift += 7
|
||||
|
||||
|
||||
class Dex:
|
||||
def __init__(self, data: bytes):
|
||||
if data[:4] != b"dex\n":
|
||||
raise ValueError("not a dex file")
|
||||
self.data = bytearray(data)
|
||||
h = struct.unpack_from("<8I", data, 56) # string_ids size/off, type_ids, proto_ids, field_ids
|
||||
self.strings_n, self.strings_off, self.types_n, self.types_off = h[0], h[1], h[2], h[3]
|
||||
self.methods_n, self.methods_off, self.classes_n, self.classes_off = struct.unpack_from("<4I", data, 88)
|
||||
|
||||
def string(self, idx: int) -> str:
|
||||
off = struct.unpack_from("<I", self.data, self.strings_off + 4 * idx)[0]
|
||||
_n, pos = _uleb(self.data, off)
|
||||
end = self.data.index(0, pos)
|
||||
return bytes(self.data[pos:end]).decode("utf-8", "replace")
|
||||
|
||||
def type_name(self, idx: int) -> str:
|
||||
return self.string(struct.unpack_from("<I", self.data, self.types_off + 4 * idx)[0])
|
||||
|
||||
def method(self, idx: int) -> tuple[str, str]:
|
||||
cls, _proto, name = struct.unpack_from("<HHI", self.data, self.methods_off + 8 * idx)
|
||||
return self.type_name(cls), self.string(name)
|
||||
|
||||
def method_index(self, cls: str, name: str) -> list[int]:
|
||||
return [i for i in range(self.methods_n) if self.method(i) == (cls, name)]
|
||||
|
||||
def code_items(self, cls: str, name: str) -> list[int]:
|
||||
"""Offsets of the code items of the methods `name` in class `cls` (direct and virtual)."""
|
||||
out = []
|
||||
for c in range(self.classes_n):
|
||||
base = self.classes_off + 32 * c
|
||||
if self.type_name(struct.unpack_from("<I", self.data, base)[0]) != cls:
|
||||
continue
|
||||
class_data = struct.unpack_from("<I", self.data, base + 24)[0]
|
||||
if not class_data:
|
||||
continue
|
||||
pos = class_data
|
||||
sf, pos = _uleb(self.data, pos)
|
||||
inf, pos = _uleb(self.data, pos)
|
||||
dm, pos = _uleb(self.data, pos)
|
||||
vm, pos = _uleb(self.data, pos)
|
||||
for _ in range(sf + inf):
|
||||
_, pos = _uleb(self.data, pos)
|
||||
_, pos = _uleb(self.data, pos)
|
||||
for count in (dm, vm):
|
||||
idx = 0
|
||||
for _ in range(count):
|
||||
diff, pos = _uleb(self.data, pos)
|
||||
_, pos = _uleb(self.data, pos)
|
||||
code, pos = _uleb(self.data, pos)
|
||||
idx += diff
|
||||
if code and self.method(idx)[1] == name:
|
||||
out.append(code)
|
||||
return out
|
||||
|
||||
def nop_calls(self, code_off: int, targets: set[int]) -> int:
|
||||
"""Replace invoke-virtual(/range) calls of any method index in `targets` inside one code item with nops."""
|
||||
insns_n = struct.unpack_from("<I", self.data, code_off + 12)[0]
|
||||
start = code_off + 16
|
||||
units = struct.unpack_from(f"<{insns_n}H", self.data, start)
|
||||
done = 0
|
||||
for i in range(insns_n - 2):
|
||||
if units[i] & 0xFF in (INVOKE_VIRTUAL, INVOKE_VIRTUAL_RANGE) and units[i + 1] in targets:
|
||||
struct.pack_into("<3H", self.data, start + 2 * i, 0, 0, 0)
|
||||
done += 1
|
||||
return done
|
||||
|
||||
def finish(self) -> bytes:
|
||||
self.data[12:32] = hashlib.sha1(bytes(self.data[32:])).digest()
|
||||
struct.pack_into("<I", self.data, 8, zlib.adler32(bytes(self.data[12:])) & 0xFFFFFFFF)
|
||||
return bytes(self.data)
|
||||
@@ -251,3 +251,68 @@ def apply_choice(package: str, choice: dict) -> bool:
|
||||
return True
|
||||
finally:
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
|
||||
|
||||
# The user's own images (Artwork dialog → "Your own images"), for games whose art can't be found automatically.
|
||||
CUSTOM_KINDS = ("portrait", "landscape", "hero", "logo", "icon")
|
||||
CUSTOM_MAX_BYTES = 40 << 20
|
||||
CUSTOM_MIN_PX = 64
|
||||
CUSTOM_MAX_PX = 3840 # larger images are scaled down (Steam's biggest shape is 1920 px wide)
|
||||
|
||||
|
||||
class ArtError(ValueError):
|
||||
"""The chosen file can't be used as artwork (the message says why, for the GUI)."""
|
||||
|
||||
|
||||
def apply_custom(package: str, kind: str, path: str | Path) -> Path:
|
||||
"""Store an image file the user chose as one kind of artwork, replacing that kind only. It is checked and
|
||||
re-encoded (PNG when it has transparency, else JPEG; logos and icons always PNG), marked as the user's pick so
|
||||
automatic fetches never replace it, and the old thumbnails go. FramePort's generated cover/banner (games without
|
||||
store art) are dropped once a real cover shape exists. Returns the stored file."""
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
if kind not in CUSTOM_KINDS:
|
||||
raise ArtError(f"unknown artwork kind {kind!r}")
|
||||
path = Path(path)
|
||||
try:
|
||||
if path.stat().st_size > CUSTOM_MAX_BYTES:
|
||||
raise ArtError(f"{path.name} is larger than {CUSTOM_MAX_BYTES >> 20} MB")
|
||||
with Image.open(path) as im:
|
||||
im.load()
|
||||
im = im.copy()
|
||||
except (OSError, UnidentifiedImageError, Image.DecompressionBombError):
|
||||
raise ArtError(f"{path.name} isn't an image FramePort can read (use PNG, JPEG or WebP)") from None
|
||||
if min(im.size) < CUSTOM_MIN_PX:
|
||||
raise ArtError(f"{path.name} is too small ({im.width}×{im.height}); use at least {CUSTOM_MIN_PX} px")
|
||||
if max(im.size) > CUSTOM_MAX_PX:
|
||||
im.thumbnail((CUSTOM_MAX_PX, CUSTOM_MAX_PX), Image.LANCZOS)
|
||||
alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
|
||||
png = alpha or kind in ("logo", "icon")
|
||||
d = fetch.artwork_dir(package)
|
||||
tmp = d / f".custom-{kind}.tmp"
|
||||
if png:
|
||||
im.convert("RGBA" if alpha else "RGB").save(tmp, "PNG", optimize=True)
|
||||
else:
|
||||
im.convert("RGB").save(tmp, "JPEG", quality=92, optimize=True)
|
||||
_drop_kind(d, kind)
|
||||
out = d / f"{kind}{'.png' if png else '.jpg'}"
|
||||
tmp.replace(out)
|
||||
if kind in ("portrait", "landscape", "hero"):
|
||||
for stem in ("cover", "banner"):
|
||||
_drop_kind(d, stem)
|
||||
(d / fetch.PICKED).write_text("custom", encoding="utf-8") # automatic fetches leave the art alone
|
||||
return out
|
||||
|
||||
|
||||
def remove_custom(package: str, kind: str) -> None:
|
||||
"""Remove one kind of artwork (the Steam set then composes it from the other kinds, or uses a placeholder)."""
|
||||
if kind not in CUSTOM_KINDS:
|
||||
raise ArtError(f"unknown artwork kind {kind!r}")
|
||||
d = fetch.artwork_dir(package)
|
||||
_drop_kind(d, kind)
|
||||
(d / fetch.PICKED).write_text("custom", encoding="utf-8") # "Find automatically" brings store art back
|
||||
|
||||
|
||||
def _drop_kind(d: Path, kind: str) -> None:
|
||||
for f in list(d.glob(f"{kind}.*")) + list(d.glob(f"t_{kind}_*")):
|
||||
f.unlink(missing_ok=True)
|
||||
@@ -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 ''}")
|
||||
@@ -298,7 +299,11 @@ def _placeholder(out_dir: Path, title: str, icon_file: Path | None, apk) -> dict
|
||||
def original_platform(entry: dict) -> str:
|
||||
"""What the game was made for (a Steam tag)."""
|
||||
extra = (entry.get("analysis") or {}).get("extra") or {}
|
||||
if entry.get("kind") == "linux":
|
||||
return "Linux"
|
||||
if entry.get("kind") == "rift":
|
||||
if extra.get("flat"):
|
||||
return "Windows"
|
||||
return "Oculus Rift" if extra.get("needs_revive") else "PC VR"
|
||||
kind = extra.get("vr_kind") or "quest"
|
||||
return {"quest": "Meta Quest", "none": "Android"}.get(kind, "Android VR")
|
||||
@@ -310,7 +315,9 @@ def steam_tags(entry: dict, where: str = "frame") -> list[str]:
|
||||
from ..targets.pc_revive import TAG
|
||||
|
||||
kind = ((entry.get("analysis") or {}).get("extra") or {}).get("vr_kind") or "quest"
|
||||
runs = TAG if where != "frame" else "PC VR on Frame" if entry.get("kind") == "rift" else \
|
||||
flat = bool(((entry.get("analysis") or {}).get("extra") or {}).get("flat"))
|
||||
runs = TAG if where != "frame" else ("Windows game on Frame" if flat else "PC VR on Frame") \
|
||||
if entry.get("kind") == "rift" else "Linux app on Frame" if entry.get("kind") == "linux" else \
|
||||
"Quest on Frame" if kind == "quest" else "Android on Frame"
|
||||
base = [runs, original_platform(entry)]
|
||||
genres = ((entry.get("details") or {}).get("genres") or [])[:4]
|
||||
|
||||
@@ -86,7 +86,20 @@ def ready_thumb(path: Path, width: int, kind: str | None = None) -> Path | None:
|
||||
return out if out.exists() else None
|
||||
|
||||
|
||||
_FILE_PATHS = False
|
||||
|
||||
|
||||
def use_file_paths(on: bool = True) -> None:
|
||||
"""Images by absolute file path: a packaged app (flet build) serves relative image paths from its own bundled
|
||||
assets, not from assets_dir, so artwork by URL stayed blank there (GitHub issue 16; the reporter confirmed file
|
||||
paths work in the Windows app). Source runs and the web view (ui_smoke) keep URLs."""
|
||||
global _FILE_PATHS
|
||||
_FILE_PATHS = on
|
||||
|
||||
|
||||
def asset_url(path: Path) -> str:
|
||||
if _FILE_PATHS:
|
||||
return str(path.resolve())
|
||||
return "/" + path.relative_to(user_data_dir()).as_posix()
|
||||
|
||||
|
||||
|
||||
+40
-1
@@ -84,6 +84,9 @@ def _update_hint() -> None:
|
||||
age = updates.cache_age()
|
||||
if age is None or age > updates.CHECK_EVERY:
|
||||
threading.Thread(target=updates.refresh_cache, daemon=True).start()
|
||||
from .recommend import catalog as _catalog
|
||||
|
||||
threading.Thread(target=_catalog.refresh_remote, daemon=True).start() # confirmed configs from GitHub main
|
||||
up = updates.cached_update()
|
||||
today = time.strftime("%Y-%m-%d")
|
||||
if up and library.setting("update.cli_hint") != today:
|
||||
@@ -227,6 +230,31 @@ def scan(path: Path = typer.Argument(..., help="a folder with game backups (APKs
|
||||
typer.echo(f"{g['package']:40} {g.get('title', '')[:34]:34} {r['status']:11} {r['source']}")
|
||||
|
||||
|
||||
@app.command("catalog-update")
|
||||
def catalog_update():
|
||||
"""Fetch confirmed game configs from the repo's main branch now (normally automatic, every 6 h)."""
|
||||
from .recommend import catalog
|
||||
|
||||
n = catalog.refresh_remote(force=True)
|
||||
st = catalog.remote_status()
|
||||
typer.echo(f"{n} config(s) downloaded; {st['entries']} on GitHub main")
|
||||
for pkg, why in sorted(st["skipped"].items()):
|
||||
typer.echo(f" skipped {pkg}: {why}")
|
||||
|
||||
|
||||
@app.command("add-linux")
|
||||
def add_linux(path: Path = typer.Argument(..., help="an arm64 AppImage, a folder, or a .zip/.tar.gz with the app"),
|
||||
exe: Optional[str] = typer.Option(None, help="the program to start (relative to the app's folder)")):
|
||||
"""Add a native arm64 Linux app to the library (installed on the Frame as it is, with a Steam shortcut)."""
|
||||
try:
|
||||
g = pipeline.add_linux_app(path, printing_reporter(verbose=False), exe=exe)
|
||||
except ValueError as exc:
|
||||
raise typer.BadParameter(str(exc)) from None
|
||||
extra = g["analysis"]["extra"]
|
||||
typer.echo(f"{g['package']:40} {g.get('title', '')[:34]:34} program {extra['exe']}"
|
||||
f"{' (AppImage)' if extra['appimage'] else ''}{' VR' if extra['openxr'] else ''}")
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def list_games():
|
||||
"""The games in the library."""
|
||||
@@ -405,7 +433,8 @@ def frame_pair(timeout: float = typer.Option(600, help="seconds to wait for the
|
||||
from .frame.pairing import PairingServer
|
||||
|
||||
srv = PairingServer().start()
|
||||
typer.echo("On the Frame, open Desktop Mode → Konsole and run:\n\n " + srv.one_liner + "\n")
|
||||
typer.echo("On the Frame, open the SteamVR dashboard → Launch a program → Desktop, then System → Konsole, and "
|
||||
"run:\n\n " + srv.one_liner + "\n")
|
||||
end = time.time() + timeout
|
||||
while time.time() < end and not srv.paired:
|
||||
time.sleep(1)
|
||||
@@ -479,6 +508,16 @@ def frame_info(frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
|
||||
typer.echo(json.dumps(_target(frame).describe(), indent=1, default=str))
|
||||
|
||||
|
||||
@frame_app.command("usb-check")
|
||||
def frame_usb_check(frame: Optional[str] = typer.Option(None, help=FRAME_HELP),
|
||||
no_speed: bool = typer.Option(False, help="skip the upload speed test (2 × 128 MB)")):
|
||||
"""Check the USB cable link to the Frame: what the Frame presents, this PC's address on it, SSH over it and its
|
||||
upload speed vs the normal connection (JSON)."""
|
||||
from .frame import usb
|
||||
|
||||
typer.echo(json.dumps(usb.check(_target(frame).connect().frame, measure=not no_speed), indent=1, default=str))
|
||||
|
||||
|
||||
@frame_app.command("controller-models")
|
||||
def frame_controller_models(frame: Optional[str] = typer.Option(None, help=FRAME_HELP),
|
||||
convert: bool = typer.Option(False, help="also convert them (cached on the Frame)")):
|
||||
|
||||
@@ -28,7 +28,7 @@ def load() -> dict:
|
||||
data = json.loads(_path().read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {"games": {}, "settings": {}}
|
||||
if _migrate(data):
|
||||
if _migrate(data) | _follow_catalog(data):
|
||||
save(data)
|
||||
return data
|
||||
|
||||
@@ -42,6 +42,54 @@ def edit() -> Iterator[dict]:
|
||||
save(data)
|
||||
|
||||
|
||||
REFRESH_ON_UPDATE = True # (tests switch it off: their hand-made libraries have no version marker)
|
||||
|
||||
|
||||
def _follow_catalog(data: dict) -> bool:
|
||||
"""Recipes FramePort derived (not ones the user edited) stay current: when their catalog entry is new or changed,
|
||||
and once after every app update (new automatic fixes and suggestions in FramePort's code), the game's recipe is
|
||||
derived again; a changed recipe shows Update on Frame."""
|
||||
from .. import __version__
|
||||
from ..recommend import catalog, engine
|
||||
|
||||
settings = data.setdefault("settings", {})
|
||||
app_updated = REFRESH_ON_UPDATE and settings.get("recipes.app_version") != __version__
|
||||
changed = app_updated
|
||||
settings["recipes.app_version"] = __version__
|
||||
for pkg, g in (data.get("games") or {}).items():
|
||||
r, a = g.get("recipe"), g.get("analysis")
|
||||
if g.get("kind") == "linux": # installed as it is: no recipe to derive
|
||||
continue
|
||||
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)
|
||||
if not app_updated and (entry is None or r.get("catalog_rev") == entry.rev()):
|
||||
continue
|
||||
try:
|
||||
g["recipe"] = recipe_to_dict(engine.suggest(analysis_from_dict(a)))
|
||||
except Exception: # noqa: BLE001 - a malformed entry keeps its recipe
|
||||
continue
|
||||
changed = True
|
||||
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", [])
|
||||
@@ -177,7 +225,7 @@ def _migrate(data: dict) -> bool:
|
||||
# Android apps without VR gain the default-on "Hide Android's navigation bar" patch
|
||||
for g in (data.get("games") or {}).values():
|
||||
a, r = g.get("analysis") or {}, g.get("recipe")
|
||||
if isinstance(r, dict) and (a.get("extra") or {}).get("vr_kind") == "none":
|
||||
if isinstance(r, dict) and (a.get("extra") or {}).get("vr_kind") == "none" and g.get("kind") != "linux":
|
||||
r.setdefault("patches", {}).setdefault("device.hide_navbar", {})
|
||||
r.setdefault("reasons", {}).setdefault(
|
||||
"device.hide_navbar", "2D app: Android's navigation buttons would cover the app's own controls.")
|
||||
|
||||
@@ -82,6 +82,7 @@ class Recipe:
|
||||
as_is: bool = False # install the game unchanged (already patched): no overport / Frame fixes / Revive
|
||||
overport: bool = True # False: an ordinary Android app: no VR translation (overport) and no FrameBridge adapter
|
||||
reasons: dict[str, str] = field(default_factory=dict) # patch id -> why it was suggested
|
||||
catalog_rev: str = "" # CatalogEntry.rev() it was derived from: a changed catalog entry re-derives the recipe
|
||||
|
||||
def enabled(self, patch_id: str) -> bool:
|
||||
return patch_id in self.patches
|
||||
|
||||
@@ -39,6 +39,12 @@ def bootstrap_dir() -> Path:
|
||||
return DATA_ROOT / "bootstrap"
|
||||
|
||||
|
||||
def _on_frame() -> bool:
|
||||
from ..frame.local import on_frame
|
||||
|
||||
return on_frame()
|
||||
|
||||
|
||||
def user_data_dir() -> Path:
|
||||
"""Tools, keystores, work dirs and settings. Override with FRAMEPORT_HOME."""
|
||||
if os.environ.get("FRAMEPORT_HOME"):
|
||||
@@ -48,7 +54,10 @@ def user_data_dir() -> Path:
|
||||
elif sys.platform == "darwin":
|
||||
base = Path.home() / "Library/Application Support/FramePort"
|
||||
else:
|
||||
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "frameport"
|
||||
# on the Frame itself ~/.local/share/frameport is the agent's folder (and its purge removes it): the app's own
|
||||
# data (library, tools, game signing keys) lives next to it
|
||||
name = "frameport-app" if _on_frame() else "frameport"
|
||||
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / name
|
||||
if not _removed.is_set():
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
return base
|
||||
|
||||
@@ -16,7 +16,7 @@ def twins(games: list[dict]) -> set[str]:
|
||||
by_pkg = {g["package"]: g for g in games}
|
||||
quest_by_title = {}
|
||||
for g in games:
|
||||
if g.get("kind") != "rift":
|
||||
if g.get("kind") not in ("rift", "linux"): # (Linux apps have no Quest/Rift twin)
|
||||
quest_by_title.setdefault(_norm(g.get("title") or ""), []).append(g["package"])
|
||||
out = set()
|
||||
for g in games:
|
||||
@@ -41,11 +41,13 @@ def display_title(game: dict, twin_set: set[str] | None = None) -> str:
|
||||
|
||||
def counterparts(game: dict, games: list[dict]) -> list[dict]:
|
||||
"""The other-platform versions of this game in the library."""
|
||||
if game.get("kind") == "linux":
|
||||
return []
|
||||
rift = game.get("kind") == "rift"
|
||||
t = _norm(game.get("title") or "")
|
||||
out = []
|
||||
for g in games:
|
||||
if g["package"] == game["package"] or (g.get("kind") == "rift") == rift:
|
||||
if g["package"] == game["package"] or (g.get("kind") == "rift") == rift or g.get("kind") == "linux":
|
||||
continue
|
||||
linked = (rift and game.get("quest_package") == g["package"]) or \
|
||||
(not rift and g.get("quest_package") == game["package"])
|
||||
|
||||
@@ -170,6 +170,18 @@ def package_listing(g: dict) -> dict[str, object]:
|
||||
pe[rel] = {"error": str(exc)}
|
||||
out["pe.json"] = pe
|
||||
return out
|
||||
if g.get("kind") == "linux": # the app's file list (a lone AppImage: only it, not the folder it's in)
|
||||
root, extra = Path(g.get("game_dir") or ""), (g.get("analysis") or {}).get("extra") or {}
|
||||
paths = [root / f for f in extra["files"]] if extra.get("files") else \
|
||||
sorted(root.rglob("*")) if root.is_dir() else []
|
||||
files = []
|
||||
for p in paths:
|
||||
if p.is_file():
|
||||
files.append([p.relative_to(root).as_posix(), p.stat().st_size])
|
||||
if len(files) >= 20000:
|
||||
break
|
||||
out["files.json"] = files
|
||||
return out
|
||||
apk = Path(g.get("apk") or "")
|
||||
if not apk.is_file():
|
||||
return out
|
||||
|
||||
@@ -55,7 +55,7 @@ def working_config_url(g: dict, recipe_yaml: str, status: str, notes: str, env:
|
||||
red: redact.Redactor | None = None) -> str:
|
||||
red = red or redact.Redactor()
|
||||
title = g.get("title") or g["package"]
|
||||
kind = "Oculus Rift (PC VR)" if g.get("kind") == "rift" else "Meta Quest"
|
||||
kind = {"rift": "Oculus Rift (PC VR)", "linux": "Linux app (arm64)"}.get(g.get("kind"), "Meta Quest")
|
||||
a = g.get("analysis") or {}
|
||||
game = f"{title} — {g['package']} ({kind}, version {a.get('version') or '?'}, {a.get('engine') or '?'} / " \
|
||||
f"{a.get('xr') or '?'})"
|
||||
|
||||
@@ -46,8 +46,12 @@ def explain(exc: BaseException) -> str:
|
||||
low = msg.lower()
|
||||
if paramiko and isinstance(exc, paramiko.ChannelException):
|
||||
return tr("The connection to the Frame is busy. Try again in a moment.")
|
||||
if "authentication failed" in low:
|
||||
return msg # already says what to do (run the bootstrap / enter the password)
|
||||
if "authentication failed" in low or "no authentication methods available" in low:
|
||||
if "password was refused" in low:
|
||||
return tr("The Frame refused that password. Check it, or run the first-time setup instead: Steam Frame → "
|
||||
"Show setup command.")
|
||||
return tr("This Frame isn't set up for FramePort yet. Run the first-time setup: Steam Frame → Show setup "
|
||||
"command.")
|
||||
if is_connection_error(exc):
|
||||
return tr("Can't reach your Frame. Make sure it's on, awake and on the same network, then try again.")
|
||||
if isinstance(exc, OSError) and exc.errno == errno.ENOSPC:
|
||||
|
||||
@@ -9,11 +9,13 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import posixpath
|
||||
import re
|
||||
import stat
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
@@ -21,9 +23,36 @@ import paramiko
|
||||
|
||||
from ..core.paths import agent_file, ssh_dir, user_data_dir, write_atomic
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
REMOTE_AGENT_DIR = ".local/share/frameport/agent"
|
||||
|
||||
|
||||
def agent_version_of(text: str) -> int:
|
||||
"""AGENT_VERSION from an agent's source (0 if missing)."""
|
||||
m = re.search(r"^AGENT_VERSION\s*=\s*(\d+)", text, re.M)
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
class FrameNotPaired(ConnectionError):
|
||||
"""SSH works but none of FramePort's ways in was accepted: the Frame hasn't run the first-time setup (or the
|
||||
password was wrong). The message keeps "authentication failed" for older callers."""
|
||||
|
||||
def __init__(self, tried_password: bool, details: list[str]):
|
||||
self.tried_password = tried_password
|
||||
self.details = details
|
||||
reason = ("the password was refused" if tried_password
|
||||
else "this Frame doesn't know FramePort yet")
|
||||
super().__init__(f"SSH authentication failed: {reason}. Run the first-time setup on the Frame (Steam Frame → "
|
||||
"Show setup command)." + (f" ({'; '.join(details)})" if details else ""))
|
||||
|
||||
|
||||
def _no_auth_methods(exc: BaseException) -> bool:
|
||||
"""paramiko ends a key/agent attempt that had nothing to offer (no SSH keys on this PC, no agent) with a plain
|
||||
SSHException, not an AuthenticationException: it's a failed login all the same, not a network problem."""
|
||||
return isinstance(exc, paramiko.SSHException) and "no authentication methods available" in str(exc).lower()
|
||||
|
||||
|
||||
def app_key() -> paramiko.Ed25519Key:
|
||||
path = ssh_dir() / "id_ed25519"
|
||||
if not path.exists():
|
||||
@@ -93,7 +122,14 @@ _saved_cache: tuple[float, list] = (-1.0, [])
|
||||
|
||||
|
||||
def saved_targets() -> list[FrameTarget]:
|
||||
"""The remembered Frames (read again only when frames.json changed: the sidebar asks several times a second)."""
|
||||
"""The remembered Frames (read again only when frames.json changed: the sidebar asks several times a second).
|
||||
FramePort running on a Frame remembers that Frame itself (127.0.0.1) the first time."""
|
||||
if not (user_data_dir() / "frames.json").exists():
|
||||
return _local_frame()
|
||||
return _read_saved()
|
||||
|
||||
|
||||
def _read_saved() -> list[FrameTarget]:
|
||||
global _saved_cache
|
||||
path = user_data_dir() / "frames.json"
|
||||
try:
|
||||
@@ -111,8 +147,62 @@ def saved_targets() -> list[FrameTarget]:
|
||||
return []
|
||||
|
||||
|
||||
def is_unreachable(exc: BaseException) -> bool:
|
||||
"""The Frame isn't there at all (asleep, off the network): retrying an upload at once won't help."""
|
||||
return isinstance(exc, (ConnectionRefusedError, TimeoutError, paramiko.ssh_exception.NoValidConnectionsError))
|
||||
|
||||
|
||||
def _local_frame() -> list[FrameTarget]:
|
||||
"""On a Frame with nothing remembered yet: this Frame, with FramePort's key authorized for the local user."""
|
||||
from . import local
|
||||
|
||||
if not local.on_frame():
|
||||
return []
|
||||
try:
|
||||
local.authorize_self(app_public_key())
|
||||
except OSError:
|
||||
pass
|
||||
target = FrameTarget("127.0.0.1", local.local_user(), 22, local.LOCAL_NAME)
|
||||
save_target(target)
|
||||
return [target]
|
||||
|
||||
|
||||
def replace_target(old_host: str, target: FrameTarget) -> None:
|
||||
"""The remembered Frame at old_host is now at target.host (same device: its SSH host key matched)."""
|
||||
items = [FrameTarget(target.host, t.user, t.port, t.name) if t.host == old_host else t for t in _read_saved()]
|
||||
if target.host not in [t.host for t in items]:
|
||||
items.insert(0, target)
|
||||
seen, out = set(), []
|
||||
for t in items:
|
||||
if t.host not in seen:
|
||||
seen.add(t.host)
|
||||
out.append(t)
|
||||
write_atomic(user_data_dir() / "frames.json", json.dumps([t.__dict__ for t in out], indent=2))
|
||||
|
||||
|
||||
def server_key(host: str, port: int = 22, timeout: float = 5) -> paramiko.PKey | None:
|
||||
"""The SSH host key a device presents (no login)."""
|
||||
import socket
|
||||
|
||||
try:
|
||||
sock = socket.create_connection((host, port), timeout=timeout)
|
||||
except OSError:
|
||||
return None
|
||||
transport = paramiko.Transport(sock)
|
||||
try:
|
||||
transport.start_client(timeout=timeout)
|
||||
return transport.get_remote_server_key()
|
||||
except (OSError, paramiko.SSHException, EOFError):
|
||||
return None
|
||||
finally:
|
||||
transport.close()
|
||||
|
||||
|
||||
_last_relocate = -1e9
|
||||
|
||||
|
||||
def save_target(target: FrameTarget) -> None:
|
||||
items = [t for t in saved_targets() if t.host != target.host]
|
||||
items = [t for t in _read_saved() if t.host != target.host]
|
||||
items.insert(0, target)
|
||||
write_atomic(user_data_dir() / "frames.json", json.dumps([t.__dict__ for t in items], indent=2))
|
||||
|
||||
@@ -133,6 +223,9 @@ def bundled_agent_version() -> int | None:
|
||||
RUN_TIMEOUT = 120 # seconds: default bound for one remote command's output
|
||||
|
||||
|
||||
NOT_IN_LIBRARY = "not in the Frame's Steam library" # agent cmd_launch's error when the shortcut is missing
|
||||
|
||||
|
||||
class AgentFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
@@ -260,6 +353,48 @@ class Frame:
|
||||
|
||||
# ------------------------------------------------------------------ connect
|
||||
def connect(self, timeout: float = 10) -> Frame:
|
||||
try:
|
||||
return self._connect(timeout)
|
||||
except OSError:
|
||||
if self.target.host in ("127.0.0.1", "localhost"): # FramePort on the Frame itself: sshd isn't running
|
||||
raise ConnectionError("FramePort runs on this Frame but can't reach it over SSH: turn on Developer "
|
||||
"Mode (Steam → Settings → System → Developer Mode), then try again") from None
|
||||
moved = self.relocate() # the router gave the Frame a new address (it's remembered by address)
|
||||
if not moved:
|
||||
raise
|
||||
log.info("Frame moved from %s to %s", self.target.host, moved)
|
||||
old, self.target.host = self.target.host, moved
|
||||
self._connect(timeout)
|
||||
replace_target(old, self.target)
|
||||
return self
|
||||
|
||||
def relocate(self) -> str | None:
|
||||
"""The Frame's new address when it no longer answers at the remembered one: a device on the network whose
|
||||
SSH host key is the one this PC saw at the old address (checked before logging in). At most once a minute (the
|
||||
GUI retries every few seconds while a Frame sleeps)."""
|
||||
global _last_relocate
|
||||
if time.monotonic() - _last_relocate < 60 or self.target.host not in [t.host for t in saved_targets()]:
|
||||
return None
|
||||
_last_relocate = time.monotonic()
|
||||
hk = paramiko.HostKeys()
|
||||
try:
|
||||
hk.load(str(ssh_dir() / "known_hosts"))
|
||||
except OSError:
|
||||
return None
|
||||
known = hk.lookup(self.target.host if self.target.port == 22 else f"[{self.target.host}]:{self.target.port}")
|
||||
if not known:
|
||||
return None
|
||||
from .discovery import browse
|
||||
|
||||
for f in browse(seconds=3.0):
|
||||
if f.host == self.target.host or f.port != self.target.port:
|
||||
continue
|
||||
key = server_key(f.host, f.port)
|
||||
if key is not None and known.get(key.get_name()) == key:
|
||||
return f.host
|
||||
return None
|
||||
|
||||
def _connect(self, timeout: float) -> Frame:
|
||||
known = ssh_dir() / "known_hosts"
|
||||
known.touch(exist_ok=True)
|
||||
kwargs = dict(hostname=self.target.host, port=self.target.port, username=self.target.user, timeout=timeout,
|
||||
@@ -283,12 +418,17 @@ class Frame:
|
||||
except paramiko.AuthenticationException as exc:
|
||||
client.close()
|
||||
errors.append(f"{attempt}: {exc}")
|
||||
except paramiko.SSHException as exc:
|
||||
client.close()
|
||||
if not _no_auth_methods(exc):
|
||||
raise
|
||||
# (Reddit, 2026-10-03: this ended the loop before the password was tried)
|
||||
errors.append(f"{attempt}: {exc}")
|
||||
except BaseException:
|
||||
client.close()
|
||||
raise
|
||||
else:
|
||||
raise ConnectionError("SSH authentication failed (" + "; ".join(errors) + "). Run the FramePort "
|
||||
"bootstrap on the Frame or enter the steamos password.")
|
||||
raise FrameNotPaired(bool(self.password), errors)
|
||||
client.save_host_keys(str(known))
|
||||
transport = client.get_transport()
|
||||
transport.set_keepalive(15)
|
||||
@@ -308,6 +448,8 @@ class Frame:
|
||||
presents the same SSH host key as this connection. Returns (frame, link name); (self, "") if none."""
|
||||
import socket
|
||||
|
||||
if self.target.host in ("127.0.0.1", "localhost"): # FramePort on the Frame itself: nothing is faster
|
||||
return self, ""
|
||||
key = self.client.get_transport().get_remote_server_key()
|
||||
for iface in FAST_LINKS:
|
||||
for name, ip in self.addresses():
|
||||
@@ -376,8 +518,17 @@ class Frame:
|
||||
remote = posixpath.join(remote_dir, "frameport_agent.py")
|
||||
if self._agent_digest == digest:
|
||||
return remote
|
||||
code, out, _ = self.run(f"sha256sum {sh_quote(remote)} 2>/dev/null | cut -c1-16")
|
||||
if out.strip() != digest:
|
||||
code, out, _ = self.run(f"sha256sum {sh_quote(remote)} 2>/dev/null | cut -c1-16; "
|
||||
f"grep -m1 '^AGENT_VERSION' {sh_quote(remote)} 2>/dev/null")
|
||||
lines = out.split("\n")
|
||||
remote_version = agent_version_of(lines[1] if len(lines) > 1 else "")
|
||||
if lines[0].strip() != digest and remote_version > agent_version_of(text.decode("utf-8", "replace")):
|
||||
# a newer FramePort (another PC, or FramePort on the Frame) installed a newer agent: keep it. Agents
|
||||
# stay compatible with older apps; replacing it broke the newer one's launchers (2026-10-04: an older
|
||||
# app put agent 43 back over 45 every few seconds)
|
||||
self._agent_digest = digest
|
||||
return remote
|
||||
if lines[0].strip() != digest:
|
||||
self.run(f"mkdir -p {sh_quote(remote_dir)}")
|
||||
tmp = f"{remote}.{os.getpid()}.{threading.get_ident()}.tmp" # two threads never share a temp file
|
||||
with self.sftp.open(tmp, "wb") as f:
|
||||
@@ -408,10 +559,24 @@ class Frame:
|
||||
if dirs:
|
||||
self.run("xargs -0 mkdir -p", stdin="\0".join(dirs))
|
||||
|
||||
def put(self, local: Path, remote: str, progress=None, resume: bool = True, mkdir: bool = True) -> None:
|
||||
def put(self, local: Path, remote: str, progress=None, resume: bool = True, mkdir: bool = True,
|
||||
attempts: int = 3) -> None:
|
||||
"""Upload with resume: data goes to <remote>.part, appended from the existing size, then renamed. progress may
|
||||
raise (e.g. Cancelled): the .part stays and the next put continues from there."""
|
||||
local = Path(local)
|
||||
raise (e.g. Cancelled): the .part stays and the next put continues from there. A failed transfer is resumed
|
||||
up to `attempts` times (Windows: an occasional OSError [Errno 22] mid-upload that the next try got past)."""
|
||||
for attempt in range(attempts):
|
||||
try:
|
||||
return self._put(Path(local), remote, progress, resume, mkdir)
|
||||
except OSError as exc:
|
||||
if attempt == attempts - 1 or is_unreachable(exc):
|
||||
raise
|
||||
log.warning("upload of %s failed (%s), resuming", Path(local).name, exc)
|
||||
time.sleep(2)
|
||||
if not self.alive():
|
||||
self.close()
|
||||
self.connect()
|
||||
|
||||
def _put(self, local: Path, remote: str, progress, resume: bool, mkdir: bool) -> None:
|
||||
size = local.stat().st_size
|
||||
part = remote + ".part"
|
||||
if mkdir:
|
||||
|
||||
@@ -152,8 +152,41 @@ def browse(seconds: float = 4.0, scan: bool = True) -> list[Found]:
|
||||
known = {f.host for f in out}
|
||||
for ip in _scan(local_subnets(), known):
|
||||
out.append(Found(ip, ip, 22, "steamos", "scan", [ip]))
|
||||
rank = {"frameport": 0, "devkit": 1, "saved": 2, "scan": 3}
|
||||
return sorted(out, key=lambda f: (rank.get(f.source, 9), f.name, link_label(f.host) != "network", f.host))
|
||||
out = dedupe(out)
|
||||
return sorted(out, key=lambda f: (SOURCE_RANK.get(f.source, 9), f.name, LINK_RANK.get(f.via, 9), f.host))
|
||||
|
||||
|
||||
SOURCE_RANK = {"frameport": 0, "devkit": 1, "saved": 2, "scan": 3}
|
||||
LINK_RANK = {"USB": 0, "Frame hotspot": 1, "network": 2} # fastest first (USB ~37 MB/s, hotspot ~85, but the hotspot
|
||||
# needs the PC on the Frame's Wi-Fi: when both answer, the cable is the deliberate choice)
|
||||
|
||||
|
||||
def dedupe(found: list[Found], key_of=None) -> list[Found]:
|
||||
"""One entry per Frame: entries whose SSH host key matches (the same device reached over home Wi-Fi, its hotspot
|
||||
and USB, or found by mDNS, the saved list and the network scan) merge into one that uses the fastest link, keeps
|
||||
the best-known source/name and lists the other addresses. Entries whose key can't be read stay as they are."""
|
||||
if key_of is None:
|
||||
from .connection import server_key
|
||||
|
||||
def key_of(f: Found):
|
||||
k = server_key(f.host, f.port, timeout=3)
|
||||
return k.get_base64() if k else None
|
||||
with ThreadPoolExecutor(16) as pool:
|
||||
keys = list(pool.map(key_of, found))
|
||||
groups: dict[str, list[Found]] = {}
|
||||
out = []
|
||||
for f, k in zip(found, keys, strict=True):
|
||||
if k is None:
|
||||
out.append(f)
|
||||
else:
|
||||
groups.setdefault(k, []).append(f)
|
||||
for members in groups.values():
|
||||
best = min(members, key=lambda f: (LINK_RANK.get(f.via, 9), f.host))
|
||||
named = min(members, key=lambda f: (SOURCE_RANK.get(f.source, 9), f.source == "scan"))
|
||||
addresses = list(dict.fromkeys([best.host] + [a for f in members for a in [f.host, *f.addresses]]))
|
||||
out.append(Found(named.name if named.source != "scan" else best.name, best.host, best.port, named.user,
|
||||
named.source, addresses, {**best.properties, **named.properties}))
|
||||
return out
|
||||
|
||||
|
||||
def local_ip_towards(host: str = "8.8.8.8") -> str:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""FramePort running on the Steam Frame itself (Desktop Mode, the Linux ARM64 bundle): it manages the same device over
|
||||
SSH to 127.0.0.1, so everything else (agent, installs, launch tests) works unchanged. Developer Mode has to be on for
|
||||
sshd; FramePort authorizes its own key for the local user, no pairing needed."""
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import getpass
|
||||
import os
|
||||
import platform
|
||||
from pathlib import Path
|
||||
|
||||
LOCAL_NAME = "This Frame (experimental)" # FramePort running on the Frame itself
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def on_frame() -> bool:
|
||||
"""SteamOS on ARM64 (the Steam Frame)."""
|
||||
if platform.machine().lower() not in ("aarch64", "arm64"):
|
||||
return False
|
||||
try:
|
||||
text = Path("/etc/os-release").read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return False
|
||||
return any(line.strip().lower() in ("id=steamos", 'id="steamos"') for line in text.splitlines())
|
||||
|
||||
|
||||
def authorize_self(public_key: str) -> bool:
|
||||
"""Add FramePort's public key to this user's ~/.ssh/authorized_keys (once). True if it was added."""
|
||||
ssh = Path.home() / ".ssh"
|
||||
keys = ssh / "authorized_keys"
|
||||
ssh.mkdir(mode=0o700, exist_ok=True)
|
||||
have = keys.read_text(encoding="utf-8", errors="replace") if keys.exists() else ""
|
||||
if public_key.strip() in have:
|
||||
return False
|
||||
with open(keys, "a", encoding="utf-8") as f:
|
||||
f.write(("" if not have or have.endswith("\n") else "\n") + public_key.strip() + " frameport-local\n")
|
||||
os.chmod(keys, 0o600)
|
||||
return True
|
||||
|
||||
|
||||
def local_user() -> str:
|
||||
try:
|
||||
return getpass.getuser()
|
||||
except Exception: # noqa: BLE001
|
||||
return "steamos"
|
||||
@@ -102,11 +102,13 @@ class PairingServer:
|
||||
requests: int = 0 # requests from the network (right or wrong code): the Frame can reach us
|
||||
flag: Path | None = None # WSL: the temporary firewall rule stays while this file exists
|
||||
hint: str = "" # set by the UI when nothing reached us after HINT_AFTER seconds: what may block the Frame
|
||||
host: str = "" # the address the Frame uses to reach this PC; "" = the PC's address towards the internet. The USB
|
||||
# setup uses the cable's fixed PC address (10.86.200.234), so no Wi-Fi, router or discovery is involved
|
||||
_httpd: http.server.ThreadingHTTPServer | None = None
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return f"http://{local_ip_towards()}:{self.port}"
|
||||
return f"http://{self.host or local_ip_towards()}:{self.port}"
|
||||
|
||||
@property
|
||||
def one_liner(self) -> str:
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""USB cable link to the Frame (usb0, a USB network gadget): one check that answers whether "connect with a USB
|
||||
cable" can work on this PC: what the Frame presents, whether this PC got an address on it, whether SSH answers
|
||||
over it (same host key), and how fast an upload is compared with the normal connection."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
USB_IFACE = "usb0"
|
||||
FRAME_USB_IP, PC_USB_IP = "10.86.200.233", "10.86.200.234" # fixed by the Frame's dnsmasq (dhcp-host by MAC)
|
||||
TEST_BYTES = 128 << 20
|
||||
|
||||
|
||||
def pc_usb_addresses(frame_ip: str) -> list[str]:
|
||||
"""This PC's IPv4 addresses in the same /24 as the Frame's USB address (Windows via ipconfig, else `ip`)."""
|
||||
prefix = frame_ip.rsplit(".", 1)[0] + "."
|
||||
texts = []
|
||||
for cmd in (["ip", "-4", "-o", "addr", "show"], ["ipconfig"], ["ifconfig"], ["ipconfig.exe"]):
|
||||
try:
|
||||
texts.append(subprocess.run(cmd, capture_output=True, text=True, timeout=10).stdout)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
text = "\n".join(texts)
|
||||
# interface addresses only (`ip`/ifconfig "inet X", ipconfig "IPv4 Address ... : X"): not broadcast/netmask values
|
||||
found = re.findall(r"\binet\s+(\d+\.\d+\.\d+\.\d+)", text) + \
|
||||
re.findall(r"IPv4[^:\n]*:\s*(\d+\.\d+\.\d+\.\d+)", text)
|
||||
return sorted({ip for ip in found if ip.startswith(prefix) and ip != frame_ip})
|
||||
|
||||
|
||||
def upload_speed(frame, size: int = TEST_BYTES) -> float:
|
||||
"""MB/s of one SFTP upload of `size` bytes to /tmp on the Frame (removed afterwards)."""
|
||||
path = f"/tmp/frameport-speed-{os.getpid()}"
|
||||
data = io.BytesIO(os.urandom(1 << 20) * (size >> 20))
|
||||
start = time.time()
|
||||
frame.sftp.putfo(data, path)
|
||||
elapsed = time.time() - start
|
||||
frame.run(f"rm -f {path}")
|
||||
return size / elapsed / 1e6
|
||||
|
||||
|
||||
def check(frame, measure: bool = True) -> dict:
|
||||
"""{frame: <agent usb_link>, frame_ip, pc_addresses, reachable, same_frame, speed_usb, speed_default, notes}."""
|
||||
info = frame.agent("usb_link", timeout=60)
|
||||
out = {"frame": info, "platform": sys.platform, "notes": []}
|
||||
ip = next((a.split("/")[0] for a in info.get("addresses") or []), None)
|
||||
out["frame_ip"] = ip
|
||||
if not info.get("present"):
|
||||
out["notes"].append("The Frame has no usb0 link: is the cable in the Frame's USB-C port and the PC?")
|
||||
return out
|
||||
if not ip:
|
||||
out["notes"].append("usb0 exists but has no address on the Frame (cable not connected to a PC?)")
|
||||
return out
|
||||
out["pc_addresses"] = pc_usb_addresses(ip)
|
||||
if not out["pc_addresses"]:
|
||||
out["notes"].append("This PC has no address on the Frame's USB network: no driver for the gadget "
|
||||
f"({', '.join(info.get('functions') or []) or 'unknown type'}) or no DHCP from the Frame")
|
||||
try:
|
||||
socket.create_connection((ip, frame.target.port), timeout=3).close()
|
||||
out["reachable"] = True
|
||||
except OSError:
|
||||
out["reachable"] = False
|
||||
out["notes"].append(f"SSH ({ip}:{frame.target.port}) doesn't answer over the cable from this PC")
|
||||
return out
|
||||
from .connection import Frame, FrameTarget
|
||||
|
||||
other = Frame(FrameTarget(ip, frame.target.user, frame.target.port), frame.password)
|
||||
try:
|
||||
other.connect(timeout=10)
|
||||
out["same_frame"] = (other.client.get_transport().get_remote_server_key()
|
||||
== frame.client.get_transport().get_remote_server_key())
|
||||
if measure:
|
||||
out["speed_usb"] = round(upload_speed(other), 1)
|
||||
out["speed_default"] = round(upload_speed(frame), 1)
|
||||
finally:
|
||||
other.close()
|
||||
return out
|
||||
@@ -210,13 +210,64 @@ def install_pcvr(frame: Frame, plan: PcvrPlan, reporter: Reporter) -> dict:
|
||||
env=launch_env(plan.recipe),
|
||||
game_args=game_args(plan.recipe), no_crash_reporter="pcvr.no_crash_reporter" in plan.recipe.patches,
|
||||
libovr_redirect="pcvr.libovr_redirect" in plan.recipe.patches,
|
||||
exe_sha256=plan.exe_sha256, revive_version=plan.revive_version,
|
||||
exe_sha256=plan.exe_sha256, revive_version=plan.revive_version, vr=not is_flat_windows(plan.package),
|
||||
recipe={"patches": sorted(plan.recipe.patches), "source": plan.recipe.source},
|
||||
)
|
||||
reporter.log(f"installed at {result['base']} (Proton {result['proton']}, Steam shortcut id {result['appid']})")
|
||||
return result
|
||||
|
||||
|
||||
@dataclass
|
||||
class LinuxPlan:
|
||||
package: str # "linux.<slug>"
|
||||
title: str
|
||||
root: Path # the app's folder (for a lone AppImage: the folder it's in, with files = [its name])
|
||||
exe: str # relative to root
|
||||
files: list[str] | None = None # only these files of root (a lone AppImage), else the whole folder
|
||||
appimage: bool = False
|
||||
openxr: bool = False
|
||||
|
||||
|
||||
def install_linux(frame: Frame, plan: LinuxPlan, reporter: Reporter) -> dict:
|
||||
"""Upload an arm64 Linux app to the Frame (resumable, unchanged files aren't re-sent); the agent extracts
|
||||
AppImages, checks the app's libraries and writes its launcher (GitHub #31)."""
|
||||
reporter.stage("Prepare Frame")
|
||||
prep = frame.agent("prepare_linux", package=plan.package, title=plan.title)
|
||||
if plan.files:
|
||||
manifest = {name: (plan.root / name).stat().st_size for name in plan.files}
|
||||
else:
|
||||
manifest = local_data_manifest(plan.root)
|
||||
manifest = {k: v for k, v in manifest.items() if not k.startswith(".unpacked")}
|
||||
to_send = [rel for rel, size in manifest.items() if prep["existing"].get("app", {}).get(rel) != size]
|
||||
need = sum(manifest[rel] for rel in to_send)
|
||||
if need > prep["free_bytes"] - (1 << 30):
|
||||
raise RuntimeError(f"not enough space on the Frame: need {need / 2**30:.1f} GiB + 1 GiB headroom, "
|
||||
f"have {prep['free_bytes'] / 2**30:.1f} GiB")
|
||||
if to_send:
|
||||
reporter.stage(f"Upload app ({len(to_send)} files, {need / 2**20:.0f} MiB)")
|
||||
with transfer_link(frame, reporter, need) as xfer:
|
||||
upload_files(xfer, [(plan.root / rel, f"app/{rel}", manifest[rel]) for rel in to_send],
|
||||
prep["incoming"], reporter, max(need, 1), 0)
|
||||
else:
|
||||
reporter.log("all app files already on the Frame; not re-sending")
|
||||
upload_steam_art(frame, plan.package, prep["base"], reporter)
|
||||
reporter.stage("Finalize install")
|
||||
executables = [rel for rel in manifest if rel != plan.exe and _is_elf(plan.root / rel)][:200]
|
||||
result = frame.agent("finalize_linux", package=plan.package, title=plan.title, exe=plan.exe,
|
||||
appimage=plan.appimage, openxr=plan.openxr, manifests={"app": manifest},
|
||||
executables=executables, tags=_tags(plan.package), timeout=900)
|
||||
reporter.log(f"installed at {result['base']} (Steam shortcut id {result['appid']})")
|
||||
return result
|
||||
|
||||
|
||||
def _is_elf(path: Path) -> bool:
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
return f.read(4) == b"\x7fELF"
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def ensure_proton(frame: Frame, reporter: Reporter, tool: str | None = None, timeout: float = 45 * 60) -> dict:
|
||||
"""Install Proton (ARM64) + its runtime on the Frame without user interaction: the agent writes Steam appmanifest
|
||||
stubs and restarts Steam, which downloads them. Waits until they're installed (progress from the appmanifests)."""
|
||||
@@ -230,6 +281,7 @@ def ensure_proton(frame: Frame, reporter: Reporter, tool: str | None = None, tim
|
||||
reporter.log(r.get("hint") or f"installing {r.get('tool')}")
|
||||
end = time.time() + timeout
|
||||
last = None
|
||||
asked_runtime = False
|
||||
while time.time() < end:
|
||||
reporter.check_cancel()
|
||||
time.sleep(10)
|
||||
@@ -241,6 +293,14 @@ def ensure_proton(frame: Frame, reporter: Reporter, tool: str | None = None, tim
|
||||
reporter.check("Proton installed", True, st["ready"]["display_name"])
|
||||
return st["ready"]
|
||||
dl = st.get("download") or {}
|
||||
sug = st.get("suggested") or {}
|
||||
if sug.get("installed") and not sug.get("require_installed") and not dl.get("total") and not asked_runtime:
|
||||
# Steam names the runtime a Proton needs (e.g. Experimental) only once Proton itself is installed: ask
|
||||
# for it now
|
||||
asked_runtime = True
|
||||
reporter.log("installing the Steam Linux Runtime this Proton needs")
|
||||
frame.agent("install_proton", mode="unattended", tool=tool)
|
||||
continue
|
||||
if dl.get("total"):
|
||||
reporter.progress(dl["done"] / dl["total"], f"downloading Proton {dl['done'] / 2**20:.0f}/"
|
||||
f"{dl['total'] / 2**20:.0f} MiB")
|
||||
@@ -325,6 +385,14 @@ def _tags(package: str) -> list[str]:
|
||||
return steam_tags(entry) if entry else []
|
||||
|
||||
|
||||
def is_flat_windows(package: str) -> bool:
|
||||
"""A Windows game without VR (added with "Add one game folder…"): Proton runs it as a window, no VR setup."""
|
||||
from ..core import library
|
||||
|
||||
g = library.game(package) or {}
|
||||
return bool(((g.get("analysis") or {}).get("extra") or {}).get("flat"))
|
||||
|
||||
|
||||
def _flatscreen(package: str) -> bool:
|
||||
"""An Android app without VR: Lepton must show it as a flat window (it never draws through OpenXR)."""
|
||||
from ..core import library
|
||||
@@ -384,8 +452,19 @@ def add_to_steam(frame: Frame, packages: list[str], reporter: Reporter, wait: fl
|
||||
continue
|
||||
if status.get("state") in ("done", "failed"):
|
||||
break
|
||||
if status.get("state") == "waiting": # Steam restarts later: after the game, or back in Gaming Mode
|
||||
reporter.check("Steam library", None,
|
||||
"added when you're back in Gaming Mode (Steam has to restart for it)"
|
||||
if status.get("reason") == "desktop" else
|
||||
"added when the game that's running now is closed (Steam has to restart for it)")
|
||||
return status
|
||||
added = {a["package"] for a in status.get("added", [])}
|
||||
for a in status.get("added", []):
|
||||
reporter.check(f"Steam library: {a['package']}", True, f"shortcut {a['appid']}")
|
||||
for e in status.get("errors", []):
|
||||
reporter.check("Steam library", False, e)
|
||||
if not status.get("errors"):
|
||||
for pkg in packages:
|
||||
if pkg not in added: # no answer in time: say so (Play adds a missing shortcut itself)
|
||||
reporter.check(f"Steam library: {pkg}", False, "the Frame didn't confirm the library entry in time")
|
||||
return status
|
||||
@@ -0,0 +1,138 @@
|
||||
# ruff: noqa: E501 (the embedded page's JavaScript)
|
||||
"""The Live view player page (served by livestream.py). A Python string rather than an .html file: the
|
||||
PyInstaller fallback bundle only carries data files it is told about."""
|
||||
|
||||
PLAYER_HTML = r"""<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>FramePort Live view</title>
|
||||
<style>
|
||||
:root { --bg: #0e1013; --text: #e8eaed; --muted: #9aa0a6; --accent: #66b3ff; --panel: rgba(20, 22, 26, .82); }
|
||||
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text);
|
||||
font: 14px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; overflow: hidden; }
|
||||
video { position: fixed; inset: 0; width: 100%; height: 100%; object-fit: contain; background: #000; }
|
||||
#bar { position: fixed; left: 12px; right: 12px; bottom: 12px; display: flex; gap: 12px; align-items: center;
|
||||
padding: 8px 12px; border-radius: 10px; background: var(--panel); transition: opacity .3s; }
|
||||
body.idle #bar { opacity: 0; }
|
||||
#dot { width: 9px; height: 9px; border-radius: 50%; background: var(--muted); flex: none; }
|
||||
#dot.live { background: #3ddc84; } #dot.err { background: #ff6b6b; }
|
||||
#msg { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
#info { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
button { background: transparent; color: var(--text); border: 1px solid #3c4043; border-radius: 6px;
|
||||
padding: 4px 10px; font: inherit; cursor: pointer; }
|
||||
button:hover { border-color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<video id="v" muted autoplay playsinline disablepictureinpicture></video>
|
||||
<div id="bar">
|
||||
<span id="dot"></span><span id="msg">Connecting to the Frame…</span><span id="info"></span>
|
||||
<button id="snd" hidden title="Browsers start videos muted: click to hear the Frame">Sound on</button>
|
||||
<button id="fs" title="Full screen (or double-click the picture)">Full screen</button>
|
||||
</div>
|
||||
<script>
|
||||
"use strict";
|
||||
const video = document.getElementById("v"), dot = document.getElementById("dot");
|
||||
const msg = document.getElementById("msg"), info = document.getElementById("info");
|
||||
const CUSHION = 0.3, CATCH_UP = 0.7, FAR_BEHIND = 2.0, KEEP = 10; // seconds behind the newest data
|
||||
let session = 0, frames = 0, lastFrames = 0, size = "";
|
||||
|
||||
function say(text, state) { msg.textContent = text; dot.className = state || ""; }
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
async function status() {
|
||||
try { const r = await fetch("status", {cache: "no-store"}); return await r.json(); }
|
||||
catch (e) { return null; }
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const id = ++session;
|
||||
let st = await status();
|
||||
while (id === session && (!st || !st.ready)) {
|
||||
if (st && st.ended) { say("Stopped: " + st.ended + " — start it again in FramePort.", "err"); return; }
|
||||
if (!st) { say("FramePort isn't streaming any more. Start Live view in FramePort.", "err"); return; }
|
||||
say("Waiting for the first picture from the Frame…");
|
||||
await sleep(500); st = await status();
|
||||
}
|
||||
const type = 'video/mp4; codecs="' + (st.codec || "avc1.640028") + '"';
|
||||
const MS = window.ManagedMediaSource || window.MediaSource;
|
||||
if (!MS || !MS.isTypeSupported(type)) { say("This browser can't play H.264 video (" + type + "). Copy this page's address into another browser.", "err"); return; }
|
||||
size = st.width ? st.width + "×" + st.height : "";
|
||||
snd.hidden = !st.audio;
|
||||
const ms = new MS();
|
||||
video.disableRemotePlayback = true;
|
||||
video.src = URL.createObjectURL(ms);
|
||||
await new Promise(r => ms.addEventListener("sourceopen", r, {once: true}));
|
||||
const sb = ms.addSourceBuffer(type);
|
||||
sb.mode = "segments";
|
||||
const pending = [];
|
||||
const pump = () => {
|
||||
if (sb.updating || !pending.length || ms.readyState !== "open") return;
|
||||
try { sb.appendBuffer(pending.shift()); } catch (e) { trim(true); }
|
||||
};
|
||||
const trim = (force) => {
|
||||
if (sb.updating || !sb.buffered.length) return;
|
||||
const start = sb.buffered.start(0), cut = video.currentTime - (force ? 1 : KEEP);
|
||||
if (cut > start) { try { sb.remove(start, cut); } catch (e) {} }
|
||||
};
|
||||
sb.addEventListener("updateend", () => {
|
||||
if (sb.buffered.length) {
|
||||
const end = sb.buffered.end(sb.buffered.length - 1);
|
||||
const lag = end - video.currentTime;
|
||||
if (lag > FAR_BEHIND || video.currentTime < sb.buffered.start(0)) video.currentTime = Math.max(end - CUSHION, 0);
|
||||
else video.playbackRate = lag > CATCH_UP ? 1.1 : lag < CUSHION ? 1.0 : video.playbackRate;
|
||||
if (video.paused) video.play().catch(() => {});
|
||||
}
|
||||
pump();
|
||||
});
|
||||
try {
|
||||
const resp = await fetch("stream.mp4", {cache: "no-store"});
|
||||
if (!resp.ok) throw new Error(await resp.text());
|
||||
say("Live from the Frame", "live");
|
||||
const reader = resp.body.getReader();
|
||||
let n = 0;
|
||||
while (id === session) {
|
||||
const {value, done} = await reader.read();
|
||||
if (done) break;
|
||||
pending.push(value); frames++;
|
||||
if (++n % 60 === 0) trim(false);
|
||||
pump();
|
||||
}
|
||||
} catch (e) {
|
||||
say("Connection lost (" + e.message + "), reconnecting…", "err");
|
||||
}
|
||||
if (id !== session) return;
|
||||
await sleep(1000);
|
||||
const again = await status();
|
||||
if (again && again.ended) { say("Stopped: " + again.ended + " — start it again in FramePort.", "err"); return; }
|
||||
run();
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
const chunks = frames - lastFrames; lastFrames = frames;
|
||||
info.textContent = [size, chunks ? "receiving" : ""].filter(Boolean).join(" · ");
|
||||
}, 1000);
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) run(); });
|
||||
const toggleFs = () => document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen();
|
||||
document.getElementById("fs").onclick = toggleFs;
|
||||
const snd = document.getElementById("snd");
|
||||
let wantSound = false; // the choice survives reconnects (each one makes a new MediaSource)
|
||||
snd.onclick = () => {
|
||||
wantSound = !wantSound; video.muted = !wantSound;
|
||||
snd.textContent = wantSound ? "Mute" : "Sound on";
|
||||
if (wantSound) video.play().catch(() => {});
|
||||
};
|
||||
video.addEventListener("loadedmetadata", () => { video.muted = !wantSound; });
|
||||
video.ondblclick = toggleFs;
|
||||
let idle;
|
||||
document.addEventListener("mousemove", () => {
|
||||
document.body.classList.remove("idle"); clearTimeout(idle);
|
||||
idle = setTimeout(() => document.body.classList.add("idle"), 2500);
|
||||
});
|
||||
run();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user