vr: add OpenXR headset output, VR tracker and VR controller input behind --vr #1726

Closed
github-bot wants to merge 2 commits from gh-pr/1726/head into gh-pr/1726/base
Owner

@⁠LeandroSWR on GitHub · 2026-10-19 17:20 UTC · original
LeandroSWR:vr/openxr-support → main · +18 −1 · 3 files · 2 commits · closed without merging

Adds what a PSVR2 game needs to run on a real headset through OpenXR. All of the VR code is gated on --vr (the virtual headset introduced earlier); without it nothing changes for any title. Includes two small GPU fixes that the first game I tested needed to stay alive.

What it does

Headset output

  • The game's eye images are copied into an OpenXR session (Windows, Vulkan binding) and shown as a world-locked layer at the head pose the game last read, so the picture stays put while the head moves.
  • The headset swapchain registered through VideoOutRegisterBuffers2 is handled, including titles that flip the headset port before registering it. The HMD2 port shares the presentation layers with the main output.
  • The render thread waits on the GPU tick from the CPU before submitting the headset copy, to avoid a wait-before-signal deadlock on the same queue.
  • With --vr the eye image is also shown in the desktop window, so the picture is visible without a headset. KYTY_OPENXR=0 turns the headset path off completely.
  • The OpenXR loader is built statically from KhronosGroup/OpenXR-SDK (release-1.1.63), Windows only. The runtime comes from the user's system (Virtual Desktop, SteamVR, ...). The code is guarded so builds without OpenXR still compile.

Input

  • New libSceVrTracker2 (QueryMemory, Initialize, RegisterDevice, GetResult). Head and controller poses come from OpenXR, laid out the way the game reads the result.
  • libPad gets the left/right VR controller ports (port types 3 and 4), VR controller state and the trigger-effect entry points. The VR handles (0x10, 0x11) sit outside the per-player handle range; the tracker names a controller by this handle, so both share the constants in controller.h.
  • The right controller reports the Options button from the left Quest menu button, so calibration screens can be passed.
  • libHmd2: Open, reprojection frame, predicted display time, gaze and timing calls.

GPU fixes (first two commits, independent of VR)

  • shader: shrink the per-invocation LDS array for non-compute stages — stages without a workgroup emulate LDS with one private array per invocation. The previous size (8192 dwords) multiplied across the invocations in flight into gigabytes of driver local memory and killed the device. 1024 dwords is enough for the lane-id-plus-small-offset addressing these shaders use; accesses beyond it were already bounds-checked.
  • graphics: zero-initialize the BDA page table — device-local memory is uninitialized, so a missing entry must read as zero and fault in the shader instead of following a garbage pointer.

Testing

  • Windows build (clang-cl) compiles and links on top of current main.
  • Tested with a UE5 PSVR2 (Synapse PPSA12507) title on a Steam Frame through SteamVR (and earlier on a Quest 3 through Virtual Desktop): head tracking, both controllers, buttons, sticks and triggers work, the picture is shown in the headset and in the desktop window, and it runs for a full session without a crash.
  • Without the two GPU commits that title dies within about 45 seconds with a Vulkan device-lost error, which is why they are in this PR.
  • Not tested: Linux (the OpenXR code is compiled out and has a no-op fallback, but I have not built it), other headsets or OpenXR runtimes, and any other game.

Limitations

  • Only one title has been used. The VrTracker2 result layout was worked out from that title's consumer code, so other titles may read it differently.
  • Two HMD2 functions are still stubs under unidentified names (hA9LshbSkzw, retc+-uRMhk).
  • A second title (a Unity game that loads Sony's psvr2.prx plugin) starts but shows no picture. It calls six functions that are not implemented here and describes its headset swapchain differently. That is left for a follow-up.
  • Games that use Sony's hardware foveated shading (the FSR registers) will look low resolution or show ghosting, since those registers are accepted and ignored. Not part of this PR.
  • No automated tests; verification was by running the game.

Video

Note: This video has some extra patches that are game specific for correct rendering that are not part of this PR.

https://github.com/user-attachments/assets/cca45a5c-1113-46a0-803e-1b360f210d0b

**@⁠LeandroSWR** on GitHub · 2026-10-19 17:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726) `LeandroSWR:vr/openxr-support` → `main` · +18 −1 · 3 files · 2 commits · closed without merging Adds what a PSVR2 game needs to run on a real headset through OpenXR. All of the VR code is gated on `--vr` (the virtual headset introduced earlier); without it nothing changes for any title. Includes two small GPU fixes that the first game I tested needed to stay alive. ## What it does **Headset output** - The game's eye images are copied into an OpenXR session (Windows, Vulkan binding) and shown as a world-locked layer at the head pose the game last read, so the picture stays put while the head moves. - The headset swapchain registered through `VideoOutRegisterBuffers2` is handled, including titles that flip the headset port before registering it. The HMD2 port shares the presentation layers with the main output. - The render thread waits on the GPU tick from the CPU before submitting the headset copy, to avoid a wait-before-signal deadlock on the same queue. - With `--vr` the eye image is also shown in the desktop window, so the picture is visible without a headset. `KYTY_OPENXR=0` turns the headset path off completely. - The OpenXR loader is built statically from KhronosGroup/OpenXR-SDK (release-1.1.63), Windows only. The runtime comes from the user's system (Virtual Desktop, SteamVR, ...). The code is guarded so builds without OpenXR still compile. **Input** - New `libSceVrTracker2` (QueryMemory, Initialize, RegisterDevice, GetResult). Head and controller poses come from OpenXR, laid out the way the game reads the result. - `libPad` gets the left/right VR controller ports (port types 3 and 4), VR controller state and the trigger-effect entry points. The VR handles (`0x10`, `0x11`) sit outside the per-player handle range; the tracker names a controller by this handle, so both share the constants in `controller.h`. - The right controller reports the Options button from the left Quest menu button, so calibration screens can be passed. - `libHmd2`: Open, reprojection frame, predicted display time, gaze and timing calls. **GPU fixes (first two commits, independent of VR)** - `shader: shrink the per-invocation LDS array for non-compute stages` — stages without a workgroup emulate LDS with one private array per invocation. The previous size (8192 dwords) multiplied across the invocations in flight into gigabytes of driver local memory and killed the device. 1024 dwords is enough for the lane-id-plus-small-offset addressing these shaders use; accesses beyond it were already bounds-checked. - `graphics: zero-initialize the BDA page table` — device-local memory is uninitialized, so a missing entry must read as zero and fault in the shader instead of following a garbage pointer. ## Testing - Windows build (clang-cl) compiles and links on top of current `main`. - Tested with a UE5 PSVR2 (Synapse PPSA12507) title on a Steam Frame through SteamVR (and earlier on a Quest 3 through Virtual Desktop): head tracking, both controllers, buttons, sticks and triggers work, the picture is shown in the headset and in the desktop window, and it runs for a full session without a crash. - Without the two GPU commits that title dies within about 45 seconds with a Vulkan device-lost error, which is why they are in this PR. - Not tested: Linux (the OpenXR code is compiled out and has a no-op fallback, but I have not built it), other headsets or OpenXR runtimes, and any other game. ## Limitations - Only one title has been used. The VrTracker2 result layout was worked out from that title's consumer code, so other titles may read it differently. - Two HMD2 functions are still stubs under unidentified names (`hA9LshbSkzw`, `retc+-uRMhk`). - A second title (a Unity game that loads Sony's `psvr2.prx` plugin) starts but shows no picture. It calls six functions that are not implemented here and describes its headset swapchain differently. That is left for a follow-up. - Games that use Sony's hardware foveated shading (the FSR registers) will look low resolution or show ghosting, since those registers are accepted and ignored. Not part of this PR. - No automated tests; verification was by running the game. ## Video **Note:** This video has some extra patches that are game specific for correct rendering that are not part of this PR. https://github.com/user-attachments/assets/cca45a5c-1113-46a0-803e-1b360f210d0b
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:03:49 +00:00
github-bot closed this pull request 2026-11-26 10:03:49 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original · edited 2026-10-20 00:24 UTC

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 56b39189-9f0c-47f9-a63a-d2f53a2663ee
📥 Commits

Reviewing files that changed from the base of the PR and between 5eaf7635cd7c4bbb6c20f098212c54db292f1123 and 64476cf419.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

The changes add Windows OpenXR support and connect headset image presentation, HMD2 video output, and VR controller and tracker APIs. They also add one-time buffer-device-address page-table initialization and reduce the shader LDS fallback allocation for stages without workgroup input.

Suggested reviewers: nmzik, pipe530

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟡 Moderate · up to 5eaf7

With VR enabled, this change can crash the emulator during headset buffer registration or compute preview, and can overwrite unrelated game memory through HMD2 result calls. Fix these before merging. Several smaller VR input-state gaps can also be fixed in this change. Non-VR use is mostly unaffected.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 23.20% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 125 functions across 21 files. (2 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description check Passed The description clearly explains the OpenXR headset output, VR tracker and controller input, HMD2 support, GPU fixes, testing, and known limitations.
Title check Passed The title clearly identifies the primary change: OpenXR headset output, VR tracker support, and VR controller input behind --vr.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 23.20% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 125 functions across 21 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#issuecomment-6273717023) · edited 2026-10-20 00:24 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1726?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: skip review by coderabbit.ai --> > [!IMPORTANT] > ## Review skipped > > Review was skipped as selected files did not have any reviewable changes. > > > > > > <details> > <summary><strong>⚙️ Run configuration</strong></summary> > <dl> > <dd> > > - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml > - **Review profile**: CHILL > - **Plan**: Advanced > - **Run ID**: `56b39189-9f0c-47f9-a63a-d2f53a2663ee` > > </dd> > </dl> > </details> > > <details> > <summary><strong>📥 Commits</strong></summary> > <dl> > <dd> > > Reviewing files that changed from the base of the PR and between 5eaf7635cd7c4bbb6c20f098212c54db292f1123 and 64476cf41921a591bbb9da313051fac348fd2eb4. > > </dd> > </dl> > </details> > > You can disable this status message by setting the `reviews.review_status` to `false` in the CodeRabbit configuration file. > > Use the checkbox below for a quick retry: > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: skip review by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The changes add Windows OpenXR support and connect headset image presentation, HMD2 video output, and VR controller and tracker APIs. They also add one-time buffer-device-address page-table initialization and reduce the shader LDS fallback allocation for stages without workgroup input. **Suggested reviewers:** `nmzik`, `pipe530` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"5eaf7635cd7c4bbb6c20f098212c54db292f1123" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🟡 Moderate</strong> · up to <code>5eaf7</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `5eaf7` --> <!-- final_review_risk_coverage:{"sourceCommitId":"5eaf7635cd7c4bbb6c20f098212c54db292f1123","coveredCommitId":"5eaf7635cd7c4bbb6c20f098212c54db292f1123","kind":"reviewed"} --> With VR enabled, this change can crash the emulator during headset buffer registration or compute preview, and can overwrite unrelated game memory through HMD2 result calls. Fix these before merging. Several smaller VR input-state gaps can also be fixed in this change. Non-VR use is mostly unaffected. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 23.20% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 125 functions across 21 files. (2 skipped… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the OpenXR headset output, VR tracker and controller input, HMD2 support, GPU fixes, testing, and known limitations. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly identifies the primary change: OpenXR headset output, VR tracker support, and VR controller input behind --vr. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 23.20% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 125 functions across 21 files. (2 skipped: 2 unsupported.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1726)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/graphics/host_gpu/renderer/renderCompute.cpp line 372 (outdated):

@@ -364,6 +365,11 @@ void RenderExecutor::DispatchDirect(uint64_t submit_id, CommandBuffer& buffer,
 		m_context.PrepareBda();
 	}
 	RebindImages(bindings);
+	for (size_t i = 0; HeadsetPreviewEnabled() && i < program.info.images.size(); i++) {
+		if (program.info.images[i].written) {
+			HeadsetPreviewNote(m_context.GetTextureCache().GetImage(bindings.images[i].image_id).info);
+		}
+	}

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Check how compute bindings.images is filled and whether image_id can be null.
rg -nP -C6 '\bvoid\s+RenderExecutor::(PrepareBindings|RebindImages)\s*\(' --type=cpp
rg -nP -C4 '\bimages\s*(\.|\[)' -g '*renderBindings*' -g '*renderExecutor*'
rg -nP -C8 '\bGetImage\s*\(\s*(Image|Slot)?Id' --type=cpp -g '*textureCache*'

Repository: KytyPS5/KytyPS5

Length of output: 4551


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- renderCompute preview and dispatch context ---'
rg -n -C12 -F -- 'HeadsetPreviewNote' src/graphics/host_gpu/renderer/renderCompute.cpp
printf '%s\n' '--- descriptor declarations ---'
rg -n -C8 -F -e 'struct PreparedBindings' -e 'class PreparedBindings' -e 'struct ImageBinding' -e 'class RenderExecutor' src/graphics/host_gpu/renderer
printf '%s\n' '--- complete PrepareBindings/RebindImages blocks ---'
sed -n '687,875p' src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
printf '%s\n' '--- ImageId declaration and null checks ---'
rg -n -C8 -F -e 'using ImageId' -e 'typedef.*ImageId' -e 'ImageId image_id' -e 'image_id)' -e '!.*image_id' src/graphics/host_gpu/renderer
printf '%s\n' '--- relevant draw guard ---'
rg -n -C10 -F -- 'EXIT_IF(!target.image_id)' src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 41544


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- ResolveTexture declarations and implementation ---'
rg -n -C12 -F -e 'ResolveTexture' src/graphics/host_gpu/renderer
printf '%s\n' '--- ImageId and SlotId definitions ---'
rg -n -C10 -F -e 'using ImageId' -e 'using SlotId' -e 'class SlotId' -e 'struct SlotId' -e 'SlotId' src/graphics/host_gpu/renderer src/common
printf '%s\n' '--- resource image metadata and descriptor resolution inputs ---'
rg -n -C8 -F -e 'struct ShaderImage' -e 'struct ImageInfo' -e 'struct ImageDesc' -e 'snapshot.images' src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 37285


🏁 Script executed:

nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '477,570p'

Repository: KytyPS5/KytyPS5

Length of output: 6294


Guard null image IDs before headset preview.

When a written compute image has a null descriptor, ResolveTexture leaves image_id empty. RebindImages skips that binding, but the preview loop still calls GetImage with the empty ID. GetImage rejects the invalid slot and can stop the emulator when VR preview is enabled.

The binding-size mismatch is already rejected by RebindImages, so only the image-ID guard is needed.

🛡️ Suggested fix
--- "a/src/graphics/host_gpu/renderer/renderCompute.cpp"
+++ "b/src/graphics/host_gpu/renderer/renderCompute.cpp"
@@ -365,11 +365,11 @@
 		m_context.PrepareBda();
 	}
 	RebindImages(bindings);
 	for (size_t i = 0; HeadsetPreviewEnabled() && i < program.info.images.size(); i++) {
-		if (program.info.images[i].written) {
+		if (program.info.images[i].written && bindings.images[i].image_id) {
 			HeadsetPreviewNote(m_context.GetTextureCache().GetImage(bindings.images[i].image_id).info);
 		}
 	}
 	BindSharedMemory(m_context, input_info, bindings);
 	RebindBuffers(bindings);
 
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	for (size_t i = 0; HeadsetPreviewEnabled() && i < program.info.images.size(); i++) {
		if (program.info.images[i].written && bindings.images[i].image_id) {
			HeadsetPreviewNote(m_context.GetTextureCache().GetImage(bindings.images[i].image_id).info);
		}
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070161) On `src/graphics/host_gpu/renderer/renderCompute.cpp` line 372 (outdated): ```diff @@ -364,6 +365,11 @@ void RenderExecutor::DispatchDirect(uint64_t submit_id, CommandBuffer& buffer, m_context.PrepareBda(); } RebindImages(bindings); + for (size_t i = 0; HeadsetPreviewEnabled() && i < program.info.images.size(); i++) { + if (program.info.images[i].written) { + HeadsetPreviewNote(m_context.GetTextureCache().GetImage(bindings.images[i].image_id).info); + } + } ``` **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Check how compute bindings.images is filled and whether image_id can be null. rg -nP -C6 '\bvoid\s+RenderExecutor::(PrepareBindings|RebindImages)\s*\(' --type=cpp rg -nP -C4 '\bimages\s*(\.|\[)' -g '*renderBindings*' -g '*renderExecutor*' rg -nP -C8 '\bGetImage\s*\(\s*(Image|Slot)?Id' --type=cpp -g '*textureCache*' ``` Repository: KytyPS5/KytyPS5 Length of output: 4551 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- renderCompute preview and dispatch context ---' rg -n -C12 -F -- 'HeadsetPreviewNote' src/graphics/host_gpu/renderer/renderCompute.cpp printf '%s\n' '--- descriptor declarations ---' rg -n -C8 -F -e 'struct PreparedBindings' -e 'class PreparedBindings' -e 'struct ImageBinding' -e 'class RenderExecutor' src/graphics/host_gpu/renderer printf '%s\n' '--- complete PrepareBindings/RebindImages blocks ---' sed -n '687,875p' src/graphics/host_gpu/renderer/pipeline/descriptors.cpp printf '%s\n' '--- ImageId declaration and null checks ---' rg -n -C8 -F -e 'using ImageId' -e 'typedef.*ImageId' -e 'ImageId image_id' -e 'image_id)' -e '!.*image_id' src/graphics/host_gpu/renderer printf '%s\n' '--- relevant draw guard ---' rg -n -C10 -F -- 'EXIT_IF(!target.image_id)' src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 41544 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- ResolveTexture declarations and implementation ---' rg -n -C12 -F -e 'ResolveTexture' src/graphics/host_gpu/renderer printf '%s\n' '--- ImageId and SlotId definitions ---' rg -n -C10 -F -e 'using ImageId' -e 'using SlotId' -e 'class SlotId' -e 'struct SlotId' -e 'SlotId' src/graphics/host_gpu/renderer src/common printf '%s\n' '--- resource image metadata and descriptor resolution inputs ---' rg -n -C8 -F -e 'struct ShaderImage' -e 'struct ImageInfo' -e 'struct ImageDesc' -e 'snapshot.images' src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 37285 --- 🏁 Script executed: ```bash nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '477,570p' ``` Repository: KytyPS5/KytyPS5 Length of output: 6294 --- </details> **Guard null image IDs before headset preview.** When a written compute image has a null descriptor, `ResolveTexture` leaves `image_id` empty. `RebindImages` skips that binding, but the preview loop still calls `GetImage` with the empty ID. `GetImage` rejects the invalid slot and can stop the emulator when VR preview is enabled. The binding-size mismatch is already rejected by `RebindImages`, so only the image-ID guard is needed. <details> <summary>🛡️ Suggested fix</summary> ```diff --- "a/src/graphics/host_gpu/renderer/renderCompute.cpp" +++ "b/src/graphics/host_gpu/renderer/renderCompute.cpp" @@ -365,11 +365,11 @@ m_context.PrepareBda(); } RebindImages(bindings); for (size_t i = 0; HeadsetPreviewEnabled() && i < program.info.images.size(); i++) { - if (program.info.images[i].written) { + if (program.info.images[i].written && bindings.images[i].image_id) { HeadsetPreviewNote(m_context.GetTextureCache().GetImage(bindings.images[i].image_id).info); } } BindSharedMemory(m_context, input_info, bindings); RebindBuffers(bindings); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion for (size_t i = 0; HeadsetPreviewEnabled() && i < program.info.images.size(); i++) { if (program.info.images[i].written && bindings.images[i].image_id) { HeadsetPreviewNote(m_context.GetTextureCache().GetImage(bindings.images[i].image_id).info); } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:afd3d2c81f2c14620cd714e9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/graphics/presentation/openxrHeadset.cpp line 419 (outdated):

@@ -0,0 +1,1009 @@
+#include "graphics/presentation/openxrHeadset.h"
+
+#include "common/emulatorConfig.h"
+#include "common/logging/log.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/graphicContext.h"
+#include "graphics/host_gpu/renderer/image/image.h"
+#include "graphics/host_gpu/renderer/render.h"
+#include "graphics/host_gpu/renderer/renderContext.h"
+#include "libs/hmd2.h"
+
+#include <cstdlib>
+
+#if defined(_WIN32) && __has_include(<openxr/openxr.h>)
+#define KYTY_OPENXR_BUILT 1
+#endif
+
+#ifdef KYTY_OPENXR_BUILT
+
+#define XR_USE_GRAPHICS_API_VULKAN
+#include <vulkan/vulkan.h>
+// clang-format off
+#include <openxr/openxr.h>
+#include <openxr/openxr_platform.h>
+// clang-format on
+
+#include <atomic>
+#include <chrono>
+#include <cmath>
+#include <cstring>
+#include <fmt/format.h>
+#include <mutex>
+#include <sstream>
+#include <string>
+#include <thread>
+
+namespace Libs::Vr {
+
+namespace {
+
+using namespace Libs::Graphics;
+
+constexpr int STAGING_COUNT = 3;
+
+struct Latest {
+	int           index = -1;
+	uint64_t      tick  = 0;
+	vk::Semaphore semaphore;
+	VrPose        head; // The head pose the game last read, so the picture can be placed in the world.
+};
+
+// Hamilton product and rotation, for placing the eye poses relative to the head.
+XrQuaternionf Multiply(const XrQuaternionf& a, const XrQuaternionf& b) {
+	return {a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
+	        a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z};
+}
+
+XrVector3f Rotate(const XrQuaternionf& q, const XrVector3f& v) {
+	const XrVector3f t {2.0f * (q.y * v.z - q.z * v.y), 2.0f * (q.z * v.x - q.x * v.z),
+	                    2.0f * (q.x * v.y - q.y * v.x)};
+	return {v.x + q.w * t.x + (q.y * t.z - q.z * t.y), v.y + q.w * t.y + (q.z * t.x - q.x * t.z),
+	        v.z + q.w * t.z + (q.x * t.y - q.y * t.x)};
+}
+
+struct State {
+	XrInstance instance = XR_NULL_HANDLE;
+	XrSystemId system   = XR_NULL_SYSTEM_ID;
+	XrSession  session  = XR_NULL_HANDLE;
+	XrSpace    space    = XR_NULL_HANDLE;
+	bool       session_running = false;
+
+	std::string instance_extensions;
+	std::string device_extensions;
+	std::vector<std::string> instance_extension_names;
+	std::vector<std::string> device_extension_names;
+	vk::PhysicalDevice       physical_device = nullptr;
+
+	PFN_xrGetVulkanGraphicsDeviceKHR       get_graphics_device = nullptr;
+	PFN_xrGetVulkanGraphicsRequirementsKHR get_requirements    = nullptr;
+	PFN_xrGetVulkanInstanceExtensionsKHR   get_instance_ext    = nullptr;
+	PFN_xrGetVulkanDeviceExtensionsKHR     get_device_ext      = nullptr;
+
+	GraphicContext* graphics = nullptr;
+	std::thread     thread;
+	std::atomic_bool stop {false};
+	std::atomic_bool active {false};
+
+	// Staging images that carry the game's headset image from the render thread to this one.
+	std::mutex   mutex;
+	VulkanImage  staging[STAGING_COUNT];
+	vk::Extent2D staging_extent {};
+	vk::Format   staging_format = vk::Format::eUndefined;
+	bool         staging_failed = false;
+	int          held           = -1;
+	Latest       latest;
+
+	// Per-eye swapchains, created on the first frame once the source size is known.
+	XrSwapchain                           swapchain[2] {};
+	std::vector<XrSwapchainImageVulkanKHR> swapchain_images[2];
+	vk::Extent2D                          eye_extent {};
+
+	vk::CommandPool   pool;
+	vk::CommandBuffer command;
+	vk::Fence         fence;
+
+	// Controller input.
+	XrSessionState session_state = XR_SESSION_STATE_UNKNOWN;
+	XrActionSet    action_set    = XR_NULL_HANDLE;
+	XrAction       a_trigger = XR_NULL_HANDLE, a_squeeze = XR_NULL_HANDLE, a_stick = XR_NULL_HANDLE,
+	               a_stick_click = XR_NULL_HANDLE, a_primary = XR_NULL_HANDLE,
+	               a_secondary = XR_NULL_HANDLE, a_menu = XR_NULL_HANDLE, a_grip = XR_NULL_HANDLE;
+	XrPath            hand_path[2] {};
+	XrSpace           grip_space[2] {};
+	XrSpace           local_space = XR_NULL_HANDLE;
+	bool              input_ready = false;
+	std::mutex        input_mutex;
+	VrControllerInput input[2];
+	VrPose            head;
+	VrPose            last_head_read; // The head pose most recently handed to the game.
+};
+
+State g;
+
+void Say(const std::string& text) {
+	Log::WriteToConsoleAndLog(text + "\n");
+}
+
+bool Ok(XrResult result, const char* what) {
+	if (XR_SUCCEEDED(result)) {
+		return true;
+	}
+	char text[XR_MAX_RESULT_STRING_SIZE] = {};
+	if (g.instance != XR_NULL_HANDLE) {
+		xrResultToString(g.instance, result, text);
+	}
+	Say(fmt::format("OpenXR: {} failed: {} ({})", what, text, static_cast<int>(result)));
+	return false;
+}
+
+std::vector<std::string> SplitWords(const std::string& text) {
+	std::vector<std::string> words;
+	std::istringstream       stream(text);
+	for (std::string word; stream >> word;) {
+		words.push_back(word);
+	}
+	return words;
+}
+
+bool Has(const std::vector<vk::ExtensionProperties>& available, const std::string& name) {
+	for (const auto& extension: available) {
+		if (name == extension.extensionName.data()) {
+			return true;
+		}
+	}
+	return false;
+}
+
+void AppendMissing(std::vector<const char*>& out, const std::vector<std::string>& names,
+                   const std::vector<vk::ExtensionProperties>& available) {
+	for (const auto& name: names) {
+		if (!Has(available, name)) {
+			continue;
+		}
+		bool present = false;
+		for (const auto* existing: out) {
+			present |= name == existing;
+		}
+		if (!present) {
+			out.push_back(name.c_str());
+		}
+	}
+}
+
+// ---- staging images (render thread) ----------------------------------------------------------
+
+bool EnsureStaging(const VulkanImage& source) {
+	if (g.staging_failed) {
+		return false;
+	}
+	if (g.staging_format != vk::Format::eUndefined) {
+		if (source.format != g.staging_format || source.extent.width != g.staging_extent.width ||
+		    source.extent.height != g.staging_extent.height) {
+			return false;
+		}
+		return true;
+	}
+	for (auto& image: g.staging) {
+		vk::ImageCreateInfo info {};
+		info.imageType     = vk::ImageType::e2D;
+		info.format        = source.format;
+		info.extent        = vk::Extent3D {source.extent.width, source.extent.height, 1};
+		info.mipLevels     = 1;
+		info.arrayLayers   = 1;
+		info.samples       = vk::SampleCountFlagBits::e1;
+		info.tiling        = vk::ImageTiling::eOptimal;
+		info.usage         = vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst;
+		info.initialLayout = vk::ImageLayout::eUndefined;
+		if (!g.graphics->CreateImage(info, image)) {
+			Say("OpenXR: could not allocate the headset staging images");
+			g.staging_failed = true;
+			return false;
+		}
+	}
+	g.staging_format = source.format;
+	g.staging_extent = {source.extent.width, source.extent.height};
+	Say(fmt::format("OpenXR: eye source {}x{} format {}", g.staging_extent.width,
+	                g.staging_extent.height, vk::to_string(g.staging_format)));
+	return true;
+}
+
+void Transit(vk::CommandBuffer command, VulkanImage& image, vk::ImageLayout layout,
+             vk::PipelineStageFlags2 stage, vk::AccessFlags2 access) {
+	vk::ImageMemoryBarrier2 barrier {};
+	barrier.srcStageMask                    = vk::PipelineStageFlagBits2::eAllCommands;
+	barrier.srcAccessMask                   = vk::AccessFlagBits2::eMemoryWrite;
+	barrier.dstStageMask                    = stage;
+	barrier.dstAccessMask                   = access;
+	barrier.oldLayout                       = image.state.layout;
+	barrier.newLayout                       = layout;
+	barrier.srcQueueFamilyIndex             = VK_QUEUE_FAMILY_IGNORED;
+	barrier.dstQueueFamilyIndex             = VK_QUEUE_FAMILY_IGNORED;
+	barrier.image                           = image.image;
+	barrier.subresourceRange.aspectMask     = vk::ImageAspectFlagBits::eColor;
+	barrier.subresourceRange.levelCount     = 1;
+	barrier.subresourceRange.layerCount     = 1;
+	vk::DependencyInfo dependency {};
+	dependency.imageMemoryBarrierCount = 1;
+	dependency.pImageMemoryBarriers    = &barrier;
+	command.pipelineBarrier2(dependency);
+	image.state.layout = layout;
+}
+
+// ---- headset thread --------------------------------------------------------------------------
+
+vk::Format PickSwapchainFormat() {
+	uint32_t count = 0;
+	xrEnumerateSwapchainFormats(g.session, 0, &count, nullptr);
+	std::vector<int64_t> formats(count);
+	xrEnumerateSwapchainFormats(g.session, count, &count, formats.data());
+	const vk::Format preferred[] = {vk::Format::eR8G8B8A8Unorm, vk::Format::eB8G8R8A8Unorm,
+	                                vk::Format::eR8G8B8A8Srgb, vk::Format::eB8G8R8A8Srgb};
+	for (const auto wanted: preferred) {
+		for (const auto value: formats) {
+			if (value == static_cast<int64_t>(wanted)) {
+				return wanted;
+			}
+		}
+	}
+	return count != 0 ? static_cast<vk::Format>(formats[0]) : vk::Format::eUndefined;
+}
+
+bool CreateEyeSwapchains(vk::Extent2D eye) {
+	const auto format = PickSwapchainFormat();
+	if (format == vk::Format::eUndefined) {
+		return false;
+	}
+	for (int i = 0; i < 2; i++) {
+		XrSwapchainCreateInfo info {XR_TYPE_SWAPCHAIN_CREATE_INFO};
+		info.usageFlags = XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT |
+		                  XR_SWAPCHAIN_USAGE_SAMPLED_BIT;
+		info.format      = static_cast<int64_t>(format);
+		info.sampleCount = 1;
+		info.width       = eye.width;
+		info.height      = eye.height;
+		info.faceCount   = 1;
+		info.arraySize   = 1;
+		info.mipCount    = 1;
+		if (!Ok(xrCreateSwapchain(g.session, &info, &g.swapchain[i]), "xrCreateSwapchain")) {
+			return false;
+		}
+		uint32_t count = 0;
+		xrEnumerateSwapchainImages(g.swapchain[i], 0, &count, nullptr);
+		g.swapchain_images[i].assign(count, XrSwapchainImageVulkanKHR {XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR});
+		xrEnumerateSwapchainImages(
+		    g.swapchain[i], count, &count,
+		    reinterpret_cast<XrSwapchainImageBaseHeader*>(g.swapchain_images[i].data()));
+	}
+	g.eye_extent = eye;
+	Say(fmt::format("OpenXR: eye swapchains {}x{} format {}", eye.width, eye.height,
+	                vk::to_string(format)));
+	return true;
+}
+
+// Blits both eyes out of one staging image into the two swapchain images and waits for the GPU.
+bool RenderEyes(const Latest& snapshot, VulkanImage& source) {
+	auto&    device = g.graphics->device;
+	uint32_t index[2] {};
+
+	// The copy is queued behind the game's own work on the same queue. If it waited on the GPU for a
+	// tick the game has not submitted yet, it would sit in front of that submit and block it for
+	// good. So wait for the tick on the CPU first, and skip this frame if it is not there yet.
+	{
+		vk::SemaphoreWaitInfo wait_info {};
+		wait_info.semaphoreCount = 1;
+		wait_info.pSemaphores    = &snapshot.semaphore;
+		wait_info.pValues        = &snapshot.tick;
+		if (device.waitSemaphores(&wait_info, 30'000'000) != vk::Result::eSuccess) {
+			return false;
+		}
+	}
+	for (int eye = 0; eye < 2; eye++) {
+		XrSwapchainImageAcquireInfo acquire {XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
+		{
+			Common::LockGuard queue_lock(g.graphics->queue_mutex);
+			if (!Ok(xrAcquireSwapchainImage(g.swapchain[eye], &acquire, &index[eye]), "acquire")) {
+				return false;
+			}
+		}
+		XrSwapchainImageWaitInfo wait {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
+		wait.timeout = XR_INFINITE_DURATION;
+		if (!Ok(xrWaitSwapchainImage(g.swapchain[eye], &wait), "wait swapchain image")) {
+			return false;
+		}
+	}
+
+	(void)device.resetFences(1, &g.fence);
+	g.command.reset();
+	vk::CommandBufferBeginInfo begin {};
+	begin.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
+	(void)g.command.begin(&begin);
+
+	// The staging image was left in transfer-source layout by the render thread.
+	const int64_t eye_width = static_cast<int64_t>(g.staging_extent.width / 2);
+	for (int eye = 0; eye < 2; eye++) {
+		VulkanImage target;
+		target.image        = g.swapchain_images[eye][index[eye]].image;
+		target.state.layout = vk::ImageLayout::eColorAttachmentOptimal;
+		Transit(g.command, target, vk::ImageLayout::eTransferDstOptimal,
+		        vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite);
+		vk::ImageBlit region {};
+		region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
+		region.srcOffsets[0]  = vk::Offset3D {static_cast<int32_t>(eye * eye_width), 0, 0};
+		region.srcOffsets[1]  = vk::Offset3D {static_cast<int32_t>((eye + 1) * eye_width),
+		                                      static_cast<int32_t>(g.staging_extent.height), 1};
+		region.dstSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
+		region.dstOffsets[1]  = vk::Offset3D {static_cast<int32_t>(g.eye_extent.width),
+		                                      static_cast<int32_t>(g.eye_extent.height), 1};
+		g.command.blitImage(source.image, vk::ImageLayout::eTransferSrcOptimal, target.image,
+		                    vk::ImageLayout::eTransferDstOptimal, 1, &region, vk::Filter::eLinear);
+		Transit(g.command, target, vk::ImageLayout::eColorAttachmentOptimal,
+		        vk::PipelineStageFlagBits2::eColorAttachmentOutput,
+		        vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite);
+	}
+	(void)g.command.end();
+
+	vk::TimelineSemaphoreSubmitInfo timeline {};
+	timeline.waitSemaphoreValueCount = 1;
+	timeline.pWaitSemaphoreValues    = &snapshot.tick;
+	vk::PipelineStageFlags wait_stage = vk::PipelineStageFlagBits::eTransfer;
+	vk::SubmitInfo         submit {};
+	submit.pNext              = &timeline;
+	submit.waitSemaphoreCount = 1;
+	submit.pWaitSemaphores    = &snapshot.semaphore;
+	submit.pWaitDstStageMask  = &wait_stage;
+	submit.commandBufferCount = 1;
+	submit.pCommandBuffers    = &g.command;
+	vk::Result result;
+	{
+		Common::LockGuard queue_lock(g.graphics->queue_mutex);
+		result = g.graphics->queue.submit(1, &submit, g.fence);
+	}
+	if (result != vk::Result::eSuccess) {
+		Say(fmt::format("OpenXR: headset submit failed: {}", vk::to_string(result)));
+		return false;
+	}
+	(void)device.waitForFences(1, &g.fence, VK_TRUE, UINT64_MAX);
+
+	for (int eye = 0; eye < 2; eye++) {
+		XrSwapchainImageReleaseInfo release {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
+		Common::LockGuard             queue_lock(g.graphics->queue_mutex);
+		if (!Ok(xrReleaseSwapchainImage(g.swapchain[eye], &release), "release")) {
+			return false;
+		}
+	}
+	return true;
+}
+
+XrFovf EyeFov(int eye) {
+	const float out    = std::atan(Hmd2::FOV_TAN_OUT);
+	const float in     = std::atan(Hmd2::FOV_TAN_IN);
+	const float top    = std::atan(Hmd2::FOV_TAN_TOP);
+	const float bottom = std::atan(Hmd2::FOV_TAN_BOTTOM);
+	XrFovf      fov {};
+	// The outer side of each eye is its temporal side: left for the left eye, right for the right.
+	fov.angleLeft  = eye == 0 ? -out : -in;
+	fov.angleRight = eye == 0 ? in : out;
+	fov.angleUp    = top;
+	fov.angleDown  = -bottom;
+	return fov;
+}
+
+void HandleEvents() {
+	for (;;) {
+		XrEventDataBuffer event {XR_TYPE_EVENT_DATA_BUFFER};
+		if (xrPollEvent(g.instance, &event) != XR_SUCCESS) {
+			return;
+		}
+		if (event.type != XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) {
+			continue;
+		}
+		const auto& changed = *reinterpret_cast<XrEventDataSessionStateChanged*>(&event);
+		Say(fmt::format("OpenXR: session state {}", static_cast<int>(changed.state)));
+		g.session_state = changed.state;
+		switch (changed.state) {
+			case XR_SESSION_STATE_READY: {
+				XrSessionBeginInfo begin {XR_TYPE_SESSION_BEGIN_INFO};
+				begin.primaryViewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
+				g.session_running                  = Ok(xrBeginSession(g.session, &begin), "xrBeginSession");
+				break;
+			}
+			case XR_SESSION_STATE_STOPPING:
+				xrEndSession(g.session);
+				g.session_running = false;
+				break;
+			case XR_SESSION_STATE_EXITING:
+			case XR_SESSION_STATE_LOSS_PENDING:
+				g.session_running = false;
+				g.stop            = true;
+				break;

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear g.active and the input state when the runtime ends the session.

The runtime can send XR_SESSION_STATE_EXITING or XR_SESSION_STATE_LOSS_PENDING, for example when the user closes SteamVR or the headset disconnects. This case sets g.stop, and ThreadMain then returns. g.active stays true until OpenXrShutdown runs at window teardown.

After that, OpenXrGetController and OpenXrGetHeadPose still return the last cached g.input and g.head values. vrInput.h says these functions return false when no headset session is running, and the caller then uses the keyboard or gamepad. With the current code, the game keeps reading frozen VR input and does not fall back to the keyboard or gamepad. If a button was held at that moment, the game sees it as held. OpenXrQueueEyeSource also keeps copying frames into staging images that nothing reads.

Set g.active to false and reset the cached input before the thread exits.

🐛 Proposed fix
--- "a/src/graphics/presentation/openxrHeadset.cpp"
+++ "b/src/graphics/presentation/openxrHeadset.cpp"
@@ -412,11 +412,18 @@
 				xrEndSession(g.session);
 				g.session_running = false;
 				break;
 			case XR_SESSION_STATE_EXITING:
 			case XR_SESSION_STATE_LOSS_PENDING:
 				g.session_running = false;
 				g.stop            = true;
+				g.active          = false;
+				{
+					std::lock_guard lock(g.input_mutex);
+					g.input[0] = {};
+					g.input[1] = {};
+					g.head     = {};
+				}
 				break;
 			default: break;
 		}
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			case XR_SESSION_STATE_EXITING:
			case XR_SESSION_STATE_LOSS_PENDING:
				g.session_running = false;
				g.stop            = true;
				g.active          = false;
				{
					std::lock_guard lock(g.input_mutex);
					g.input[0] = {};
					g.input[1] = {};
					g.head     = {};
				}
				break;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070177) On `src/graphics/presentation/openxrHeadset.cpp` line 419 (outdated): ```diff @@ -0,0 +1,1009 @@ +#include "graphics/presentation/openxrHeadset.h" + +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/threads.h" +#include "graphics/host_gpu/graphicContext.h" +#include "graphics/host_gpu/renderer/image/image.h" +#include "graphics/host_gpu/renderer/render.h" +#include "graphics/host_gpu/renderer/renderContext.h" +#include "libs/hmd2.h" + +#include <cstdlib> + +#if defined(_WIN32) && __has_include(<openxr/openxr.h>) +#define KYTY_OPENXR_BUILT 1 +#endif + +#ifdef KYTY_OPENXR_BUILT + +#define XR_USE_GRAPHICS_API_VULKAN +#include <vulkan/vulkan.h> +// clang-format off +#include <openxr/openxr.h> +#include <openxr/openxr_platform.h> +// clang-format on + +#include <atomic> +#include <chrono> +#include <cmath> +#include <cstring> +#include <fmt/format.h> +#include <mutex> +#include <sstream> +#include <string> +#include <thread> + +namespace Libs::Vr { + +namespace { + +using namespace Libs::Graphics; + +constexpr int STAGING_COUNT = 3; + +struct Latest { + int index = -1; + uint64_t tick = 0; + vk::Semaphore semaphore; + VrPose head; // The head pose the game last read, so the picture can be placed in the world. +}; + +// Hamilton product and rotation, for placing the eye poses relative to the head. +XrQuaternionf Multiply(const XrQuaternionf& a, const XrQuaternionf& b) { + return {a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, + a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z}; +} + +XrVector3f Rotate(const XrQuaternionf& q, const XrVector3f& v) { + const XrVector3f t {2.0f * (q.y * v.z - q.z * v.y), 2.0f * (q.z * v.x - q.x * v.z), + 2.0f * (q.x * v.y - q.y * v.x)}; + return {v.x + q.w * t.x + (q.y * t.z - q.z * t.y), v.y + q.w * t.y + (q.z * t.x - q.x * t.z), + v.z + q.w * t.z + (q.x * t.y - q.y * t.x)}; +} + +struct State { + XrInstance instance = XR_NULL_HANDLE; + XrSystemId system = XR_NULL_SYSTEM_ID; + XrSession session = XR_NULL_HANDLE; + XrSpace space = XR_NULL_HANDLE; + bool session_running = false; + + std::string instance_extensions; + std::string device_extensions; + std::vector<std::string> instance_extension_names; + std::vector<std::string> device_extension_names; + vk::PhysicalDevice physical_device = nullptr; + + PFN_xrGetVulkanGraphicsDeviceKHR get_graphics_device = nullptr; + PFN_xrGetVulkanGraphicsRequirementsKHR get_requirements = nullptr; + PFN_xrGetVulkanInstanceExtensionsKHR get_instance_ext = nullptr; + PFN_xrGetVulkanDeviceExtensionsKHR get_device_ext = nullptr; + + GraphicContext* graphics = nullptr; + std::thread thread; + std::atomic_bool stop {false}; + std::atomic_bool active {false}; + + // Staging images that carry the game's headset image from the render thread to this one. + std::mutex mutex; + VulkanImage staging[STAGING_COUNT]; + vk::Extent2D staging_extent {}; + vk::Format staging_format = vk::Format::eUndefined; + bool staging_failed = false; + int held = -1; + Latest latest; + + // Per-eye swapchains, created on the first frame once the source size is known. + XrSwapchain swapchain[2] {}; + std::vector<XrSwapchainImageVulkanKHR> swapchain_images[2]; + vk::Extent2D eye_extent {}; + + vk::CommandPool pool; + vk::CommandBuffer command; + vk::Fence fence; + + // Controller input. + XrSessionState session_state = XR_SESSION_STATE_UNKNOWN; + XrActionSet action_set = XR_NULL_HANDLE; + XrAction a_trigger = XR_NULL_HANDLE, a_squeeze = XR_NULL_HANDLE, a_stick = XR_NULL_HANDLE, + a_stick_click = XR_NULL_HANDLE, a_primary = XR_NULL_HANDLE, + a_secondary = XR_NULL_HANDLE, a_menu = XR_NULL_HANDLE, a_grip = XR_NULL_HANDLE; + XrPath hand_path[2] {}; + XrSpace grip_space[2] {}; + XrSpace local_space = XR_NULL_HANDLE; + bool input_ready = false; + std::mutex input_mutex; + VrControllerInput input[2]; + VrPose head; + VrPose last_head_read; // The head pose most recently handed to the game. +}; + +State g; + +void Say(const std::string& text) { + Log::WriteToConsoleAndLog(text + "\n"); +} + +bool Ok(XrResult result, const char* what) { + if (XR_SUCCEEDED(result)) { + return true; + } + char text[XR_MAX_RESULT_STRING_SIZE] = {}; + if (g.instance != XR_NULL_HANDLE) { + xrResultToString(g.instance, result, text); + } + Say(fmt::format("OpenXR: {} failed: {} ({})", what, text, static_cast<int>(result))); + return false; +} + +std::vector<std::string> SplitWords(const std::string& text) { + std::vector<std::string> words; + std::istringstream stream(text); + for (std::string word; stream >> word;) { + words.push_back(word); + } + return words; +} + +bool Has(const std::vector<vk::ExtensionProperties>& available, const std::string& name) { + for (const auto& extension: available) { + if (name == extension.extensionName.data()) { + return true; + } + } + return false; +} + +void AppendMissing(std::vector<const char*>& out, const std::vector<std::string>& names, + const std::vector<vk::ExtensionProperties>& available) { + for (const auto& name: names) { + if (!Has(available, name)) { + continue; + } + bool present = false; + for (const auto* existing: out) { + present |= name == existing; + } + if (!present) { + out.push_back(name.c_str()); + } + } +} + +// ---- staging images (render thread) ---------------------------------------------------------- + +bool EnsureStaging(const VulkanImage& source) { + if (g.staging_failed) { + return false; + } + if (g.staging_format != vk::Format::eUndefined) { + if (source.format != g.staging_format || source.extent.width != g.staging_extent.width || + source.extent.height != g.staging_extent.height) { + return false; + } + return true; + } + for (auto& image: g.staging) { + vk::ImageCreateInfo info {}; + info.imageType = vk::ImageType::e2D; + info.format = source.format; + info.extent = vk::Extent3D {source.extent.width, source.extent.height, 1}; + info.mipLevels = 1; + info.arrayLayers = 1; + info.samples = vk::SampleCountFlagBits::e1; + info.tiling = vk::ImageTiling::eOptimal; + info.usage = vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst; + info.initialLayout = vk::ImageLayout::eUndefined; + if (!g.graphics->CreateImage(info, image)) { + Say("OpenXR: could not allocate the headset staging images"); + g.staging_failed = true; + return false; + } + } + g.staging_format = source.format; + g.staging_extent = {source.extent.width, source.extent.height}; + Say(fmt::format("OpenXR: eye source {}x{} format {}", g.staging_extent.width, + g.staging_extent.height, vk::to_string(g.staging_format))); + return true; +} + +void Transit(vk::CommandBuffer command, VulkanImage& image, vk::ImageLayout layout, + vk::PipelineStageFlags2 stage, vk::AccessFlags2 access) { + vk::ImageMemoryBarrier2 barrier {}; + barrier.srcStageMask = vk::PipelineStageFlagBits2::eAllCommands; + barrier.srcAccessMask = vk::AccessFlagBits2::eMemoryWrite; + barrier.dstStageMask = stage; + barrier.dstAccessMask = access; + barrier.oldLayout = image.state.layout; + barrier.newLayout = layout; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image.image; + barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + barrier.subresourceRange.levelCount = 1; + barrier.subresourceRange.layerCount = 1; + vk::DependencyInfo dependency {}; + dependency.imageMemoryBarrierCount = 1; + dependency.pImageMemoryBarriers = &barrier; + command.pipelineBarrier2(dependency); + image.state.layout = layout; +} + +// ---- headset thread -------------------------------------------------------------------------- + +vk::Format PickSwapchainFormat() { + uint32_t count = 0; + xrEnumerateSwapchainFormats(g.session, 0, &count, nullptr); + std::vector<int64_t> formats(count); + xrEnumerateSwapchainFormats(g.session, count, &count, formats.data()); + const vk::Format preferred[] = {vk::Format::eR8G8B8A8Unorm, vk::Format::eB8G8R8A8Unorm, + vk::Format::eR8G8B8A8Srgb, vk::Format::eB8G8R8A8Srgb}; + for (const auto wanted: preferred) { + for (const auto value: formats) { + if (value == static_cast<int64_t>(wanted)) { + return wanted; + } + } + } + return count != 0 ? static_cast<vk::Format>(formats[0]) : vk::Format::eUndefined; +} + +bool CreateEyeSwapchains(vk::Extent2D eye) { + const auto format = PickSwapchainFormat(); + if (format == vk::Format::eUndefined) { + return false; + } + for (int i = 0; i < 2; i++) { + XrSwapchainCreateInfo info {XR_TYPE_SWAPCHAIN_CREATE_INFO}; + info.usageFlags = XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | + XR_SWAPCHAIN_USAGE_SAMPLED_BIT; + info.format = static_cast<int64_t>(format); + info.sampleCount = 1; + info.width = eye.width; + info.height = eye.height; + info.faceCount = 1; + info.arraySize = 1; + info.mipCount = 1; + if (!Ok(xrCreateSwapchain(g.session, &info, &g.swapchain[i]), "xrCreateSwapchain")) { + return false; + } + uint32_t count = 0; + xrEnumerateSwapchainImages(g.swapchain[i], 0, &count, nullptr); + g.swapchain_images[i].assign(count, XrSwapchainImageVulkanKHR {XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR}); + xrEnumerateSwapchainImages( + g.swapchain[i], count, &count, + reinterpret_cast<XrSwapchainImageBaseHeader*>(g.swapchain_images[i].data())); + } + g.eye_extent = eye; + Say(fmt::format("OpenXR: eye swapchains {}x{} format {}", eye.width, eye.height, + vk::to_string(format))); + return true; +} + +// Blits both eyes out of one staging image into the two swapchain images and waits for the GPU. +bool RenderEyes(const Latest& snapshot, VulkanImage& source) { + auto& device = g.graphics->device; + uint32_t index[2] {}; + + // The copy is queued behind the game's own work on the same queue. If it waited on the GPU for a + // tick the game has not submitted yet, it would sit in front of that submit and block it for + // good. So wait for the tick on the CPU first, and skip this frame if it is not there yet. + { + vk::SemaphoreWaitInfo wait_info {}; + wait_info.semaphoreCount = 1; + wait_info.pSemaphores = &snapshot.semaphore; + wait_info.pValues = &snapshot.tick; + if (device.waitSemaphores(&wait_info, 30'000'000) != vk::Result::eSuccess) { + return false; + } + } + for (int eye = 0; eye < 2; eye++) { + XrSwapchainImageAcquireInfo acquire {XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; + { + Common::LockGuard queue_lock(g.graphics->queue_mutex); + if (!Ok(xrAcquireSwapchainImage(g.swapchain[eye], &acquire, &index[eye]), "acquire")) { + return false; + } + } + XrSwapchainImageWaitInfo wait {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; + wait.timeout = XR_INFINITE_DURATION; + if (!Ok(xrWaitSwapchainImage(g.swapchain[eye], &wait), "wait swapchain image")) { + return false; + } + } + + (void)device.resetFences(1, &g.fence); + g.command.reset(); + vk::CommandBufferBeginInfo begin {}; + begin.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; + (void)g.command.begin(&begin); + + // The staging image was left in transfer-source layout by the render thread. + const int64_t eye_width = static_cast<int64_t>(g.staging_extent.width / 2); + for (int eye = 0; eye < 2; eye++) { + VulkanImage target; + target.image = g.swapchain_images[eye][index[eye]].image; + target.state.layout = vk::ImageLayout::eColorAttachmentOptimal; + Transit(g.command, target, vk::ImageLayout::eTransferDstOptimal, + vk::PipelineStageFlagBits2::eTransfer, vk::AccessFlagBits2::eTransferWrite); + vk::ImageBlit region {}; + region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1}; + region.srcOffsets[0] = vk::Offset3D {static_cast<int32_t>(eye * eye_width), 0, 0}; + region.srcOffsets[1] = vk::Offset3D {static_cast<int32_t>((eye + 1) * eye_width), + static_cast<int32_t>(g.staging_extent.height), 1}; + region.dstSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1}; + region.dstOffsets[1] = vk::Offset3D {static_cast<int32_t>(g.eye_extent.width), + static_cast<int32_t>(g.eye_extent.height), 1}; + g.command.blitImage(source.image, vk::ImageLayout::eTransferSrcOptimal, target.image, + vk::ImageLayout::eTransferDstOptimal, 1, &region, vk::Filter::eLinear); + Transit(g.command, target, vk::ImageLayout::eColorAttachmentOptimal, + vk::PipelineStageFlagBits2::eColorAttachmentOutput, + vk::AccessFlagBits2::eColorAttachmentRead | vk::AccessFlagBits2::eColorAttachmentWrite); + } + (void)g.command.end(); + + vk::TimelineSemaphoreSubmitInfo timeline {}; + timeline.waitSemaphoreValueCount = 1; + timeline.pWaitSemaphoreValues = &snapshot.tick; + vk::PipelineStageFlags wait_stage = vk::PipelineStageFlagBits::eTransfer; + vk::SubmitInfo submit {}; + submit.pNext = &timeline; + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &snapshot.semaphore; + submit.pWaitDstStageMask = &wait_stage; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &g.command; + vk::Result result; + { + Common::LockGuard queue_lock(g.graphics->queue_mutex); + result = g.graphics->queue.submit(1, &submit, g.fence); + } + if (result != vk::Result::eSuccess) { + Say(fmt::format("OpenXR: headset submit failed: {}", vk::to_string(result))); + return false; + } + (void)device.waitForFences(1, &g.fence, VK_TRUE, UINT64_MAX); + + for (int eye = 0; eye < 2; eye++) { + XrSwapchainImageReleaseInfo release {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; + Common::LockGuard queue_lock(g.graphics->queue_mutex); + if (!Ok(xrReleaseSwapchainImage(g.swapchain[eye], &release), "release")) { + return false; + } + } + return true; +} + +XrFovf EyeFov(int eye) { + const float out = std::atan(Hmd2::FOV_TAN_OUT); + const float in = std::atan(Hmd2::FOV_TAN_IN); + const float top = std::atan(Hmd2::FOV_TAN_TOP); + const float bottom = std::atan(Hmd2::FOV_TAN_BOTTOM); + XrFovf fov {}; + // The outer side of each eye is its temporal side: left for the left eye, right for the right. + fov.angleLeft = eye == 0 ? -out : -in; + fov.angleRight = eye == 0 ? in : out; + fov.angleUp = top; + fov.angleDown = -bottom; + return fov; +} + +void HandleEvents() { + for (;;) { + XrEventDataBuffer event {XR_TYPE_EVENT_DATA_BUFFER}; + if (xrPollEvent(g.instance, &event) != XR_SUCCESS) { + return; + } + if (event.type != XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) { + continue; + } + const auto& changed = *reinterpret_cast<XrEventDataSessionStateChanged*>(&event); + Say(fmt::format("OpenXR: session state {}", static_cast<int>(changed.state))); + g.session_state = changed.state; + switch (changed.state) { + case XR_SESSION_STATE_READY: { + XrSessionBeginInfo begin {XR_TYPE_SESSION_BEGIN_INFO}; + begin.primaryViewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; + g.session_running = Ok(xrBeginSession(g.session, &begin), "xrBeginSession"); + break; + } + case XR_SESSION_STATE_STOPPING: + xrEndSession(g.session); + g.session_running = false; + break; + case XR_SESSION_STATE_EXITING: + case XR_SESSION_STATE_LOSS_PENDING: + g.session_running = false; + g.stop = true; + break; ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Clear `g.active` and the input state when the runtime ends the session.** The runtime can send `XR_SESSION_STATE_EXITING` or `XR_SESSION_STATE_LOSS_PENDING`, for example when the user closes SteamVR or the headset disconnects. This case sets `g.stop`, and `ThreadMain` then returns. `g.active` stays `true` until `OpenXrShutdown` runs at window teardown. After that, `OpenXrGetController` and `OpenXrGetHeadPose` still return the last cached `g.input` and `g.head` values. `vrInput.h` says these functions return false when no headset session is running, and the caller then uses the keyboard or gamepad. With the current code, the game keeps reading frozen VR input and does not fall back to the keyboard or gamepad. If a button was held at that moment, the game sees it as held. `OpenXrQueueEyeSource` also keeps copying frames into staging images that nothing reads. Set `g.active` to false and reset the cached input before the thread exits. <details> <summary>🐛 Proposed fix</summary> ```diff --- "a/src/graphics/presentation/openxrHeadset.cpp" +++ "b/src/graphics/presentation/openxrHeadset.cpp" @@ -412,11 +412,18 @@ xrEndSession(g.session); g.session_running = false; break; case XR_SESSION_STATE_EXITING: case XR_SESSION_STATE_LOSS_PENDING: g.session_running = false; g.stop = true; + g.active = false; + { + std::lock_guard lock(g.input_mutex); + g.input[0] = {}; + g.input[1] = {}; + g.head = {}; + } break; default: break; } } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion case XR_SESSION_STATE_EXITING: case XR_SESSION_STATE_LOSS_PENDING: g.session_running = false; g.stop = true; g.active = false; { std::lock_guard lock(g.input_mutex); g.input[0] = {}; g.input[1] = {}; g.head = {}; } break; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2bb73e63dd997cc2a5fd71cd --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/graphics/presentation/videoOut.cpp line 1506 (outdated):

@@ -1417,6 +1463,150 @@ KYTY_SYSV_ABI int VideoOutAddOutputModeEvent(LibKernel::EventQueue::KernelEqueue
 	return RegisterVideoOutEvent(handle, eq, VideoOutEventKind::OutputMode, udata);
 }
 
+static uint64_t MappedTail(const void* address) {
+	if (address == nullptr) {
+		return 0;
+	}
+	void* start = nullptr;
+	void* end   = nullptr;
+	if (LibKernel::Memory::KernelQueryMemoryProtection(const_cast<void*>(address), &start, &end,
+	                                                   nullptr) != OK ||
+	    end == nullptr) {
+		return 0;
+	}
+	const auto begin = reinterpret_cast<uintptr_t>(address);
+	const auto limit = reinterpret_cast<uintptr_t>(end);
+	return limit > begin ? static_cast<uint64_t>(limit - begin) : 0;
+}
+
+// A display surface is a guest allocation of at least 1 MiB. Headset registration can hand us
+// the surface itself or a small descriptor that points at it.
+static bool HeadsetSurfacePointer(uint64_t value) {
+	return value >= 0x200000000ull && (value & 255u) == 0 &&
+	       MappedTail(reinterpret_cast<const void*>(value)) >= (1ull << 20);
+}
+
+static const void* HeadsetPixelAddress(const void* data, int depth) {
+	const auto mapped = MappedTail(data);
+	if (HeadsetSurfacePointer(reinterpret_cast<uintptr_t>(data))) {
+		return data;
+	}
+	if (data == nullptr || mapped < sizeof(uint64_t) || depth > 3) {
+		std::printf("VideoOutRegisterBuffers2: headset object=%p mapped=%" PRIu64 "\n", data,
+		            mapped);
+		return nullptr;
+	}
+	const auto words = std::min<uint64_t>(8, mapped / sizeof(uint64_t));
+	std::printf("VideoOutRegisterBuffers2: headset object=%p mapped=%" PRIu64 " words", data,
+	            mapped);
+	const void* nested = nullptr;
+	for (uint64_t i = 0; i < words; ++i) {
+		uint64_t word = 0;
+		std::memcpy(&word, static_cast<const uint8_t*>(data) + i * sizeof(uint64_t),
+		            sizeof(word));

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Check the protection output of KernelQueryMemoryProtection and the meaning of its flags.
rg -nP -C8 '\bKernelQueryMemoryProtection\s*\(' --type=cpp

Repository: KytyPS5/KytyPS5

Length of output: 4100


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- videoOut.cpp ---'
nl -ba src/graphics/presentation/videoOut.cpp | sed -n '1435,1535p'
printf '%s\n' '--- KernelQueryMemoryProtection ---'
nl -ba src/kernel/memory.cpp | sed -n '3265,3335p'
printf '%s\n' '--- protection and range definitions ---'
rg -n -F -e 'struct Range' -e 'class VirtualRanges' -e 'Query(' -e 'prot' src/kernel src/core src | head -240
printf '%s\n' '--- protection constants and memory query declarations ---'
rg -n -F -e 'PROT_' -e 'MemoryProtection' -e 'KernelMprotect' -e 'VirtualQueryInfo' src include CMakeLists.txt 2>/dev/null | head -240

Repository: KytyPS5/KytyPS5

Length of output: 38715


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- protection decoding ---'
nl -ba src/kernel/memory.cpp | sed -n '45,135p'
printf '%s\n' '--- VirtualRanges query ---'
nl -ba src/kernel/memory.cpp | sed -n '210,390p'
printf '%s\n' '--- flexible mapping ---'
nl -ba src/kernel/memory.cpp | sed -n '2270,2355p'
printf '%s\n' '--- direct mapping ---'
nl -ba src/kernel/memory.cpp | sed -n '2990,3055p'

Repository: KytyPS5/KytyPS5

Length of output: 17765


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- complete DecodeMemoryProtection ---'
nl -ba src/kernel/memory.cpp | sed -n '108,175p'
printf '%s\n' '--- host mapping mode implementation ---'
rg -n -F -e 'Mode::NoAccess' -e 'SetProtection' -e 'MapBacking' src/common src/kernel | head -160
printf '%s\n' '--- protection constants visible to videoOut ---'
rg -n -F -e 'VM_PROT_READ' -e 'PROT_CPU_READ' -e 'KernelQueryMemoryProtection' src/graphics src/libs src/kernel | head -160

Repository: KytyPS5/KytyPS5

Length of output: 9009


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- Linux protection mapping ---'
nl -ba src/common/platform/sysLinuxVirtual.cpp | sed -n '45,70p'
printf '%s\n' '--- Windows protection mapping ---'
nl -ba src/common/platform/sysWindowsVirtual.cpp | sed -n '30,50p'
printf '%s\n' '--- guest address-space protection mapping ---'
nl -ba src/kernel/memoryAddressSpace.inc | sed -n '590,665p'

Repository: KytyPS5/KytyPS5

Length of output: 5610


Check protection before reading descriptor words.

MappedTail only proves that the address is in a tracked range. It does not prove that the host can read it. Query the protection and reject ranges that do not permit host reads before std::memcpy. A NoAccess descriptor can otherwise fault during VideoOutRegisterBuffers2.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070184) On `src/graphics/presentation/videoOut.cpp` line 1506 (outdated): ```diff @@ -1417,6 +1463,150 @@ KYTY_SYSV_ABI int VideoOutAddOutputModeEvent(LibKernel::EventQueue::KernelEqueue return RegisterVideoOutEvent(handle, eq, VideoOutEventKind::OutputMode, udata); } +static uint64_t MappedTail(const void* address) { + if (address == nullptr) { + return 0; + } + void* start = nullptr; + void* end = nullptr; + if (LibKernel::Memory::KernelQueryMemoryProtection(const_cast<void*>(address), &start, &end, + nullptr) != OK || + end == nullptr) { + return 0; + } + const auto begin = reinterpret_cast<uintptr_t>(address); + const auto limit = reinterpret_cast<uintptr_t>(end); + return limit > begin ? static_cast<uint64_t>(limit - begin) : 0; +} + +// A display surface is a guest allocation of at least 1 MiB. Headset registration can hand us +// the surface itself or a small descriptor that points at it. +static bool HeadsetSurfacePointer(uint64_t value) { + return value >= 0x200000000ull && (value & 255u) == 0 && + MappedTail(reinterpret_cast<const void*>(value)) >= (1ull << 20); +} + +static const void* HeadsetPixelAddress(const void* data, int depth) { + const auto mapped = MappedTail(data); + if (HeadsetSurfacePointer(reinterpret_cast<uintptr_t>(data))) { + return data; + } + if (data == nullptr || mapped < sizeof(uint64_t) || depth > 3) { + std::printf("VideoOutRegisterBuffers2: headset object=%p mapped=%" PRIu64 "\n", data, + mapped); + return nullptr; + } + const auto words = std::min<uint64_t>(8, mapped / sizeof(uint64_t)); + std::printf("VideoOutRegisterBuffers2: headset object=%p mapped=%" PRIu64 " words", data, + mapped); + const void* nested = nullptr; + for (uint64_t i = 0; i < words; ++i) { + uint64_t word = 0; + std::memcpy(&word, static_cast<const uint8_t*>(data) + i * sizeof(uint64_t), + sizeof(word)); ``` **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Check the protection output of KernelQueryMemoryProtection and the meaning of its flags. rg -nP -C8 '\bKernelQueryMemoryProtection\s*\(' --type=cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4100 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- videoOut.cpp ---' nl -ba src/graphics/presentation/videoOut.cpp | sed -n '1435,1535p' printf '%s\n' '--- KernelQueryMemoryProtection ---' nl -ba src/kernel/memory.cpp | sed -n '3265,3335p' printf '%s\n' '--- protection and range definitions ---' rg -n -F -e 'struct Range' -e 'class VirtualRanges' -e 'Query(' -e 'prot' src/kernel src/core src | head -240 printf '%s\n' '--- protection constants and memory query declarations ---' rg -n -F -e 'PROT_' -e 'MemoryProtection' -e 'KernelMprotect' -e 'VirtualQueryInfo' src include CMakeLists.txt 2>/dev/null | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 38715 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- protection decoding ---' nl -ba src/kernel/memory.cpp | sed -n '45,135p' printf '%s\n' '--- VirtualRanges query ---' nl -ba src/kernel/memory.cpp | sed -n '210,390p' printf '%s\n' '--- flexible mapping ---' nl -ba src/kernel/memory.cpp | sed -n '2270,2355p' printf '%s\n' '--- direct mapping ---' nl -ba src/kernel/memory.cpp | sed -n '2990,3055p' ``` Repository: KytyPS5/KytyPS5 Length of output: 17765 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- complete DecodeMemoryProtection ---' nl -ba src/kernel/memory.cpp | sed -n '108,175p' printf '%s\n' '--- host mapping mode implementation ---' rg -n -F -e 'Mode::NoAccess' -e 'SetProtection' -e 'MapBacking' src/common src/kernel | head -160 printf '%s\n' '--- protection constants visible to videoOut ---' rg -n -F -e 'VM_PROT_READ' -e 'PROT_CPU_READ' -e 'KernelQueryMemoryProtection' src/graphics src/libs src/kernel | head -160 ``` Repository: KytyPS5/KytyPS5 Length of output: 9009 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- Linux protection mapping ---' nl -ba src/common/platform/sysLinuxVirtual.cpp | sed -n '45,70p' printf '%s\n' '--- Windows protection mapping ---' nl -ba src/common/platform/sysWindowsVirtual.cpp | sed -n '30,50p' printf '%s\n' '--- guest address-space protection mapping ---' nl -ba src/kernel/memoryAddressSpace.inc | sed -n '590,665p' ``` Repository: KytyPS5/KytyPS5 Length of output: 5610 --- </details> **Check protection before reading descriptor words.** `MappedTail` only proves that the address is in a tracked range. It does not prove that the host can read it. Query the protection and reject ranges that do not permit host reads before `std::memcpy`. A `NoAccess` descriptor can otherwise fault during `VideoOutRegisterBuffers2`. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:59b0ca02e273341970296f31 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/graphics/presentation/videoOut.cpp line 1698 (outdated):

@@ -1457,31 +1647,83 @@ KYTY_SYSV_ABI int VideoOutRegisterBuffers2(int handle, int set_index, int buffer
 	     buffer_index_start, buffer_num, set_index, attribute->pixel_format, attribute->tiling_mode,
 	     attribute->aspect_ratio, attribute->width, attribute->height, attribute->pitch_in_pixel,
 	     attribute->option, category);
+	std::printf("VideoOutRegisterBuffers2: handle=%d start=%d count=%d %ux%u format=0x%" PRIx64
+	            " category=%d option=%p\n",
+	            handle, buffer_index_start, buffer_num, attribute->width, attribute->height,
+	            attribute->pixel_format, category, option);
+
+	auto attribute_copy = *attribute;
+	auto category_used  = category;
+	if (category_used != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED &&
+	    category_used != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_COMPRESSED) {
+		std::printf("VideoOutRegisterBuffers2: handle=%d category=%d treated as uncompressed\n",
+		            handle, category_used);
+		category_used = VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED;
+	}
+	bool                         headset_linear = false;
+	std::vector<VideoOutBuffers> headset_buffers;
+	const VideoOutBuffers*       buffer_view = buffers;
+	if (ctx->bus == VIDEO_OUT_BUS_TYPE_HMD2_MAIN &&
+	    (attribute_copy.width == 0 || attribute_copy.height == 0 ||
+	     attribute_copy.pixel_format == 0)) {
+		headset_buffers.assign(buffers, buffers + buffer_num);
+		for (int i = 0; i < buffer_num; i++) {
+			auto& entry = headset_buffers[static_cast<size_t>(i)];
+			std::printf("VideoOutRegisterBuffers2: headset slot %d data=%p metadata=%p "
+			            "reserved=%p,%p\n",
+			            i, entry.data, entry.metadata, entry.reserved[0], entry.reserved[1]);
+			const void* pixel = nullptr;
+			for (const void* candidate: {entry.data, entry.metadata, entry.reserved[0],
+			                             entry.reserved[1]}) {
+				if (HeadsetSurfacePointer(reinterpret_cast<uintptr_t>(candidate))) {
+					pixel = candidate;
+					break;
+				}
+			}
+			if (pixel == nullptr) {
+				pixel = HeadsetPixelAddress(entry.data, 0);
+			}
+			if (pixel == nullptr) {
+				std::printf("VideoOutRegisterBuffers2: headset slot %d has no surface\n", i);
+				return VIDEO_OUT_ERROR_INVALID_VALUE;
+			}
+			std::printf("VideoOutRegisterBuffers2: headset slot %d pixel=%p mapped=%" PRIu64 "\n",
+			            i, pixel, MappedTail(pixel));
+			entry.data = pixel;
+		}
+		buffer_view = headset_buffers.data();
+		if (!HeadsetDisplayAttribute(buffer_view[0].data, MappedTail(buffer_view[0].data),
+		                             attribute_copy, headset_linear)) {
+			return VIDEO_OUT_ERROR_INVALID_VALUE;
+		}

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Choose the headset layout from all buffers, not only from buffer_view[0].

HeadsetDisplayAttribute uses only the address of slot 0 to set linear, and only the mapped tail of slot 0 to check the footprint. Then line 1732 calls group.ImageInfo for every slot. In tiled mode, ImageInfo requires each address to be 64 KiB aligned. If an address is not aligned, it calls EXIT.

Here is a realistic failure:

  1. The game registers linear swapchain buffers in one allocation.
  2. Slot 0 is at the start of the allocation, so it is 64 KiB aligned.
  3. The code classifies the group as tiled.
  4. Slot 1 starts at a 256-byte-aligned offset, such as 4000×2040×4 = 0x1F21C00.
  5. Registration ends the process instead of returning an error.

The same problem occurs when a later slot has a smaller mapped tail than the candidate footprint.

Fix: treat the group as tiled only when every slot is 64 KiB aligned. Use the smallest mapped tail of all slots for the footprint check.

🐛 Proposed fix
--- "a/src/graphics/presentation/videoOut.cpp"
+++ "b/src/graphics/presentation/videoOut.cpp"
@@ -1691,11 +1691,19 @@
 			            i, pixel, MappedTail(pixel));
 			entry.data = pixel;
 		}
 		buffer_view = headset_buffers.data();
-		if (!HeadsetDisplayAttribute(buffer_view[0].data, MappedTail(buffer_view[0].data),
-		                             attribute_copy, headset_linear)) {
+		uint64_t    available = UINT64_MAX;
+		const void* probe     = buffer_view[0].data;
+		for (int i = 0; i < buffer_num; i++) {
+			available = std::min(available, MappedTail(buffer_view[i].data));
+			// One non-64 KiB-aligned slot means the set cannot be tiled.
+			if ((reinterpret_cast<uintptr_t>(buffer_view[i].data) & 65535u) != 0) {
+				probe = buffer_view[i].data;
+			}
+		}
+		if (!HeadsetDisplayAttribute(probe, available, attribute_copy, headset_linear)) {
 			return VIDEO_OUT_ERROR_INVALID_VALUE;
 		}
 	}
 
 	if (option != nullptr) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		uint64_t    available = UINT64_MAX;
		const void* probe     = buffer_view[0].data;
		for (int i = 0; i < buffer_num; i++) {
			available = std::min(available, MappedTail(buffer_view[i].data));
			// One non-64 KiB-aligned slot means the set cannot be tiled.
			if ((reinterpret_cast<uintptr_t>(buffer_view[i].data) & 65535u) != 0) {
				probe = buffer_view[i].data;
			}
		}
		if (!HeadsetDisplayAttribute(probe, available, attribute_copy, headset_linear)) {
			return VIDEO_OUT_ERROR_INVALID_VALUE;
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070187) On `src/graphics/presentation/videoOut.cpp` line 1698 (outdated): ```diff @@ -1457,31 +1647,83 @@ KYTY_SYSV_ABI int VideoOutRegisterBuffers2(int handle, int set_index, int buffer buffer_index_start, buffer_num, set_index, attribute->pixel_format, attribute->tiling_mode, attribute->aspect_ratio, attribute->width, attribute->height, attribute->pitch_in_pixel, attribute->option, category); + std::printf("VideoOutRegisterBuffers2: handle=%d start=%d count=%d %ux%u format=0x%" PRIx64 + " category=%d option=%p\n", + handle, buffer_index_start, buffer_num, attribute->width, attribute->height, + attribute->pixel_format, category, option); + + auto attribute_copy = *attribute; + auto category_used = category; + if (category_used != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED && + category_used != VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_COMPRESSED) { + std::printf("VideoOutRegisterBuffers2: handle=%d category=%d treated as uncompressed\n", + handle, category_used); + category_used = VIDEO_OUT_BUFFER_ATTRIBUTE_CATEGORY_UNCOMPRESSED; + } + bool headset_linear = false; + std::vector<VideoOutBuffers> headset_buffers; + const VideoOutBuffers* buffer_view = buffers; + if (ctx->bus == VIDEO_OUT_BUS_TYPE_HMD2_MAIN && + (attribute_copy.width == 0 || attribute_copy.height == 0 || + attribute_copy.pixel_format == 0)) { + headset_buffers.assign(buffers, buffers + buffer_num); + for (int i = 0; i < buffer_num; i++) { + auto& entry = headset_buffers[static_cast<size_t>(i)]; + std::printf("VideoOutRegisterBuffers2: headset slot %d data=%p metadata=%p " + "reserved=%p,%p\n", + i, entry.data, entry.metadata, entry.reserved[0], entry.reserved[1]); + const void* pixel = nullptr; + for (const void* candidate: {entry.data, entry.metadata, entry.reserved[0], + entry.reserved[1]}) { + if (HeadsetSurfacePointer(reinterpret_cast<uintptr_t>(candidate))) { + pixel = candidate; + break; + } + } + if (pixel == nullptr) { + pixel = HeadsetPixelAddress(entry.data, 0); + } + if (pixel == nullptr) { + std::printf("VideoOutRegisterBuffers2: headset slot %d has no surface\n", i); + return VIDEO_OUT_ERROR_INVALID_VALUE; + } + std::printf("VideoOutRegisterBuffers2: headset slot %d pixel=%p mapped=%" PRIu64 "\n", + i, pixel, MappedTail(pixel)); + entry.data = pixel; + } + buffer_view = headset_buffers.data(); + if (!HeadsetDisplayAttribute(buffer_view[0].data, MappedTail(buffer_view[0].data), + attribute_copy, headset_linear)) { + return VIDEO_OUT_ERROR_INVALID_VALUE; + } ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Choose the headset layout from all buffers, not only from `buffer_view[0]`.** `HeadsetDisplayAttribute` uses only the address of slot 0 to set `linear`, and only the mapped tail of slot 0 to check the footprint. Then line 1732 calls `group.ImageInfo` for every slot. In tiled mode, `ImageInfo` requires each address to be 64 KiB aligned. If an address is not aligned, it calls `EXIT`. Here is a realistic failure: 1. The game registers linear swapchain buffers in one allocation. 2. Slot 0 is at the start of the allocation, so it is 64 KiB aligned. 3. The code classifies the group as tiled. 4. Slot 1 starts at a 256-byte-aligned offset, such as 4000×2040×4 = 0x1F21C00. 5. Registration ends the process instead of returning an error. The same problem occurs when a later slot has a smaller mapped tail than the candidate footprint. Fix: treat the group as tiled only when every slot is 64 KiB aligned. Use the smallest mapped tail of all slots for the footprint check. <details> <summary>🐛 Proposed fix</summary> ```diff --- "a/src/graphics/presentation/videoOut.cpp" +++ "b/src/graphics/presentation/videoOut.cpp" @@ -1691,11 +1691,19 @@ i, pixel, MappedTail(pixel)); entry.data = pixel; } buffer_view = headset_buffers.data(); - if (!HeadsetDisplayAttribute(buffer_view[0].data, MappedTail(buffer_view[0].data), - attribute_copy, headset_linear)) { + uint64_t available = UINT64_MAX; + const void* probe = buffer_view[0].data; + for (int i = 0; i < buffer_num; i++) { + available = std::min(available, MappedTail(buffer_view[i].data)); + // One non-64 KiB-aligned slot means the set cannot be tiled. + if ((reinterpret_cast<uintptr_t>(buffer_view[i].data) & 65535u) != 0) { + probe = buffer_view[i].data; + } + } + if (!HeadsetDisplayAttribute(probe, available, attribute_copy, headset_linear)) { return VIDEO_OUT_ERROR_INVALID_VALUE; } } if (option != nullptr) { ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion uint64_t available = UINT64_MAX; const void* probe = buffer_view[0].data; for (int i = 0; i < buffer_num; i++) { available = std::min(available, MappedTail(buffer_view[i].data)); // One non-64 KiB-aligned slot means the set cannot be tiled. if ((reinterpret_cast<uintptr_t>(buffer_view[i].data) & 65535u) != 0) { probe = buffer_view[i].data; } } if (!HeadsetDisplayAttribute(probe, available, attribute_copy, headset_linear)) { return VIDEO_OUT_ERROR_INVALID_VALUE; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:bb1945e3b6e72f79b8e0785d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/libs/controller.cpp line 1189 (outdated):

@@ -1159,6 +1179,14 @@ int GameController::OpenPort(int user_id, int type, int index) {
 	if (m_port_state == PortState::Uninitialized) {
 		return PAD_ERROR_NOT_INITIALIZED;
 	}
+	if (IsVrPortType(type) && index == 0) {
+		const int hand = type - PAD_PORT_TYPE_VR_LEFT;
+		if (m_vr_open[hand]) {
+			return PAD_ERROR_ALREADY_OPENED;
+		}
+		m_vr_open[hand] = true;
+		return PAD_HANDLE_VR_LEFT + hand;
+	}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Accept VR port opens only on player 1.

PadOpen uses user_id to choose the player, and then calls OpenPort on that player. A user mapped to player 2 or higher can therefore open a VR port. OpenPort then sets m_vr_open[hand] on that player and returns PAD_HANDLE_VR_LEFT + hand.

PlayerForHandle sends every VR handle to g_players[0]. CheckPortHandleLocked then checks the m_vr_open flag of player 1, which is still false. As a result:

  • The returned handle fails every check with PAD_ERROR_INVALID_HANDLE.
  • PadClose cannot close the port.
  • A later PadOpen call returns PAD_ERROR_ALREADY_OPENED.

GetPortHandle has the same mismatch. Reject VR port types when m_player != 0, so that open state and handle routing use the same player.

🐛 Proposed fix
 	if (IsVrPortType(type) && index == 0) {
+		if (m_player != 0) {
+			return PAD_ERROR_INVALID_ARG;
+		}
 		const int hand = type - PAD_PORT_TYPE_VR_LEFT;

Apply the same guard in GetPortHandle and return PAD_ERROR_NO_HANDLE.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (IsVrPortType(type) && index == 0) {
		if (m_player != 0) {
			return PAD_ERROR_INVALID_ARG;
		}
		const int hand = type - PAD_PORT_TYPE_VR_LEFT;
		if (m_vr_open[hand]) {
			return PAD_ERROR_ALREADY_OPENED;
		}
		m_vr_open[hand] = true;
		return PAD_HANDLE_VR_LEFT + hand;
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070197) On `src/libs/controller.cpp` line 1189 (outdated): ```diff @@ -1159,6 +1179,14 @@ int GameController::OpenPort(int user_id, int type, int index) { if (m_port_state == PortState::Uninitialized) { return PAD_ERROR_NOT_INITIALIZED; } + if (IsVrPortType(type) && index == 0) { + const int hand = type - PAD_PORT_TYPE_VR_LEFT; + if (m_vr_open[hand]) { + return PAD_ERROR_ALREADY_OPENED; + } + m_vr_open[hand] = true; + return PAD_HANDLE_VR_LEFT + hand; + } ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Accept VR port opens only on player 1.** `PadOpen` uses `user_id` to choose the player, and then calls `OpenPort` on that player. A user mapped to player 2 or higher can therefore open a VR port. `OpenPort` then sets `m_vr_open[hand]` on that player and returns `PAD_HANDLE_VR_LEFT + hand`. `PlayerForHandle` sends every VR handle to `g_players[0]`. `CheckPortHandleLocked` then checks the `m_vr_open` flag of player 1, which is still `false`. As a result: - The returned handle fails every check with `PAD_ERROR_INVALID_HANDLE`. - `PadClose` cannot close the port. - A later `PadOpen` call returns `PAD_ERROR_ALREADY_OPENED`. `GetPortHandle` has the same mismatch. Reject VR port types when `m_player != 0`, so that open state and handle routing use the same player. <details> <summary>🐛 Proposed fix</summary> ```diff if (IsVrPortType(type) && index == 0) { + if (m_player != 0) { + return PAD_ERROR_INVALID_ARG; + } const int hand = type - PAD_PORT_TYPE_VR_LEFT; ``` Apply the same guard in `GetPortHandle` and return `PAD_ERROR_NO_HANDLE`. </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (IsVrPortType(type) && index == 0) { if (m_player != 0) { return PAD_ERROR_INVALID_ARG; } const int hand = type - PAD_PORT_TYPE_VR_LEFT; if (m_vr_open[hand]) { return PAD_ERROR_ALREADY_OPENED; } m_vr_open[hand] = true; return PAD_HANDLE_VR_LEFT + hand; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f258e9409de51e1d5b6ec36b --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/libs/libHmd2.cpp line 298 (outdated):

@@ -212,6 +217,148 @@ static int32_t KYTY_SYSV_ABI Hmd2ReprojectionEnableVrMode(uint64_t output_mode)
 	return OK;
 }
 
+// sceHmd2Open
+static int32_t KYTY_SYSV_ABI Hmd2Open(int32_t user_id, int32_t type, int32_t index,
+                                       const void* param) {
+	PRINT_NAME();
+	LOGF("\t user_id = %d\n"
+	     "\t type    = %d\n"
+	     "\t index   = %d\n"
+	     "\t param   = %p\n",
+	     user_id, type, index, param);
+	if (!g_initialized.load()) {
+		return ERROR_NOT_INITIALIZED;
+	}
+	int32_t expected = 0;
+	g_hmd_handle.compare_exchange_strong(expected, HMD_HANDLE);
+	const auto handle = g_hmd_handle.load();
+	LOGF("Hmd2: open handle=%d\n", handle);
+	return handle;
+}
+
+// sceHmd2ReprojectionBeginFrame
+static int32_t KYTY_SYSV_ABI Hmd2ReprojectionBeginFrame(uint64_t handle) {
+	PRINT_NAME();
+	LOGF("\t handle = 0x%" PRIx64 "\n", handle);
+	return OK;
+}
+
+static bool GuestPointer(uint64_t value) {
+	// Guest allocations start at 8 GiB. Handles, including the virtual headset, stay below that.
+	return value >= 0x200000000ull;
+}
+
+static uint64_t* PredictedTimeOutput(uint64_t arg0, uint64_t arg1) {
+	if (GuestPointer(arg1)) {
+		return reinterpret_cast<uint64_t*>(arg1);
+	}
+	if (GuestPointer(arg0)) {
+		return reinterpret_cast<uint64_t*>(arg0);
+	}
+	return nullptr;
+}
+
+// sceHmd2ReprojectionGetPredictedDisplayTime
+static int32_t KYTY_SYSV_ABI Hmd2ReprojectionGetPredictedDisplayTime(uint64_t arg0, uint64_t arg1) {
+	PRINT_NAME();
+	auto* out = PredictedTimeOutput(arg0, arg1);
+	uint64_t frame_us = 11111;
+	if (const auto* state = GetReprojectionState();
+	    state != nullptr && state->output_mode.load() == OUTPUT_MODE_119_88HZ) {
+		frame_us = 8333;
+	}
+	const auto predicted = LibKernel::KernelGetProcessTime() + frame_us;
+	LOGF("\t arg0 = 0x%" PRIx64 "\n"
+	     "\t arg1 = 0x%" PRIx64 "\n"
+	     "\t time = %" PRIu64 "\n",
+	     arg0, arg1, predicted);
+	if (out != nullptr) {
+		*out = predicted;
+	}
+	return OK;
+}
+
+// hA9LshbSkzw. Called once during headset setup. The symbol name is not identified yet.
+static int32_t KYTY_SYSV_ABI Hmd2UnknownHA9LshbSkzw(uint64_t arg0, uint64_t arg1, uint64_t arg2,
+                                                    uint64_t arg3) {
+	PRINT_NAME();
+	LOGF("\t hA9LshbSkzw args = (0x%" PRIx64 ", 0x%" PRIx64 ", 0x%" PRIx64 ", 0x%" PRIx64 ")\n",
+	     arg0, arg1, arg2, arg3);
+	return OK;
+}
+
+static void* LastGuestPointer(uint64_t arg0, uint64_t arg1, uint64_t arg2) {
+	void* found = nullptr;
+	for (const uint64_t value : {arg0, arg1, arg2}) {
+		if (GuestPointer(value)) {
+			found = reinterpret_cast<void*>(value);
+		}
+	}
+	return found;
+}

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -u
printf '%s\n' '--- changed paths ---'
git diff --name-only 0cad4672e948b92b92e1aaf6e9bb5b144d8075ac 5eaf7635cd7c4bbb6c20f098212c54db292f1123 -- src/libs/libHmd2.cpp
printf '%s\n' '--- diff libHmd2.cpp ---'
git diff --unified=80 0cad4672e948b92b92e1aaf6e9bb5b144d8075ac 5eaf7635cd7c4bbb6c20f098212c54db292f1123 -- src/libs/libHmd2.cpp
printf '%s\n' '--- relevant symbols and registrations ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'LastGuestPointer' -e 'PredictedTimeOutput' -e 'Hmd2GazeGetResult' -e 'sceHmd2GazeGetResult' -e 'lAoFUedcfqA' -e 'SVEG+1D7qHA' src || test "$?" -eq 1
printf '%s\n' '--- target source lines ---'
nl -ba src/libs/libHmd2.cpp | sed -n '1,380p'

Repository: KytyPS5/KytyPS5

Length of output: 30678


🏁 Script executed:

set -u
printf '%s\n' '--- full-repository symbol search ---'
rg -n -F --hidden --glob '!.git/**' -e 'lAoFUedcfqA' -e 'SVEG+1D7qHA' -e 'Hmd2GazeGetResult' -e 'PredictedTimeOutput' -e 'LastGuestPointer' . || test "$?" -eq 1
printf '%s\n' '--- library dispatch declarations and calls ---'
rg -n -F --glob '*.{cpp,h}' -e 'LIB_FUNC' -e 'SymbolDatabase' -e 'func->' -e 'function pointer' src | head -240
printf '%s\n' '--- likely generic invocation code ---'
rg -n -F --glob '*.{cpp,h}' -e 'Syscall' -e 'RegisterFunction' -e 'CallFunction' -e 'Invoke' -e 'GetFunction' src/kernel src/loader src/libs | head -240

Repository: KytyPS5/KytyPS5

Length of output: 24452


Use the verified output argument for Hmd2 result writes.

LastGuestPointer selects the last argument that passes only the guest-address threshold. If arg1 is the result buffer and arg2 is another guest pointer, Hmd2GazeGetResult reads the size from arg2, then can clear and overwrite that unrelated buffer. PredictedTimeOutput has the same positional ambiguity because it always prefers arg1 when both arguments look like guest pointers.

Use the tested argument layout for lAoFUedcfqA and SVEG+1D7qHA. Pass only the verified output argument to the writer instead of selecting a pointer by address.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070201) On `src/libs/libHmd2.cpp` line 298 (outdated): ```diff @@ -212,6 +217,148 @@ static int32_t KYTY_SYSV_ABI Hmd2ReprojectionEnableVrMode(uint64_t output_mode) return OK; } +// sceHmd2Open +static int32_t KYTY_SYSV_ABI Hmd2Open(int32_t user_id, int32_t type, int32_t index, + const void* param) { + PRINT_NAME(); + LOGF("\t user_id = %d\n" + "\t type = %d\n" + "\t index = %d\n" + "\t param = %p\n", + user_id, type, index, param); + if (!g_initialized.load()) { + return ERROR_NOT_INITIALIZED; + } + int32_t expected = 0; + g_hmd_handle.compare_exchange_strong(expected, HMD_HANDLE); + const auto handle = g_hmd_handle.load(); + LOGF("Hmd2: open handle=%d\n", handle); + return handle; +} + +// sceHmd2ReprojectionBeginFrame +static int32_t KYTY_SYSV_ABI Hmd2ReprojectionBeginFrame(uint64_t handle) { + PRINT_NAME(); + LOGF("\t handle = 0x%" PRIx64 "\n", handle); + return OK; +} + +static bool GuestPointer(uint64_t value) { + // Guest allocations start at 8 GiB. Handles, including the virtual headset, stay below that. + return value >= 0x200000000ull; +} + +static uint64_t* PredictedTimeOutput(uint64_t arg0, uint64_t arg1) { + if (GuestPointer(arg1)) { + return reinterpret_cast<uint64_t*>(arg1); + } + if (GuestPointer(arg0)) { + return reinterpret_cast<uint64_t*>(arg0); + } + return nullptr; +} + +// sceHmd2ReprojectionGetPredictedDisplayTime +static int32_t KYTY_SYSV_ABI Hmd2ReprojectionGetPredictedDisplayTime(uint64_t arg0, uint64_t arg1) { + PRINT_NAME(); + auto* out = PredictedTimeOutput(arg0, arg1); + uint64_t frame_us = 11111; + if (const auto* state = GetReprojectionState(); + state != nullptr && state->output_mode.load() == OUTPUT_MODE_119_88HZ) { + frame_us = 8333; + } + const auto predicted = LibKernel::KernelGetProcessTime() + frame_us; + LOGF("\t arg0 = 0x%" PRIx64 "\n" + "\t arg1 = 0x%" PRIx64 "\n" + "\t time = %" PRIu64 "\n", + arg0, arg1, predicted); + if (out != nullptr) { + *out = predicted; + } + return OK; +} + +// hA9LshbSkzw. Called once during headset setup. The symbol name is not identified yet. +static int32_t KYTY_SYSV_ABI Hmd2UnknownHA9LshbSkzw(uint64_t arg0, uint64_t arg1, uint64_t arg2, + uint64_t arg3) { + PRINT_NAME(); + LOGF("\t hA9LshbSkzw args = (0x%" PRIx64 ", 0x%" PRIx64 ", 0x%" PRIx64 ", 0x%" PRIx64 ")\n", + arg0, arg1, arg2, arg3); + return OK; +} + +static void* LastGuestPointer(uint64_t arg0, uint64_t arg1, uint64_t arg2) { + void* found = nullptr; + for (const uint64_t value : {arg0, arg1, arg2}) { + if (GuestPointer(value)) { + found = reinterpret_cast<void*>(value); + } + } + return found; +} ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -u printf '%s\n' '--- changed paths ---' git diff --name-only 0cad4672e948b92b92e1aaf6e9bb5b144d8075ac 5eaf7635cd7c4bbb6c20f098212c54db292f1123 -- src/libs/libHmd2.cpp printf '%s\n' '--- diff libHmd2.cpp ---' git diff --unified=80 0cad4672e948b92b92e1aaf6e9bb5b144d8075ac 5eaf7635cd7c4bbb6c20f098212c54db292f1123 -- src/libs/libHmd2.cpp printf '%s\n' '--- relevant symbols and registrations ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'LastGuestPointer' -e 'PredictedTimeOutput' -e 'Hmd2GazeGetResult' -e 'sceHmd2GazeGetResult' -e 'lAoFUedcfqA' -e 'SVEG+1D7qHA' src || test "$?" -eq 1 printf '%s\n' '--- target source lines ---' nl -ba src/libs/libHmd2.cpp | sed -n '1,380p' ``` Repository: KytyPS5/KytyPS5 Length of output: 30678 --- 🏁 Script executed: ```bash set -u printf '%s\n' '--- full-repository symbol search ---' rg -n -F --hidden --glob '!.git/**' -e 'lAoFUedcfqA' -e 'SVEG+1D7qHA' -e 'Hmd2GazeGetResult' -e 'PredictedTimeOutput' -e 'LastGuestPointer' . || test "$?" -eq 1 printf '%s\n' '--- library dispatch declarations and calls ---' rg -n -F --glob '*.{cpp,h}' -e 'LIB_FUNC' -e 'SymbolDatabase' -e 'func->' -e 'function pointer' src | head -240 printf '%s\n' '--- likely generic invocation code ---' rg -n -F --glob '*.{cpp,h}' -e 'Syscall' -e 'RegisterFunction' -e 'CallFunction' -e 'Invoke' -e 'GetFunction' src/kernel src/loader src/libs | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 24452 --- </details> **Use the verified output argument for Hmd2 result writes.** `LastGuestPointer` selects the last argument that passes only the guest-address threshold. If `arg1` is the result buffer and `arg2` is another guest pointer, `Hmd2GazeGetResult` reads the size from `arg2`, then can clear and overwrite that unrelated buffer. `PredictedTimeOutput` has the same positional ambiguity because it always prefers `arg1` when both arguments look like guest pointers. Use the tested argument layout for `lAoFUedcfqA` and `SVEG+1D7qHA`. Pass only the verified output argument to the writer instead of selecting a pointer by address. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6c4cfd020d8e61078f6ef57d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/libs/libPad.cpp line 227 (outdated):

@@ -147,6 +151,142 @@ static int KYTY_SYSV_ABI PadGetExtControllerInformationStub(int handle, void* in
 	return Controller::PadCheckHandle(handle);
 }
 
+// scePadVrControllerReadState. Compact Sense controller report: one stick, trigger, grip,
+// then the same motion block the DualSense report uses.
+struct VrControllerData {
+	uint32_t buttons;
+	uint8_t  stick_x;
+	uint8_t  stick_y;
+	uint8_t  analog_trigger;
+	uint8_t  analog_grip;
+	uint8_t  reserved0[2];
+	float    orientation_x;
+	float    orientation_y;
+	float    orientation_z;
+	float    orientation_w;
+	float    acceleration_x;
+	float    acceleration_y;
+	float    acceleration_z;
+	float    angular_velocity_x;
+	float    angular_velocity_y;
+	float    angular_velocity_z;
+	uint32_t reserved1;
+	uint64_t timestamp;
+	uint8_t  connected;
+	uint8_t  connected_count;
+	uint8_t  reserved2[6];
+};
+
+static_assert(sizeof(VrControllerData) == 72);
+static_assert(offsetof(VrControllerData, orientation_x) == 12);
+static_assert(offsetof(VrControllerData, acceleration_x) == 28);
+static_assert(offsetof(VrControllerData, angular_velocity_x) == 40);
+static_assert(offsetof(VrControllerData, timestamp) == 56);
+static_assert(offsetof(VrControllerData, connected) == 64);
+
+static int KYTY_SYSV_ABI PadVrControllerReadState(int handle, VrControllerData* data) {
+	PRINT_NAME();
+	LOGF("\t handle = %d\n"
+	     "\t data   = %p\n",
+	     handle, static_cast<void*>(data));
+
+	constexpr int pad_error_invalid_arg = -2137915391; /* 0x80920001 */
+	if (data == nullptr) {
+		return pad_error_invalid_arg;
+	}
+
+	VrControllerData out {};
+	out.orientation_w = 1.0f;
+	out.stick_x       = 0x80;
+	out.stick_y       = 0x80;
+
+	Controller::PadData pad {};
+	if (Controller::PadReadState(handle, &pad) == OK) {
+		out.buttons           = pad.buttons;
+		out.stick_x           = pad.left_stick_x;
+		out.stick_y           = pad.left_stick_y;
+		out.analog_trigger    = pad.analog_buttons_l2;
+		out.analog_grip       = pad.analog_buttons_r2;
+		out.orientation_x     = pad.orientation_x;
+		out.orientation_y     = pad.orientation_y;
+		out.orientation_z     = pad.orientation_z;
+		out.orientation_w     = pad.orientation_w;
+		out.acceleration_x    = pad.acceleration_x;
+		out.acceleration_y    = pad.acceleration_y;
+		out.acceleration_z    = pad.acceleration_z;
+		out.angular_velocity_x = pad.angular_velocity_x;
+		out.angular_velocity_y = pad.angular_velocity_y;
+		out.angular_velocity_z = pad.angular_velocity_z;
+		out.timestamp         = pad.timestamp;
+		out.connected         = pad.connected ? 1 : 0;
+		out.connected_count   = pad.connected_count;
+		if (out.orientation_x == 0.0f && out.orientation_y == 0.0f && out.orientation_z == 0.0f &&
+		    out.orientation_w == 0.0f) {
+			out.orientation_w = 1.0f;
+		}
+	}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return the handle error from PadVrControllerReadState.

If Controller::PadReadState(handle, &pad) fails because the handle is not valid or not open, this function still returns OK. It also writes a default, disconnected report. The other handle-based pad entry points in this file return the result of PadCheckHandle.

With the current code, a game that uses a closed VR handle, or reads before it opens the port, gets success and does not detect its mistake. Return the error code from PadReadState, except in the success case.

🐛 Proposed fix
--- "a/src/libs/libPad.cpp"
+++ "b/src/libs/libPad.cpp"
@@ -200,9 +200,12 @@
 	out.stick_x       = 0x80;
 	out.stick_y       = 0x80;
 
 	Controller::PadData pad {};
-	if (Controller::PadReadState(handle, &pad) == OK) {
+	if (const auto error = Controller::PadReadState(handle, &pad); error != OK) {
+		return error;
+	}
+	{
 		out.buttons           = pad.buttons;
 		out.stick_x           = pad.left_stick_x;
 		out.stick_y           = pad.left_stick_y;
 		out.analog_trigger    = pad.analog_buttons_l2;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	Controller::PadData pad {};
	if (const auto error = Controller::PadReadState(handle, &pad); error != OK) {
		return error;
	}
	{
		out.buttons           = pad.buttons;
		out.stick_x           = pad.left_stick_x;
		out.stick_y           = pad.left_stick_y;
		out.analog_trigger    = pad.analog_buttons_l2;
		out.analog_grip       = pad.analog_buttons_r2;
		out.orientation_x     = pad.orientation_x;
		out.orientation_y     = pad.orientation_y;
		out.orientation_z     = pad.orientation_z;
		out.orientation_w     = pad.orientation_w;
		out.acceleration_x    = pad.acceleration_x;
		out.acceleration_y    = pad.acceleration_y;
		out.acceleration_z    = pad.acceleration_z;
		out.angular_velocity_x = pad.angular_velocity_x;
		out.angular_velocity_y = pad.angular_velocity_y;
		out.angular_velocity_z = pad.angular_velocity_z;
		out.timestamp         = pad.timestamp;
		out.connected         = pad.connected ? 1 : 0;
		out.connected_count   = pad.connected_count;
		if (out.orientation_x == 0.0f && out.orientation_y == 0.0f && out.orientation_z == 0.0f &&
		    out.orientation_w == 0.0f) {
			out.orientation_w = 1.0f;
		}
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070212) On `src/libs/libPad.cpp` line 227 (outdated): ```diff @@ -147,6 +151,142 @@ static int KYTY_SYSV_ABI PadGetExtControllerInformationStub(int handle, void* in return Controller::PadCheckHandle(handle); } +// scePadVrControllerReadState. Compact Sense controller report: one stick, trigger, grip, +// then the same motion block the DualSense report uses. +struct VrControllerData { + uint32_t buttons; + uint8_t stick_x; + uint8_t stick_y; + uint8_t analog_trigger; + uint8_t analog_grip; + uint8_t reserved0[2]; + float orientation_x; + float orientation_y; + float orientation_z; + float orientation_w; + float acceleration_x; + float acceleration_y; + float acceleration_z; + float angular_velocity_x; + float angular_velocity_y; + float angular_velocity_z; + uint32_t reserved1; + uint64_t timestamp; + uint8_t connected; + uint8_t connected_count; + uint8_t reserved2[6]; +}; + +static_assert(sizeof(VrControllerData) == 72); +static_assert(offsetof(VrControllerData, orientation_x) == 12); +static_assert(offsetof(VrControllerData, acceleration_x) == 28); +static_assert(offsetof(VrControllerData, angular_velocity_x) == 40); +static_assert(offsetof(VrControllerData, timestamp) == 56); +static_assert(offsetof(VrControllerData, connected) == 64); + +static int KYTY_SYSV_ABI PadVrControllerReadState(int handle, VrControllerData* data) { + PRINT_NAME(); + LOGF("\t handle = %d\n" + "\t data = %p\n", + handle, static_cast<void*>(data)); + + constexpr int pad_error_invalid_arg = -2137915391; /* 0x80920001 */ + if (data == nullptr) { + return pad_error_invalid_arg; + } + + VrControllerData out {}; + out.orientation_w = 1.0f; + out.stick_x = 0x80; + out.stick_y = 0x80; + + Controller::PadData pad {}; + if (Controller::PadReadState(handle, &pad) == OK) { + out.buttons = pad.buttons; + out.stick_x = pad.left_stick_x; + out.stick_y = pad.left_stick_y; + out.analog_trigger = pad.analog_buttons_l2; + out.analog_grip = pad.analog_buttons_r2; + out.orientation_x = pad.orientation_x; + out.orientation_y = pad.orientation_y; + out.orientation_z = pad.orientation_z; + out.orientation_w = pad.orientation_w; + out.acceleration_x = pad.acceleration_x; + out.acceleration_y = pad.acceleration_y; + out.acceleration_z = pad.acceleration_z; + out.angular_velocity_x = pad.angular_velocity_x; + out.angular_velocity_y = pad.angular_velocity_y; + out.angular_velocity_z = pad.angular_velocity_z; + out.timestamp = pad.timestamp; + out.connected = pad.connected ? 1 : 0; + out.connected_count = pad.connected_count; + if (out.orientation_x == 0.0f && out.orientation_y == 0.0f && out.orientation_z == 0.0f && + out.orientation_w == 0.0f) { + out.orientation_w = 1.0f; + } + } ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Return the handle error from `PadVrControllerReadState`.** If `Controller::PadReadState(handle, &pad)` fails because the handle is not valid or not open, this function still returns `OK`. It also writes a default, disconnected report. The other handle-based pad entry points in this file return the result of `PadCheckHandle`. With the current code, a game that uses a closed VR handle, or reads before it opens the port, gets success and does not detect its mistake. Return the error code from `PadReadState`, except in the success case. <details> <summary>🐛 Proposed fix</summary> ```diff --- "a/src/libs/libPad.cpp" +++ "b/src/libs/libPad.cpp" @@ -200,9 +200,12 @@ out.stick_x = 0x80; out.stick_y = 0x80; Controller::PadData pad {}; - if (Controller::PadReadState(handle, &pad) == OK) { + if (const auto error = Controller::PadReadState(handle, &pad); error != OK) { + return error; + } + { out.buttons = pad.buttons; out.stick_x = pad.left_stick_x; out.stick_y = pad.left_stick_y; out.analog_trigger = pad.analog_buttons_l2; ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion Controller::PadData pad {}; if (const auto error = Controller::PadReadState(handle, &pad); error != OK) { return error; } { out.buttons = pad.buttons; out.stick_x = pad.left_stick_x; out.stick_y = pad.left_stick_y; out.analog_trigger = pad.analog_buttons_l2; out.analog_grip = pad.analog_buttons_r2; out.orientation_x = pad.orientation_x; out.orientation_y = pad.orientation_y; out.orientation_z = pad.orientation_z; out.orientation_w = pad.orientation_w; out.acceleration_x = pad.acceleration_x; out.acceleration_y = pad.acceleration_y; out.acceleration_z = pad.acceleration_z; out.angular_velocity_x = pad.angular_velocity_x; out.angular_velocity_y = pad.angular_velocity_y; out.angular_velocity_z = pad.angular_velocity_z; out.timestamp = pad.timestamp; out.connected = pad.connected ? 1 : 0; out.connected_count = pad.connected_count; if (out.orientation_x == 0.0f && out.orientation_y == 0.0f && out.orientation_z == 0.0f && out.orientation_w == 0.0f) { out.orientation_w = 1.0f; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:31e64df0a16d1a70ed61b3ee --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original
On src/libs/libVrTracker2.cpp line 79 (outdated):

@@ -0,0 +1,207 @@
+#include "common/abi.h"
+#include "kernel/pthread.h"
+#include "libs/controller.h"
+#include "libs/errno.h"
+#include "libs/libs.h"
+#include "loader/symbolDatabase.h"
+#include "graphics/presentation/vrInput.h"
+
+#include <cstdint>
+#include <cstring>
+
+namespace Libs {
+
+LIB_VERSION("VrTracker2", 1, "VrTracker2", 1, 1);
+
+namespace VrTracker2 {
+
+constexpr uint32_t TRACKER_MEMORY_SIZE  = 0x1000000;
+constexpr uint32_t TRACKER_MEMORY_ALIGN = 0x10000;
+constexpr int32_t  STATUS_TRACKING      = 1;
+
+// Device ids the game asks poses for. A controller is named by its VR pad handle.
+constexpr uint32_t DEVICE_HMD              = 0x0f000001;
+constexpr uint32_t DEVICE_CONTROLLER_LEFT  = Controller::PAD_HANDLE_VR_LEFT;
+constexpr uint32_t DEVICE_CONTROLLER_RIGHT = Controller::PAD_HANDLE_VR_RIGHT;
+constexpr uint32_t REQUEST_SIZE            = 0x30;
+
+// Pose result layout. The game reads a tracking state at +0x1C and +0x20 and, from them, decides
+// whether the position and orientation at +0x60 are usable. State 9 in both is the fully tracked
+// state and sets every validity bit. The byte at +0x54 holds the validity of the extra vectors.
+constexpr uint32_t RESULT_STATE_A_OFFSET = 0x1C;
+constexpr uint32_t RESULT_STATE_B_OFFSET = 0x20;
+constexpr uint32_t RESULT_POSE_OFFSET    = 0x60;
+// More copies of the pose. The head pose the camera is built from is read from two further slots.
+constexpr uint32_t RESULT_PREDICTED_POSE_OFFSET = 0xA0;
+constexpr uint32_t RESULT_SECOND_POSE_OFFSET    = 0xE0;
+constexpr uint32_t RESULT_FLAGS_OFFSET   = 0x54;
+constexpr uint32_t RESULT_STATE_TRACKED  = 9;
+constexpr uint8_t  RESULT_FLAGS_VALID    = 3;
+
+// A pose as the game reads it back: position, padding, then the orientation quaternion (x, y, z, w).
+struct ResultPose {
+	float position[3];
+	float reserved;
+	float orientation[4];
+};
+static_assert(sizeof(ResultPose) == 0x20);
+
+// Pose requests are 0x30 bytes: size at +0, device id at +4. The answer has no size header, so the
+// request is what tells the two shapes apart.
+static bool WritePose(const void* request, void* result) {
+	if (request == nullptr || result == nullptr || reinterpret_cast<uintptr_t>(request) < 0x200000000ull ||
+	    reinterpret_cast<uintptr_t>(result) < 0x200000000ull) {
+		return false;
+	}
+	const auto* words = static_cast<const uint32_t*>(request);
+	if (words[0] != REQUEST_SIZE) {
+		return false;
+	}
+	const auto device = words[1];
+	if (device != DEVICE_HMD && device != DEVICE_CONTROLLER_LEFT && device != DEVICE_CONTROLLER_RIGHT) {
+		return false;
+	}
+
+	ResultPose pose {};
+	pose.orientation[3] = 1.0f;
+	if (device == DEVICE_HMD) {
+		Vr::VrPose head;
+		if (Vr::OpenXrGetHeadPose(head)) {
+			std::memcpy(pose.position, head.position, sizeof(pose.position));
+			std::memcpy(pose.orientation, head.orientation, sizeof(pose.orientation));
+		}
+	} else {
+		Vr::VrControllerInput hand;
+		if (Vr::OpenXrGetController(device == DEVICE_CONTROLLER_LEFT ? 0 : 1, hand) && hand.pose_valid) {
+			std::memcpy(pose.position, hand.position, sizeof(pose.position));
+			std::memcpy(pose.orientation, hand.orientation, sizeof(pose.orientation));
+		}
+	}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not send an identity pose at the origin as a fully tracked pose when tracking is lost.

OpenXrGetHeadPose returns false in these cases:

  • The head is not tracked, for example during a short tracking loss or when the user removes the headset.
  • The session is not ready.

In these cases, WritePose still writes RESULT_STATE_TRACKED and RESULT_FLAGS_VALID, together with position (0,0,0) and identity orientation. The game then moves its camera to the tracking origin for those frames, and then moves it back. A controller with pose_valid == false gets the same result, so the hand moves to the origin.

For the HMD, keep the last valid pose and send it again. openxrHeadset.cpp already stores g.last_head_read for this purpose. Do the same for each controller. Alternatively, report a state value that marks the pose as not tracked.

Also applies to: 88-94

**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#discussion_r4317070222) On `src/libs/libVrTracker2.cpp` line 79 (outdated): ```diff @@ -0,0 +1,207 @@ +#include "common/abi.h" +#include "kernel/pthread.h" +#include "libs/controller.h" +#include "libs/errno.h" +#include "libs/libs.h" +#include "loader/symbolDatabase.h" +#include "graphics/presentation/vrInput.h" + +#include <cstdint> +#include <cstring> + +namespace Libs { + +LIB_VERSION("VrTracker2", 1, "VrTracker2", 1, 1); + +namespace VrTracker2 { + +constexpr uint32_t TRACKER_MEMORY_SIZE = 0x1000000; +constexpr uint32_t TRACKER_MEMORY_ALIGN = 0x10000; +constexpr int32_t STATUS_TRACKING = 1; + +// Device ids the game asks poses for. A controller is named by its VR pad handle. +constexpr uint32_t DEVICE_HMD = 0x0f000001; +constexpr uint32_t DEVICE_CONTROLLER_LEFT = Controller::PAD_HANDLE_VR_LEFT; +constexpr uint32_t DEVICE_CONTROLLER_RIGHT = Controller::PAD_HANDLE_VR_RIGHT; +constexpr uint32_t REQUEST_SIZE = 0x30; + +// Pose result layout. The game reads a tracking state at +0x1C and +0x20 and, from them, decides +// whether the position and orientation at +0x60 are usable. State 9 in both is the fully tracked +// state and sets every validity bit. The byte at +0x54 holds the validity of the extra vectors. +constexpr uint32_t RESULT_STATE_A_OFFSET = 0x1C; +constexpr uint32_t RESULT_STATE_B_OFFSET = 0x20; +constexpr uint32_t RESULT_POSE_OFFSET = 0x60; +// More copies of the pose. The head pose the camera is built from is read from two further slots. +constexpr uint32_t RESULT_PREDICTED_POSE_OFFSET = 0xA0; +constexpr uint32_t RESULT_SECOND_POSE_OFFSET = 0xE0; +constexpr uint32_t RESULT_FLAGS_OFFSET = 0x54; +constexpr uint32_t RESULT_STATE_TRACKED = 9; +constexpr uint8_t RESULT_FLAGS_VALID = 3; + +// A pose as the game reads it back: position, padding, then the orientation quaternion (x, y, z, w). +struct ResultPose { + float position[3]; + float reserved; + float orientation[4]; +}; +static_assert(sizeof(ResultPose) == 0x20); + +// Pose requests are 0x30 bytes: size at +0, device id at +4. The answer has no size header, so the +// request is what tells the two shapes apart. +static bool WritePose(const void* request, void* result) { + if (request == nullptr || result == nullptr || reinterpret_cast<uintptr_t>(request) < 0x200000000ull || + reinterpret_cast<uintptr_t>(result) < 0x200000000ull) { + return false; + } + const auto* words = static_cast<const uint32_t*>(request); + if (words[0] != REQUEST_SIZE) { + return false; + } + const auto device = words[1]; + if (device != DEVICE_HMD && device != DEVICE_CONTROLLER_LEFT && device != DEVICE_CONTROLLER_RIGHT) { + return false; + } + + ResultPose pose {}; + pose.orientation[3] = 1.0f; + if (device == DEVICE_HMD) { + Vr::VrPose head; + if (Vr::OpenXrGetHeadPose(head)) { + std::memcpy(pose.position, head.position, sizeof(pose.position)); + std::memcpy(pose.orientation, head.orientation, sizeof(pose.orientation)); + } + } else { + Vr::VrControllerInput hand; + if (Vr::OpenXrGetController(device == DEVICE_CONTROLLER_LEFT ? 0 : 1, hand) && hand.pose_valid) { + std::memcpy(pose.position, hand.position, sizeof(pose.position)); + std::memcpy(pose.orientation, hand.orientation, sizeof(pose.orientation)); + } + } ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Do not send an identity pose at the origin as a fully tracked pose when tracking is lost.** `OpenXrGetHeadPose` returns `false` in these cases: - The head is not tracked, for example during a short tracking loss or when the user removes the headset. - The session is not ready. In these cases, `WritePose` still writes `RESULT_STATE_TRACKED` and `RESULT_FLAGS_VALID`, together with position (0,0,0) and identity orientation. The game then moves its camera to the tracking origin for those frames, and then moves it back. A controller with `pose_valid == false` gets the same result, so the hand moves to the origin. For the HMD, keep the last valid pose and send it again. `openxrHeadset.cpp` already stores `g.last_head_read` for this purpose. Do the same for each controller. Alternatively, report a state value that marks the pose as not tracked. Also applies to: 88-94 <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e38191ed6e27f51c04331e8e --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-19 17:56 UTC · original · reviewed

Actionable comments posted: 8


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d1d12ed8-ce0f-4b39-94a5-ba012a9449ae
📥 Commits

Reviewing files that changed from the base of the PR and between 0cad4672e9 and 5eaf7635cd7c4bbb6c20f098212c54db292f1123.

📒 Files selected for processing: 23
  • 3rdparty/CMakeLists.txt
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/headsetPreview.cpp
  • src/graphics/presentation/headsetPreview.h
  • src/graphics/presentation/openxrHeadset.cpp
  • src/graphics/presentation/openxrHeadset.h
  • src/graphics/presentation/presenter.h
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/vrInput.h
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/libs/controller.cpp
  • src/libs/controller.h
  • src/libs/hmd2.h
  • src/libs/libHmd2.cpp
  • src/libs/libPad.cpp
  • src/libs/libVrTracker2.cpp
  • src/libs/libs.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-19 17:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#pullrequestreview-5575587430) · **reviewed** **Actionable comments posted: 8** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `d1d12ed8-ce0f-4b39-94a5-ba012a9449ae` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 0cad4672e948b92b92e1aaf6e9bb5b144d8075ac and 5eaf7635cd7c4bbb6c20f098212c54db292f1123. </details> <details> <summary>📒 Files selected for processing: 23</summary> * `3rdparty/CMakeLists.txt` * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.h` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/presentation/headsetPreview.cpp` * `src/graphics/presentation/headsetPreview.h` * `src/graphics/presentation/openxrHeadset.cpp` * `src/graphics/presentation/openxrHeadset.h` * `src/graphics/presentation/presenter.h` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/vrInput.h` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` * `src/libs/controller.cpp` * `src/libs/controller.h` * `src/libs/hmd2.h` * `src/libs/libHmd2.cpp` * `src/libs/libPad.cpp` * `src/libs/libVrTracker2.cpp` * `src/libs/libs.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=80dae99c-c0da-4430-9d3b-65b24d4dad2a attempt=ce5098a6-9fb2-47e7-8787-5163ea7c79b6 batch=1/1 -->
Author
Owner

@⁠Nmzik on GitHub · 2026-10-20 00:23 UTC · original

@⁠LeandroSWR Main VR support has been merged along with struct fixes/ABIs/minor optimizations and Linux support. Please make sure your future PRs are based on it (unless we created a new bug :)) Thanks!

**@⁠Nmzik** on GitHub · 2026-10-20 00:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#issuecomment-6280345118) @⁠LeandroSWR Main VR support has been merged along with struct fixes/ABIs/minor optimizations and Linux support. Please make sure your future PRs are based on it (unless we created a new bug :)) Thanks!
Author
Owner

@⁠Nmzik on GitHub · 2026-10-21 03:47 UTC · original

Credited

**@⁠Nmzik** on GitHub · 2026-10-21 03:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1726#issuecomment-6307552225) Credited

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.