diff --git a/app/src/main/cpp/questxr/quest_xr.cpp b/app/src/main/cpp/questxr/quest_xr.cpp index 09423c7d1a..8646bd501c 100644 --- a/app/src/main/cpp/questxr/quest_xr.cpp +++ b/app/src/main/cpp/questxr/quest_xr.cpp @@ -614,10 +614,13 @@ private: XrSessionBeginInfo begin{XR_TYPE_SESSION_BEGIN_INFO}; begin.primaryViewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; check(xrBeginSession(session_, &begin), "xrBeginSession"); running_ = true; + // Meta's clock governor scales clocks by the DroidDeck process's overall load and cannot see + // SteamVR missing refreshes inside the guest; holding the top level kept it at 72 Hz. if (setPerformance_) { for (auto domain : {XR_PERF_SETTINGS_DOMAIN_CPU_EXT, XR_PERF_SETTINGS_DOMAIN_GPU_EXT}) { - XrResult request = setPerformance_(session_, domain, XR_PERF_SETTINGS_LEVEL_SUSTAINED_HIGH_EXT); - __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "sustained performance domain=%d result=%d", domain, request); + XrResult request = setPerformance_(session_, domain, XR_PERF_SETTINGS_LEVEL_BOOST_EXT); + if (XR_FAILED(request)) request = setPerformance_(session_, domain, XR_PERF_SETTINGS_LEVEL_SUSTAINED_HIGH_EXT); + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "performance domain=%d result=%d", domain, request); } } } else if (state_ == XR_SESSION_STATE_STOPPING) { diff --git a/app/src/main/java/com/droiddeck/launcher/QuestSteamVrWatch.kt b/app/src/main/java/com/droiddeck/launcher/QuestSteamVrWatch.kt new file mode 100644 index 0000000000..eab1ee2f37 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/QuestSteamVrWatch.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher + +import com.droiddeck.launcher.gpu.SteamVr + +internal class QuestSteamVrWatch(start: Long) { + private var startupDeadline = start + STARTUP_MS + private var lastRunning: Long? = null + private var graceUntil = start + private var wasPaused = false + + // A frozen guest cannot answer the status call, so a status read during a freeze, or one that + // started before it, says nothing about SteamVR. + fun stopped(now: Long, status: SteamVr.Status, paused: Boolean): Boolean { + if (paused) { + wasPaused = true + return false + } + if (wasPaused) { + wasPaused = false + graceUntil = now + RESUME_GRACE_MS + } + if (status == SteamVr.Status.RUNNING) { + lastRunning = now + graceUntil = now + return false + } + val deadline = lastRunning?.plus(RUNNING_GRACE_MS) ?: startupDeadline + return now >= maxOf(deadline, graceUntil) + } + + companion object { + const val STARTUP_MS = 30_000L + const val RUNNING_GRACE_MS = 5_000L + const val RESUME_GRACE_MS = 15_000L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt index 98e5a0b227..5bde3ef872 100644 --- a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt @@ -52,18 +52,17 @@ class QuestXrActivity : NativeActivity() { if (!closing) leaveXr("SteamVR start failed", sessionAlive()) return@Thread } - val startupDeadline = SystemClock.elapsedRealtime() + 30_000 - var lastRunning: Long? = null + val watch = QuestSteamVrWatch(SystemClock.elapsedRealtime()) while (!closing) { if (!sessionAlive()) { leaveXr("Steam session ended", false) break } - steamVrStatus = SteamVr.status(this) - val now = SystemClock.elapsedRealtime() - if (steamVrStatus == SteamVr.Status.RUNNING) lastRunning = now - val deadline = lastRunning?.plus(5_000) ?: startupDeadline - if (steamVrStatus != SteamVr.Status.RUNNING && now >= deadline) { + val pausedBefore = guestPaused() + val status = SteamVr.status(this) + val paused = pausedBefore || guestPaused() + if (!paused) steamVrStatus = status + if (watch.stopped(SystemClock.elapsedRealtime(), status, paused)) { leaveXr("SteamVR stopped or did not finish starting", true) break } @@ -81,6 +80,8 @@ class QuestXrActivity : NativeActivity() { } } + private fun guestPaused() = SessionState.suspending || SessionState.suspended || SessionState.resuming + private fun sessionAlive() = SessionState.running && !SessionState.stopRequested && sessionId != null && SessionState.sessionId == sessionId diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 11fd6b86f2..8473957bcd 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2916,6 +2916,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb")) com.droiddeck.launcher.input.VrControllers.publish(this) + com.droiddeck.launcher.session.QuestSteamVrLaunch.publish(this) val turnip = TurnipDriver(this) com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup") @@ -6371,6 +6372,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } if (CompositorHost.isStarted) applyFrameGen(force = true) applyFollowOrientation(resources.configuration) + uiHandler.removeCallbacks(questSteamVrRequest) + if (com.droiddeck.launcher.session.QuestExperimental.isSupported()) uiHandler.post(questSteamVrRequest) if (runtimeRemovalBlocked) return if (!SessionState.suspended) pausedFrame = null com.droiddeck.launcher.ui.Motion.refresh(this) @@ -6430,10 +6433,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onPause() { + uiHandler.removeCallbacks(questSteamVrRequest) departureCleanup() super.onPause() } + private val questSteamVrRequest = object : Runnable { + override fun run() { + if (com.droiddeck.launcher.session.QuestSteamVrLaunch.takeRequest(this@SessionActivity) && + SessionState.running && SessionState.mode == SessionService.MODE_STEAM) steamVrAction("start") + uiHandler.postDelayed(this, 1000) + } + } + private fun departureCleanup() { com.droiddeck.launcher.input.SystemKeyCapture.detach(this) com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) diff --git a/app/src/main/java/com/droiddeck/launcher/session/QuestSteamVrLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/QuestSteamVrLaunch.kt new file mode 100644 index 0000000000..8f619b86b3 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/QuestSteamVrLaunch.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import java.io.File + +/** + * On a Quest, SteamVR has to run inside the immersive activity. A launch from Steam's library happens in the + * guest, so the guest's SteamVR helper leaves a request in the shared runtime directory for the session to act on. + */ +object QuestSteamVrLaunch { + private const val DIR = ".wayland-rt/droiddeck-steamvr" + private const val MARKER = "quest-immersive" + private const val REQUEST = "xr-request" + + fun publish(context: Context) { + val dir = File(context.filesDir, DIR) + val marker = File(dir, MARKER) + if (!QuestExperimental.isSupported()) { + marker.delete() + return + } + runCatching { + dir.mkdirs() + marker.writeText("") + } + } + + /** A request left by an earlier session must not open the immersive view in this one. */ + fun clearRequest(context: Context) { + File(context.filesDir, "$DIR/$REQUEST").delete() + } + + fun takeRequest(context: Context): Boolean = + QuestExperimental.isSupported() && File(context.filesDir, "$DIR/$REQUEST").delete() +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index c2296584e5..56c4f27f57 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -417,6 +417,7 @@ class SessionService : Service() { SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program), ) com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this)) + QuestSteamVrLaunch.clearRequest(this) val gen = synchronized(SessionState.startLock) { synchronized(stopLock) { SessionState.steamClientArch = null diff --git a/app/src/test/java/com/droiddeck/launcher/QuestSteamVrWatchTest.kt b/app/src/test/java/com/droiddeck/launcher/QuestSteamVrWatchTest.kt new file mode 100644 index 0000000000..e19c65a5cc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/QuestSteamVrWatchTest.kt @@ -0,0 +1,50 @@ +package com.droiddeck.launcher + +import com.droiddeck.launcher.gpu.SteamVr.Status +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class QuestSteamVrWatchTest { + @Test + fun steamVrThatNeverStartsFailsAfterTheStartupWindow() { + val watch = QuestSteamVrWatch(0) + assertFalse(watch.stopped(29_999, Status.READY, paused = false)) + assertTrue(watch.stopped(30_000, Status.READY, paused = false)) + } + + @Test + fun steamVrThatStopsFailsAfterTheRunningGrace() { + val watch = QuestSteamVrWatch(0) + assertFalse(watch.stopped(10_000, Status.RUNNING, paused = false)) + assertFalse(watch.stopped(14_999, Status.UNAVAILABLE, paused = false)) + assertTrue(watch.stopped(15_000, Status.UNAVAILABLE, paused = false)) + } + + @Test + fun aFrozenGuestNeverCountsAsStopped() { + val watch = QuestSteamVrWatch(0) + assertFalse(watch.stopped(10_000, Status.RUNNING, paused = false)) + for (now in 11_000L..600_000L step 10_000) assertFalse(watch.stopped(now, Status.UNAVAILABLE, paused = true)) + } + + @Test + fun aResumedGuestGetsTheFullGraceFromItsFirstAnswerAfterTheFreeze() { + val watch = QuestSteamVrWatch(0) + watch.stopped(10_000, Status.RUNNING, paused = false) + watch.stopped(300_000, Status.UNAVAILABLE, paused = true) + assertFalse(watch.stopped(310_000, Status.UNAVAILABLE, paused = false)) + assertFalse(watch.stopped(324_999, Status.UNAVAILABLE, paused = false)) + assertTrue(watch.stopped(325_000, Status.UNAVAILABLE, paused = false)) + } + + @Test + fun steamVrAnsweringAfterAResumeKeepsTheSessionOpen() { + val watch = QuestSteamVrWatch(0) + watch.stopped(10_000, Status.RUNNING, paused = false) + watch.stopped(300_000, Status.UNAVAILABLE, paused = true) + assertFalse(watch.stopped(312_000, Status.RUNNING, paused = false)) + assertFalse(watch.stopped(316_999, Status.UNAVAILABLE, paused = false)) + assertTrue(watch.stopped(317_000, Status.UNAVAILABLE, paused = false)) + } +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index df0f4cedf1..449c90ac93 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -1,6 +1,7 @@ #!/usr/bin/python3 import base64 +import ctypes import json import math import re @@ -19,6 +20,7 @@ import urllib.parse from pathlib import Path VERSION = 1 +PR_SET_CHILD_SUBREAPER = 36 OUTPUT_CAP = 256 * 1024 REQUEST_CAP = 256 * 1024 RESPONSE_CAP = 1024 * 1024 @@ -1238,7 +1240,17 @@ def answer(agent_dir, path): write_json(agent_dir / "resp" / (rid + ".json"), result) +def stop_adopting_orphans(): + # libddsession makes every session process a child subreaper. The agent never reaps adopted orphans, so + # SteamVR left zombies that its helper's stop counted as still running. The session shell above reaps them. + try: + ctypes.CDLL(None, use_errno=True).prctl(PR_SET_CHILD_SUBREAPER, 0, 0, 0, 0) + except (OSError, AttributeError): + pass + + def serve(agent_dir, focus=True, poll=0.1): + stop_adopting_orphans() (agent_dir / "req").mkdir(parents=True, exist_ok=True) (agent_dir / "resp").mkdir(parents=True, exist_ok=True) can_focus = focus and bool(os.environ.get("DISPLAY")) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr index 176f92aad3..8abe106a7f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr @@ -14,7 +14,16 @@ chmod 700 "$state" PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9 -running() { pgrep -x vrserver >/dev/null 2>&1; } +alive() { + for p in $(pgrep -x "$1"); do + case "$(awk '/^State:/ { print $2 }' "/proc/$p/status" 2>/dev/null)" in + Z|'') ;; + *) return 0 ;; + esac + done + return 1 +} +running() { alive vrserver; } installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; } quest_settings() { backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json @@ -40,6 +49,19 @@ configure_graphics() { esac } +# On the guest's three cores Steam's web helpers took CPU time from vrcompositor's frames, so while the Quest view +# shows SteamVR they run at a lower priority. +steam_ui_priority() { + status=0 + for p in $(pgrep -x steamwebhelper); do + for t in /proc/"$p"/task/*; do + renice -n "$1" -p "${t##*/}" >/dev/null 2>&1 || [ ! -e "$t" ] || status=1 + done + done + [ "$status" = 0 ] || echo "could not set every Steam web helper thread to priority $1" >&2 + return "$status" +} + unregister() { if grep -qF "\"$steamvr\"" "$HOME/.config/openvr/openvrpaths.vrpath" 2>/dev/null; then rm -f "$HOME/.config/openvr/openvrpaths.vrpath" @@ -50,7 +72,7 @@ unregister() { } idle() { - [ ! -f "$state/active" ] && ! running && ! pgrep -x vrstartup >/dev/null 2>&1 && + [ ! -f "$state/active" ] && ! running && ! alive vrstartup && ( flock -n 9 ) 9>"$state/start.lock" } @@ -61,7 +83,7 @@ stop() { done for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done attempts=0 - while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do + while alive 'vrserver|vrcompositor'; do attempts=$((attempts + 1)) if [ "$attempts" = 10 ]; then for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done @@ -69,8 +91,12 @@ stop() { [ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; } sleep 0.1 done + # A SteamVR process killed while holding the IPC mutex in this file leaves it locked, and the next vrserver + # gives up on it ("failed to acquire SysMgrMutex"), so the headset shows an empty void. + alive 'vrserver|vrcompositor|vrstartup|vrdashboard|vrwebhelper' || rm -f /dev/shm/u*-ValveIPCSharedObj-SteamVR unregister quest_settings restore + steam_ui_priority 0 || : } case "${1:-status}" in @@ -81,6 +107,11 @@ launch) "$0" install || exit $? while [ -f "$state/installing" ]; do sleep 1; done fi + if [ -f "$state/quest-immersive" ]; then + : > "$state/xr-request" + echo "asked DroidDeck to open the Quest's immersive view, which starts SteamVR" + exit 0 + fi "$0" start ;; status) @@ -122,7 +153,7 @@ start) flock -n 9 || { echo "SteamVR start already in progress"; exit 0; } installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; } [ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; } - if [ -f "$state/active" ] && { running || pgrep -x vrstartup >/dev/null 2>&1; }; then + if [ -f "$state/active" ] && { running || alive vrstartup; }; then echo "DroidDeck SteamVR is already running" exit 0 fi @@ -215,8 +246,9 @@ JSON export LD_PRELOAD="$layer/libdroiddeck_vr_scheduling.so${LD_PRELOAD:+:$LD_PRELOAD}" if [ "${DROIDDECK_VR_PRESENT:-}" = questwsi ]; then quest_settings apply || exit 1 + steam_ui_priority 10 || : startup_handed_off=0 - trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT + trap '[ "$startup_handed_off" = 1 ] || { quest_settings restore; steam_ui_priority 0 || :; }' EXIT cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so if [ -f "$cvp" ]; then disabled=$cvp.droiddeck-disabled diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr-settings b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr-settings index 723a2b6d5b..b7a4ef457a 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr-settings +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr-settings @@ -4,7 +4,14 @@ import os from pathlib import Path import sys -OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False} +# SteamVR's arm64 build throttles the compositor to save power and skipped refreshes it had time for. +OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False, 'framesToThrottle': 0, 'powersaveFramesToThrottle': 0} +# Backups written before the throttle overrides existed do not record them. +ADDED_LATER = {'framesToThrottle', 'powersaveFramesToThrottle'} + + +def saved_entry(section, key): + return [key in section, section.get(key)] def read(path): @@ -33,6 +40,8 @@ def saved_preferences(path): if not isinstance(backup.get('section'), bool) or not isinstance(backup.get('values'), dict): raise ValueError('invalid backup object') for key in OVERRIDES: + if key not in backup['values'] and key in ADDED_LATER: + continue entry = backup['values'].get(key) if not isinstance(entry, list) or len(entry) != 2 or not isinstance(entry[0], bool): raise ValueError('invalid saved preference: ' + key) @@ -45,12 +54,16 @@ def saved_preferences(path): def update(operation, settings_path, backup_path): settings = read(settings_path) if operation == 'apply': + section = settings.get('steamvr', {}) if backup_path.exists(): - saved_preferences(backup_path) + backup = saved_preferences(backup_path) + missing = [key for key in OVERRIDES if key not in backup['values']] + if missing: + backup['values'].update({key: saved_entry(section, key) for key in missing}) + write(backup_path, backup) else: - section = settings.get('steamvr', {}) write(backup_path, {'section': 'steamvr' in settings, - 'values': {key: [key in section, section.get(key)] for key in OVERRIDES}}) + 'values': {key: saved_entry(section, key) for key in OVERRIDES}}) settings.setdefault('steamvr', {}).update(OVERRIDES) write(settings_path, settings) elif operation == 'restore': @@ -59,6 +72,8 @@ def update(operation, settings_path, backup_path): backup = saved_preferences(backup_path) section = settings.setdefault('steamvr', {}) for key in OVERRIDES: + if key not in backup['values']: + continue present, value = backup['values'][key] if present: section[key] = value diff --git a/tools/tests/test_steamvr_helper.py b/tools/tests/test_steamvr_helper.py index f99f5cbdc2..95df651c7f 100644 --- a/tools/tests/test_steamvr_helper.py +++ b/tools/tests/test_steamvr_helper.py @@ -108,7 +108,8 @@ class SteamVrHelperTest(unittest.TestCase): receiver.bind(str(self.runtime / 'droiddeck-xr-frames')) self.assertIn('present=questwsi lease=unset', self.lease_log()) settings = json.loads((self.home / '.local/share/Steam/config/steamvr.vrsettings').read_text()) - self.assertEqual(settings['steamvr'], {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}) + self.assertEqual(settings['steamvr'], {'enableLinuxVulkanAsync': True, 'motionSmoothing': False, + 'framesToThrottle': 0, 'powersaveFramesToThrottle': 0}) self.assertFalse(cvp.exists()) self.assertEqual(Path(str(cvp) + '.droiddeck-disabled').read_bytes(), b'frame-only backend') @@ -172,6 +173,31 @@ class SteamVrHelperTest(unittest.TestCase): self.assertEqual(json.loads(settings.read_text()), original) self.assertFalse(backup.exists()) + def test_backup_saved_before_new_overrides_keeps_their_current_values(self): + settings = self.root / 'steamvr.vrsettings' + backup = self.root / 'quest-backup.json' + helper = SOURCE.with_name('droiddeck-steamvr-settings') + settings.write_text(json.dumps({'steamvr': {'motionSmoothing': True, 'framesToThrottle': 2}})) + backup.write_text(json.dumps({'section': True, 'values': {'enableLinuxVulkanAsync': [False, None], + 'motionSmoothing': [True, True]}})) + subprocess.run([sys.executable, str(helper), 'apply', str(settings), str(backup)], check=True) + self.assertEqual(json.loads(settings.read_text())['steamvr']['framesToThrottle'], 0) + subprocess.run([sys.executable, str(helper), 'restore', str(settings), str(backup)], check=True) + self.assertEqual(json.loads(settings.read_text()), {'steamvr': {'motionSmoothing': True, 'framesToThrottle': 2}}) + self.assertFalse(backup.exists()) + + def test_backup_missing_an_original_override_is_rejected(self): + settings = self.root / 'steamvr.vrsettings' + backup = self.root / 'quest-backup.json' + helper = SOURCE.with_name('droiddeck-steamvr-settings') + settings.write_text(json.dumps({'steamvr': {'motionSmoothing': False}})) + content = json.dumps({'section': True, 'values': {'motionSmoothing': [True, True]}}) + backup.write_text(content) + result = subprocess.run([sys.executable, str(helper), 'restore', str(settings), str(backup)], + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(backup.read_text(), content) + def test_quest_update_preserves_previous_cvp_backup(self): self.environment['DROIDDECK_VR_PRESENT'] = 'questwsi' cvp = self.steamvr / 'drivers/cv/bin/linuxarm64/libArcturusPerception.so' diff --git a/tools/vr/src/driver_droiddeck.cpp b/tools/vr/src/driver_droiddeck.cpp index 05f3aec58b..c0b2f92ab1 100644 --- a/tools/vr/src/driver_droiddeck.cpp +++ b/tools/vr/src/driver_droiddeck.cpp @@ -530,6 +530,9 @@ bool JoyConLive(const droiddeck_joycon_hand &hand, int64_t nowNs) { nowNs - hand.time_ns < kJoyConStaleNs && hand.time_ns - nowNs < kJoyConStaleNs; } +// Older SteamVR games pick Touch or Vive controls from the tracking system name and treat anything but "oculus" as Vive. +static const char *TrackingSystemName(bool quest) { return quest ? "oculus" : "droiddeck"; } + class HandController : public ITrackedDeviceServerDriver { public: explicit HandController(bool right) : right_(right), arm_(right), camera_(right), luma_(right) {} @@ -1041,7 +1044,8 @@ public: const char *model = touch_ ? "DroidDeck Quest Touch" : index_ ? "DroidDeck Index Hand" : "DroidDeck Pad Hand"; VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, model); VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, touch_ ? "Meta" : index_ ? "Valve" : "DroidDeck"); - VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, "droiddeck"); + VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, TrackingSystemName(xrMode_)); + VRProperties()->SetStringProperty(c, Prop_ActualTrackingSystemName_String, "droiddeck"); VRProperties()->SetStringProperty(c, Prop_RenderModelName_String, touch_ ? (right_ ? "oculus_quest_plus_controller_right" : "oculus_quest_plus_controller_left") : (right_ ? "{indexcontroller}valve_controller_knu_1_0_right" : "{indexcontroller}valve_controller_knu_1_0_left")); @@ -1378,7 +1382,8 @@ public: sentAspect_ = eyeAspect_; VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, xrMode_ ? "DroidDeck Quest OpenXR" : "DroidDeck Cardboard"); VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, "DroidDeck"); - VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, "droiddeck"); + VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, TrackingSystemName(xrMode_)); + VRProperties()->SetStringProperty(c, Prop_ActualTrackingSystemName_String, "droiddeck"); VRProperties()->SetFloatProperty(c, Prop_UserIpdMeters_Float, 0.064f); if (xrMode_) { VRServerDriverHost()->SetDisplayEyeToHead(id_, XrEyeToHead(xr.head, xr.eyes[0].pose), XrEyeToHead(xr.head, xr.eyes[1].pose)); @@ -1447,6 +1452,22 @@ public: DriverPose_t GetPose() override { return GetPose(nullptr); } + static DriverPose_t XrHeadPose(const DroidDeckXrTracking &xr, bool fresh) { + DriverPose_t p = {}; + p.qWorldFromDriverRotation.w = 1; + p.qDriverFromHeadRotation.w = 1; + p.qRotation.w = 1; + p.deviceIsConnected = true; + p.poseIsValid = fresh && XrTrackingFile::Tracked(xr.head); + p.result = p.poseIsValid ? TrackingResult_Running_OK : TrackingResult_Running_OutOfRange; + if (p.poseIsValid) { + p.qRotation = {xr.head.orientation[3], xr.head.orientation[0], xr.head.orientation[1], xr.head.orientation[2]}; + for (int axis = 0; axis < 3; axis++) p.vecPosition[axis] = xr.head.position[axis]; + p.poseTimeOffset = XrTrackingFile::PoseTimeOffset(xr.predicted_ns, XrTrackingFile::Now()); + } + return p; + } + DriverPose_t GetPose(droiddeck_spatialpose *snapshot) { std::lock_guard lock(spatialMutex_); DriverPose_t p = {}; @@ -1455,17 +1476,7 @@ public: p.qRotation.w = 1; DroidDeckXrTracking xr; bool freshXr = xr_.Read(&xr) && XrTrackingFile::Fresh(xr); - if (freshXr || xrMode_) { - p.deviceIsConnected = true; - p.poseIsValid = freshXr && XrTrackingFile::Tracked(xr.head); - p.result = p.poseIsValid ? TrackingResult_Running_OK : TrackingResult_Running_OutOfRange; - if (p.poseIsValid) { - p.qRotation = {xr.head.orientation[3], xr.head.orientation[0], xr.head.orientation[1], xr.head.orientation[2]}; - for (int axis = 0; axis < 3; axis++) p.vecPosition[axis] = xr.head.position[axis]; - p.poseTimeOffset = XrTrackingFile::PoseTimeOffset(xr.predicted_ns, XrTrackingFile::Now()); - } - return p; - } + if (freshXr || xrMode_) return XrHeadPose(xr, freshXr); p.vecPosition[1] = 1.6; droiddeck_headpose hp; bool ok = pose_.Read(&hp); @@ -1580,19 +1591,44 @@ private: droiddeck_joycon joyCons = {}; bool haveJoyCons = false; auto lastSent = std::chrono::steady_clock::now(); + uint32_t lastLatch = 0; + bool headInvalid = false; + auto lastHands = lastSent - std::chrono::seconds(1); + auto publishHead = [&](const DriverPose_t &head) { + headInvalid = !head.poseIsValid; + VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(head)); + }; while (running_) { DroidDeckXrTracking xr; if (xrMode_) { - bool fresh = xr_.Read(&xr) && XrTrackingFile::Fresh(xr); - if (fresh) PublishChaperone(xr); - DriverPose_t head = GetPose(); - VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(head)); - for (int hand = 0; hand < 2; hand++) if (CardboardController *pad = ActiveHand(hand)) { - DroidDeckXrHand state = fresh ? xr.hands[hand] : DroidDeckXrHand{}; - pad->UpdateXr(state, fresh ? xr.predicted_ns : 0); + DroidDeckXrTracking latched; + const bool haveLatch = latch_.Read(&latched) && XrTrackingFile::Fresh(latched); + const auto now = std::chrono::steady_clock::now(); + const bool latchAdvanced = haveLatch && latched.seq != lastLatch; + if (haveLatch) { + if (latchAdvanced) { + lastLatch = latched.seq; + publishHead(XrHeadPose(latched, true)); + } + } else if (now - lastHands >= std::chrono::milliseconds(2)) { + publishHead(GetPose()); } - VRDriverInput()->UpdateBooleanComponent(proximity_, fresh, 0); - std::this_thread::sleep_for(std::chrono::milliseconds(2)); + if (now - lastHands >= std::chrono::milliseconds(2)) { + lastHands = now; + bool fresh = xr_.Read(&xr) && XrTrackingFile::Fresh(xr); + if (fresh) PublishChaperone(xr); + if (haveLatch && !latchAdvanced) { + if (!(fresh && XrTrackingFile::Tracked(xr.head))) publishHead(XrHeadPose(xr, fresh)); + else if (!XrTrackingFile::Tracked(latched.head)) publishHead(XrHeadPose(xr, fresh)); + else if (headInvalid) publishHead(XrHeadPose(latched, true)); + } + for (int hand = 0; hand < 2; hand++) if (CardboardController *pad = ActiveHand(hand)) { + DroidDeckXrHand state = fresh ? xr.hands[hand] : DroidDeckXrHand{}; + pad->UpdateXr(state, fresh ? xr.predicted_ns : 0); + } + VRDriverInput()->UpdateBooleanComponent(proximity_, fresh, 0); + } + std::this_thread::sleep_for(std::chrono::microseconds(500)); continue; } droiddeck_headpose hp; @@ -1735,7 +1771,7 @@ private: if (!poses[i].bDeviceIsConnected) continue; PropertyContainerHandle_t c = VRProperties()->TrackedDeviceToPropertyContainer(i); if (VRProperties()->GetInt32Property(c, Prop_DeviceClass_Int32) != TrackedDeviceClass_Controller) continue; - if (VRProperties()->GetStringProperty(c, Prop_TrackingSystemName_String) != "droiddeck") return true; + if (VRProperties()->GetStringProperty(c, Prop_SerialNumber_String).rfind("droiddeck-", 0) != 0) return true; } return false; } @@ -1770,6 +1806,7 @@ private: DriverPose_t lastSpatial_{}; droiddeck_spatialpose lastSpatialSnapshot_{}; XrTrackingFile xr_; + XrTrackingFile latch_{"/run/droiddeck/" DROIDDECK_XR_LATCH_FILE}; XrChaperoneOrigin chaperone_; bool xrMode_ = false; PadRing pad_; diff --git a/tools/vr/src/scheduling.c b/tools/vr/src/scheduling.c index 381397cea7..fd87c20472 100644 --- a/tools/vr/src/scheduling.c +++ b/tools/vr/src/scheduling.c @@ -1,8 +1,11 @@ #define _GNU_SOURCE +#include #include #include #include +#include #include +#include #include #include #include @@ -19,6 +22,38 @@ static int cannot_schedule_realtime(void) { return !(caps[CAP_SYS_NICE / 32].effective & (UINT32_C(1) << (CAP_SYS_NICE % 32))); } +/* Without real-time scheduling, vrcompositor's frame threads ran at the same nice level as Steam's web helpers on + * the guest's three cores and missed refreshes. Its threads at normal priority take the highest nice level instead; + * some are started where they do not inherit it, so they are raised again once a second. */ +static int compositor_without_realtime(void) { + return !strcmp(program_invocation_short_name, "vrcompositor") && cannot_schedule_realtime(); +} + +static void raise_threads(void) { + DIR *tasks = opendir("/proc/self/task"); + if (!tasks) return; + for (struct dirent *task; (task = readdir(tasks));) { + const int tid = atoi(task->d_name); + if (tid <= 0) continue; + errno = 0; + const int nice = getpriority(PRIO_PROCESS, (id_t)tid); + if (!errno && nice <= 0 && nice > -20) setpriority(PRIO_PROCESS, (id_t)tid, -20); + } + closedir(tasks); +} + +static void *raise_loop(void *unused) { + for (;;) { raise_threads(); sleep(1); } + return unused; +} + +__attribute__((constructor)) static void raise_compositor(void) { + if (!compositor_without_realtime()) return; + setpriority(PRIO_PROCESS, 0, -20); + pthread_t thread; + if (!pthread_create(&thread, NULL, raise_loop, NULL)) pthread_detach(thread); +} + int setrlimit(__rlimit_resource_t resource, const struct rlimit *limit) { int (*next)(__rlimit_resource_t, const struct rlimit *) = dlsym(RTLD_NEXT, "setrlimit"); if (!next) { errno = ENOSYS; return -1; } diff --git a/tools/vr/src/vk_layer_droiddeck_vr.c b/tools/vr/src/vk_layer_droiddeck_vr.c index be74139e5f..8eddc8a840 100644 --- a/tools/vr/src/vk_layer_droiddeck_vr.c +++ b/tools/vr/src/vk_layer_droiddeck_vr.c @@ -294,9 +294,12 @@ static void forget_device_semaphores(VkDevice dev); static void track_forget_device(VkDevice dev); static void producer_destroy_device(struct dev *device, const VkAllocationCallbacks *allocator); +static void warp_forget(VkDevice device, VkRenderPass pass); + static void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallbacks *alloc) { struct dev *d = dev_for(device); if (!d) return; + warp_forget(device, VK_NULL_HANDLE); #ifdef DROIDDECK_WSI_CAPTURE droiddeck_wsi_destroy(device); #endif @@ -585,9 +588,28 @@ static void VKAPI_CALL DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapc NEXT(device, DestroySwapchainKHR)(device, swapchain, allocator); } +static VkResult VKAPI_CALL AcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, + VkFence fence, uint32_t *index) { + VkResult r = NEXT(device, AcquireNextImageKHR)(device, swapchain, timeout, semaphore, fence, index); +#ifdef DROIDDECK_WSI_CAPTURE + if (r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR) droiddeck_wsi_acquired(device, swapchain, *index); +#endif + return r; +} + +static VkResult VKAPI_CALL AcquireNextImage2KHR(VkDevice device, const VkAcquireNextImageInfoKHR *info, uint32_t *index) { + VkResult r = NEXT(device, AcquireNextImage2KHR)(device, info, index); +#ifdef DROIDDECK_WSI_CAPTURE + if (r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR) droiddeck_wsi_acquired(device, info->swapchain, *index); +#endif + return r; +} + static PFN_vkVoidFunction display_device_hook(const char *name) { HOOK_AS("vkCreateSwapchainKHR", CreateSwapchainKHR) HOOK_AS("vkDestroySwapchainKHR", DestroySwapchainKHR) + HOOK_AS("vkAcquireNextImageKHR", AcquireNextImageKHR) + HOOK_AS("vkAcquireNextImage2KHR", AcquireNextImage2KHR) HOOK_AS("vkDisplayPowerControlEXT", DisplayPowerControlEXT) HOOK_AS("vkRegisterDeviceEventEXT", RegisterDeviceEventEXT) HOOK_AS("vkRegisterDisplayEventEXT", RegisterDisplayEventEXT) @@ -1383,6 +1405,100 @@ static VkResult VKAPI_CALL CreateImage(VkDevice d, const VkImageCreateInfo *ci, return r; } +/* vrcompositor renders both eyes through one shared texture and warps each into its half of the output in the + * same command buffer. On Turnip its barrier before the right eye's warp left the texture cache holding the + * left eye, so blocks of the left eye showed in the right one. A full barrier before each warp pass fixes it. */ +#define WARP_PASSES 32 +static struct { VkDevice device; VkRenderPass pass; } g_warp_passes[WARP_PASSES]; +static pthread_mutex_t g_warp_lock = PTHREAD_MUTEX_INITIALIZER; + +static int warp_wanted(void) { + static int wanted = -1; + if (wanted < 0) { + const char *mode = getenv("DROIDDECK_VR_PRESENT"); + wanted = mode && !strcmp(mode, "questwsi") && !strcmp(program_invocation_short_name, "vrcompositor"); + } + return wanted; +} + +static void warp_note(VkDevice device, VkRenderPass pass, uint32_t attachments, VkSampleCountFlagBits samples) { + if (attachments != 1 || samples != VK_SAMPLE_COUNT_1_BIT) return; + pthread_mutex_lock(&g_warp_lock); + for (int i = 0; i < WARP_PASSES; i++) + if (!g_warp_passes[i].pass) { g_warp_passes[i].device = device; g_warp_passes[i].pass = pass; break; } + pthread_mutex_unlock(&g_warp_lock); +} + +static void warp_forget(VkDevice device, VkRenderPass pass) { + pthread_mutex_lock(&g_warp_lock); + for (int i = 0; i < WARP_PASSES; i++) + if (g_warp_passes[i].device == device && (!pass || g_warp_passes[i].pass == pass)) + g_warp_passes[i].device = VK_NULL_HANDLE, g_warp_passes[i].pass = VK_NULL_HANDLE; + pthread_mutex_unlock(&g_warp_lock); +} + +static int warp_pass(VkRenderPass pass) { + int found = 0; + pthread_mutex_lock(&g_warp_lock); + for (int i = 0; i < WARP_PASSES && !found; i++) found = pass && g_warp_passes[i].pass == pass; + pthread_mutex_unlock(&g_warp_lock); + return found; +} + +static VkResult VKAPI_CALL CreateRenderPass(VkDevice d, const VkRenderPassCreateInfo *ci, const VkAllocationCallbacks *a, VkRenderPass *out) { + VkResult r = NEXT(d, CreateRenderPass)(d, ci, a, out); + if (r == VK_SUCCESS) warp_note(d, *out, ci->attachmentCount, ci->attachmentCount ? ci->pAttachments[0].samples : 0); + return r; +} + +static void VKAPI_CALL DestroyRenderPass(VkDevice d, VkRenderPass pass, const VkAllocationCallbacks *a) { + if (pass) warp_forget(d, pass); + NEXT(d, DestroyRenderPass)(d, pass, a); +} + +static VkResult VKAPI_CALL CreateRenderPass2(VkDevice d, const VkRenderPassCreateInfo2 *ci, const VkAllocationCallbacks *a, VkRenderPass *out) { + PFN_vkCreateRenderPass2 next = (PFN_vkCreateRenderPass2)dev_for(d)->gdpa(d, "vkCreateRenderPass2"); + if (!next) next = (PFN_vkCreateRenderPass2)dev_for(d)->gdpa(d, "vkCreateRenderPass2KHR"); + VkResult r = next(d, ci, a, out); + if (r == VK_SUCCESS) warp_note(d, *out, ci->attachmentCount, ci->attachmentCount ? ci->pAttachments[0].samples : 0); + return r; +} + +static void warp_barrier(VkCommandBuffer cb, VkRenderPass pass) { + if (!warp_pass(pass)) return; + struct dev *d = dev_for(cb); + VkMemoryBarrier all = {VK_STRUCTURE_TYPE_MEMORY_BARRIER, NULL, VK_ACCESS_MEMORY_WRITE_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT}; + ((PFN_vkCmdPipelineBarrier)d->gdpa(d->handle, "vkCmdPipelineBarrier"))(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &all, 0, NULL, 0, NULL); +} + +static void VKAPI_CALL CmdBeginRenderPass(VkCommandBuffer cb, const VkRenderPassBeginInfo *bi, VkSubpassContents contents) { + warp_barrier(cb, bi->renderPass); + struct dev *d = dev_for(cb); + ((PFN_vkCmdBeginRenderPass)d->gdpa(d->handle, "vkCmdBeginRenderPass"))(cb, bi, contents); +} + +static void VKAPI_CALL CmdBeginRenderPass2(VkCommandBuffer cb, const VkRenderPassBeginInfo *bi, const VkSubpassBeginInfo *si) { + warp_barrier(cb, bi->renderPass); + struct dev *d = dev_for(cb); + PFN_vkCmdBeginRenderPass2 next = (PFN_vkCmdBeginRenderPass2)d->gdpa(d->handle, "vkCmdBeginRenderPass2"); + if (!next) next = (PFN_vkCmdBeginRenderPass2)d->gdpa(d->handle, "vkCmdBeginRenderPass2KHR"); + next(cb, bi, si); +} + +static PFN_vkVoidFunction warp_hook(const char *name) { + if (!warp_wanted()) return NULL; + HOOK_AS("vkCreateRenderPass", CreateRenderPass) + HOOK_AS("vkCreateRenderPass2", CreateRenderPass2) + HOOK_AS("vkCreateRenderPass2KHR", CreateRenderPass2) + HOOK_AS("vkDestroyRenderPass", DestroyRenderPass) + HOOK_AS("vkCmdBeginRenderPass", CmdBeginRenderPass) + HOOK_AS("vkCmdBeginRenderPass2", CmdBeginRenderPass2) + HOOK_AS("vkCmdBeginRenderPass2KHR", CmdBeginRenderPass2) + return NULL; +} + static PFN_vkVoidFunction semaphore_hook(const char *name) { HOOK_AS("vkCreateImage", CreateImage) HOOK_AS("vkCreateSemaphore", CreateSemaphore) @@ -1445,7 +1561,8 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVr_GetInstanceProcAddr( if (f) return f; } if (in) { - PFN_vkVoidFunction f = semaphore_hook(name); + PFN_vkVoidFunction f = warp_hook(name); + if (!f) f = semaphore_hook(name); if (f && in->gipa(instance, name)) return f; } return in ? in->gipa(instance, name) : NULL; @@ -1461,7 +1578,8 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVr_GetDeviceProcAddr(Vk if (f) return f; } if (d) { - PFN_vkVoidFunction mine = semaphore_hook(name); + PFN_vkVoidFunction mine = warp_hook(name); + if (!mine) mine = semaphore_hook(name); if (mine && d->gdpa(device, name)) return mine; } return d ? d->gdpa(device, name) : NULL; diff --git a/tools/vr/src/wsi_capture.cpp b/tools/vr/src/wsi_capture.cpp index ee7a7266c9..2c9c2f2181 100644 --- a/tools/vr/src/wsi_capture.cpp +++ b/tools/vr/src/wsi_capture.cpp @@ -41,6 +41,7 @@ struct CaptureSlot { bool rgbaInitialized{}; void *mapping{}; VkFence fence{}; + uint64_t uses{}; bool busy{}, queued{}; DroidDeckXrFrameHeader header{}; ~CaptureSlot() { Clear(); } @@ -134,9 +135,13 @@ struct Swapchain { VkFormat format{}; std::vector images; std::vector ready; + std::vector> copying; std::array slots; uint64_t frame{}; XrTrackingFile tracking; + XrLatchWriter latch; + DroidDeckXrTracking previous{}; + bool latched{}; XrFrameSender sender; XrGpuSender gpuSender; bool gpu{}; @@ -158,17 +163,47 @@ struct Swapchain { std::fprintf(stderr, "[droiddeck-vr-layer] WSI worker failed; restart SteamVR\n"); } } + // The headset takes one frame per display refresh, so waiting for each acknowledgement before sending the + // next left SteamVR's frames missing that refresh: up to two frames travel at once, each slot freed by its ack. + static constexpr size_t kInFlight = 2; + std::vector> inFlight; + int64_t oldestSent{}; + bool CollectAcks(int timeout) { + if (!gpu || inFlight.empty()) return true; + bool ok = gpuSender.Acks(timeout, [this](uint64_t ack) { + auto it = std::find_if(inFlight.begin(), inFlight.end(), [ack](const auto &item) { return item.first == ack; }); + if (it == inFlight.end()) return false; + { std::lock_guard lock(sendMutex); it->second->busy = false; } + inFlight.erase(it); + oldestSent = XrTrackingFile::Now(); + return true; + }); + return ok && (inFlight.empty() || XrTrackingFile::Now() - oldestSent < 5000000000LL); + } void Loop() { for (;;) { + if (!CollectAcks(0)) { + std::lock_guard lock(sendMutex); + std::fprintf(stderr, "[droiddeck-vr-layer] WSI headset stopped acknowledging frames; restart SteamVR\n"); + failed = true; return; + } CaptureSlot *slot; { std::unique_lock lock(sendMutex); - sendReady.wait(lock, [this] { - return stopping || std::any_of(slots.begin(), slots.end(), [](const auto &item) { return item.queued; }); - }); + auto ready = [this] { + return stopping || (inFlight.size() < kInFlight + && std::any_of(slots.begin(), slots.end(), [](const auto &item) { return item.queued; })); + }; + if (inFlight.empty()) sendReady.wait(lock, ready); + else if (!ready()) { + lock.unlock(); + CollectAcks(1); + continue; + } + if (stopping) return; slot = nullptr; for (auto &item : slots) if (item.queued && (!slot || item.header.frame_id < slot->header.frame_id)) slot = &item; - if (!slot) return; + if (!slot) continue; slot->queued = false; } auto &d = *device; @@ -182,10 +217,16 @@ struct Swapchain { VkMappedMemoryRange range{VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE}; range.memory = memory; range.size = VK_WHOLE_SIZE; if (result == VK_SUCCESS && !gpu) result = d.InvalidateMappedMemoryRanges(d.handle, 1, &range); int64_t invalidated = XrTrackingFile::Now(); + bool posted = false; if (result == VK_SUCCESS && XrTrackingFile::Now() - header.captured_ns < 200000000LL) { if (gpu) { uint32_t flags = (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) ? XR_GPU_BGRA : 0; - if (!gpuSender.Send(header, static_cast(slot - slots.data()), flags)) result = VK_ERROR_DEVICE_LOST; + if (!gpuSender.Post(header, static_cast(slot - slots.data()), flags)) result = VK_ERROR_DEVICE_LOST; + else { + if (inFlight.empty()) oldestSent = XrTrackingFile::Now(); + inFlight.emplace_back(header.frame_id, slot); + posted = true; + } } else sender.SendShared("/run/droiddeck/" DROIDDECK_XR_FRAME_SOCKET, header, sharedFd); } if (header.frame_id % 120 == 0) std::fprintf(stderr, "[droiddeck-vr-layer] WSI ms wait=%.2f invalidate=%.2f shared=%.2f\n", @@ -195,7 +236,7 @@ struct Swapchain { std::fprintf(stderr, "[droiddeck-vr-layer] WSI buffer quarantined: result=%d leaseLost=%d; restart SteamVR\n", result, sender.SharedLeaseLost()); failed = true; return; } - slot->busy = false; + if (!posted) slot->busy = false; } } bool Initialize(VkSwapchainKHR chain, VkQueue queue) { @@ -211,6 +252,7 @@ struct Swapchain { images.resize(count); if (d.GetSwapchainImagesKHR(d.handle, chain, &count, images.data())) return false; ready.resize(count); + copying.assign(count, {nullptr, 0}); VkSemaphoreCreateInfo semaphoreInfo{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; for (auto &semaphore : ready) if (d.CreateSemaphore(d.handle, &semaphoreInfo, nullptr, &semaphore)) return false; XrGpuPoolInfo info; @@ -236,8 +278,11 @@ struct Swapchain { return result; } bool Header(DroidDeckXrFrameHeader &header) { - DroidDeckXrTracking packet{}; - if (!tracking.Read(&packet) || !XrTrackingFile::Fresh(packet)) return false; + DroidDeckXrTracking latest{}; + if (!tracking.Read(&latest) || !XrTrackingFile::Fresh(latest)) return false; + DroidDeckXrTracking packet = latched && XrTrackingFile::Fresh(previous) ? previous : latest; + previous = latest; latched = true; + latch.Write(latest); header = {}; header.magic = DROIDDECK_XR_FRAME_MAGIC; header.version = DROIDDECK_XR_FRAME_VERSION; header.width = extent.width; header.height = extent.height; @@ -260,6 +305,15 @@ struct Swapchain { } return xr_frame_valid(header); } + // The headless swapchain hands an image back as soon as it is presented, and KGSL has no implicit sync, so + // the compositor drew its next frame into an image this copy still read: blocky panels. The copy is waited + // for when the image is acquired again, by which time it has nearly always finished, rather than stalling + // the compositor in every present. + void Acquired(uint32_t index) { + if (index >= copying.size() || !copying[index].first) return; + CaptureSlot &slot = *copying[index].first; + if (slot.uses == copying[index].second) device->WaitForFences(device->handle, 1, &slot.fence, VK_TRUE, UINT64_MAX); + } VkResult Capture(VkQueue queue, uint32_t index, const VkPresentInfoKHR &present, VkSemaphore *completion) { auto &d = *device; if (index >= images.size()) return VK_ERROR_OUT_OF_DATE_KHR; @@ -329,6 +383,8 @@ struct Swapchain { submit.pWaitDstStageMask = stages.data(); submit.commandBufferCount = 1; submit.pCommandBuffers = &command; submit.signalSemaphoreCount = 1; submit.pSignalSemaphores = &ready[index]; if ((result = d.QueueSubmit(queue, 1, &submit, fence))) return Fail(result, slot); + if (copying.size() < images.size()) copying.resize(images.size(), {nullptr, 0}); + copying[index] = {&slot, ++slot.uses}; rgbaInitialized = true; { std::lock_guard lock(sendMutex); slot.header = header; slot.queued = true; sendReady.notify_all(); } *completion = ready[index]; @@ -379,6 +435,11 @@ extern "C" void droiddeck_wsi_swapchain(VkDevice device, VkSwapchainKHR chain, c chainState->extent = create->imageExtent; chainState->format = create->imageFormat; swapchains[chain] = std::move(chainState); } +extern "C" void droiddeck_wsi_acquired(VkDevice device, VkSwapchainKHR chain, uint32_t index) { + (void)device; std::lock_guard lock(mutex); + auto it = swapchains.find(chain); + if (it != swapchains.end() && it->second->initialized) it->second->Acquired(index); +} extern "C" void droiddeck_wsi_forget(VkDevice device, VkSwapchainKHR chain) { (void)device; std::lock_guard lock(mutex); swapchains.erase(chain); } diff --git a/tools/vr/src/wsi_capture.h b/tools/vr/src/wsi_capture.h index d56aab4eac..887b87a395 100644 --- a/tools/vr/src/wsi_capture.h +++ b/tools/vr/src/wsi_capture.h @@ -10,6 +10,7 @@ void droiddeck_wsi_device(VkDevice device, VkPhysicalDevice physical, VkInstance void droiddeck_wsi_destroy(VkDevice device); void droiddeck_wsi_swapchain(VkDevice device, VkSwapchainKHR swapchain, const VkSwapchainCreateInfoKHR *create); void droiddeck_wsi_forget(VkDevice device, VkSwapchainKHR swapchain); +void droiddeck_wsi_acquired(VkDevice device, VkSwapchainKHR swapchain, uint32_t index); VkResult droiddeck_wsi_present(VkDevice device, VkQueue queue, const VkPresentInfoKHR *present, PFN_vkQueuePresentKHR next); #ifdef __cplusplus diff --git a/tools/vr/src/xr_gpu_channel.h b/tools/vr/src/xr_gpu_channel.h index 52fb5d9d39..c0b9797ff5 100644 --- a/tools/vr/src/xr_gpu_channel.h +++ b/tools/vr/src/xr_gpu_channel.h @@ -111,6 +111,21 @@ public: || !xr_gpu_receive(socket_, &ack, sizeof(ack)) || ack != header.frame_id) { Close(); return false; } return true; } + bool Post(const DroidDeckXrFrameHeader &header, uint32_t slot, uint32_t flags = 0) { + if (socket_ < 0 || slot >= XR_GPU_SLOTS || (flags & ~XR_GPU_BGRA) || !xr_frame_valid(header)) return false; + XrGpuFrame frame; frame.header = header; frame.slot = slot; frame.flags = flags; + if (!xr_gpu_send(socket_, &frame, sizeof(frame))) { Close(); return false; } + return true; + } + template bool Acks(int timeout, Visit visit) { + if (socket_ < 0) return false; + while (xr_gpu_wait(socket_, timeout)) { + uint64_t ack{}; + if (!xr_gpu_receive(socket_, &ack, sizeof(ack)) || !visit(ack)) { Close(); return false; } + timeout = 0; + } + return true; + } void Close() { if (socket_ >= 0) close(socket_); socket_ = -1; } private: int socket_ = -1; diff --git a/tools/vr/src/xr_tracking_file.h b/tools/vr/src/xr_tracking_file.h index 1b122d412d..5bd314fde0 100644 --- a/tools/vr/src/xr_tracking_file.h +++ b/tools/vr/src/xr_tracking_file.h @@ -2,6 +2,7 @@ #include "xr_tracking.h" #include #include +#include #include #include #include @@ -38,8 +39,16 @@ public: } return false; } + // Android stamps these packets with the real monotonic clock. The session's clockpause preload holds the + // guest's clock back by the time spent suspended, so read libc's clock directly. static int64_t Now() { - timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); + using ClockGettime = int (*)(clockid_t, timespec *); + static const ClockGettime real = [] { + void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD); + void *symbol = libc ? dlsym(libc, "clock_gettime") : nullptr; + return symbol ? reinterpret_cast(symbol) : &clock_gettime; + }(); + timespec now{}; real(CLOCK_MONOTONIC, &now); return (int64_t)now.tv_sec * 1000000000LL + now.tv_nsec; } static double PoseTimeOffset(int64_t predicted, int64_t now) { @@ -66,3 +75,36 @@ private: std::mutex mutex_; std::string path_; }; + +#define DROIDDECK_XR_LATCH_FILE "droiddeck-xr-latch" + +// The compositor's capture latches one head pose per frame here; the driver hands SteamVR exactly that pose, +// so the frame drawn next and the pose the headset reprojects it with are the same sample. +class XrLatchWriter { +public: + ~XrLatchWriter() { if (mapping_) munmap(mapping_, sizeof(*mapping_)); } + void Write(const DroidDeckXrTracking &packet) { + if (!mapping_ && !Open()) return; + const uint32_t sequence = __atomic_load_n(&mapping_->seq, __ATOMIC_RELAXED) | 1u; + __atomic_store_n(&mapping_->seq, sequence, __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_RELEASE); + DroidDeckXrTracking copy = packet; copy.seq = sequence; + std::memcpy(mapping_, ©, sizeof(copy)); + __atomic_store_n(&mapping_->seq, sequence + 1, __ATOMIC_RELEASE); + } +private: + bool Open() { + if (attempted_) return false; + attempted_ = true; + int descriptor = open("/run/droiddeck/" DROIDDECK_XR_LATCH_FILE, O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (descriptor < 0) return false; + void *mapping = ftruncate(descriptor, sizeof(*mapping_)) == 0 + ? mmap(nullptr, sizeof(*mapping_), PROT_READ | PROT_WRITE, MAP_SHARED, descriptor, 0) : MAP_FAILED; + close(descriptor); + if (mapping == MAP_FAILED) return false; + mapping_ = static_cast(mapping); + return true; + } + DroidDeckXrTracking *mapping_ = nullptr; + bool attempted_ = false; +};