This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 21:27:42 -04:00
1 parent 4163b31b02
commit 83ec5708ed
852 files changed
+4844 -46144

No files matched your search

+7 -51
View File
@@ -1,15 +1,3 @@
// SteamVR driver for DroidDeck's Cardboard mode: one 3DoF HMD whose pose is the phone's rotation
// sensor, read from the head pose file the app shares with the guest
// (app/src/main/cpp/waylandcomp/src/headpose_shm.h, /run/droiddeck/droiddeck-headpose).
//
// The HMD renders an undistorted side-by-side pair: the app's Cardboard pass, in its side-by-side
// mode, does the lens distortion for the viewer the user picked. So the projection here is exactly
// the frustum that pass samples (tan_half_fov, eye_aspect from the pose file), and the distortion is
// the identity.
//
// How the frames reach the screen is the open question this driver is for: see docs/cardboard-vr.md.
// It exposes IVRDisplayComponent with the display "on the desktop" (extended mode) at the session's
// size, and logs what vrserver / vrcompositor ask of it.
#include "openvr_driver.h"
#include <algorithm>
@@ -50,7 +38,6 @@ void Log(const char *fmt, ...) {
fprintf(stderr, "[droiddeck] %s\n", buf);
}
// The shared pose file, mapped read-only; reads follow the seqlock in headpose_shm.h.
class PoseFile {
public:
bool Read(droiddeck_headpose *out) {
@@ -82,7 +69,6 @@ private:
};
HmdQuaternion_t QuatFromMatrix(const float m[9]) {
// Row-major rotation -> quaternion (Shepperd's method).
HmdQuaternion_t q;
float tr = m[0] + m[4] + m[8];
if (tr > 0.0f) {
@@ -101,8 +87,6 @@ HmdQuaternion_t QuatFromMatrix(const float m[9]) {
return q;
}
// IVRVirtualDisplay: the compositor renders the final frame into its own backbuffer and hands it
// here instead of scanning it out. What the handle is on Linux is what this logs (experiment).
class VirtualDisplay : public IVRVirtualDisplay {
public:
void Present(const PresentInfo_t *info, uint32_t size) override {
@@ -115,7 +99,6 @@ public:
}
void WaitForPresent() override {}
bool GetTimeSinceLastVsync(float *seconds, uint64_t *counter) override {
// A free-running 60 Hz vsync.
using namespace std::chrono;
double t = duration<double>(steady_clock::now().time_since_epoch()).count();
double period = 1.0 / 60.0;
@@ -129,8 +112,6 @@ private:
std::chrono::steady_clock::time_point last_;
};
// The vsync grid SteamVR paces against in driver-direct mode (Prop_DriverDirectModeSendsVsyncEvents):
// a free-running 60 Hz tick, declared a little ahead of time (ALVR's announcer, alvr/server_openvr/src/vsync.rs).
class Vsync {
public:
static constexpr std::chrono::nanoseconds kInterval{16666667};
@@ -172,10 +153,6 @@ private:
static inline std::chrono::steady_clock::time_point last_{};
};
// IVRDriverDirectModeComponent: SteamVR renders each eye into textures this driver allocates
// (shared Vulkan images from SteamVR's IPC resource manager, dmabufs on Linux) and hands them
// over per frame. This is how ALVR gets frames on Linux; it avoids the compositor's own direct mode,
// which needs VK_KHR_display - something Turnip on KGSL refuses outright.
class DirectMode : public IVRDriverDirectModeComponent {
public:
struct Set {
@@ -190,8 +167,8 @@ public:
Set set;
set.pid = pid;
set.desc = *d;
const uint32_t usage = 0x1 /* TRANSFER_SRC */ | 0x4 /* SAMPLED */ | 0x80 /* INPUT_ATTACHMENT */;
const uint32_t create = 0x8 /* MUTABLE_FORMAT */;
const uint32_t usage = 0x1 | 0x4 | 0x80 ;
const uint32_t create = 0x8 ;
for (int i = 0; i < 3; i++) {
SharedTextureHandle_t h = 0;
if (!VRIPCResourceManager()->NewSharedVulkanImage(d->nFormat, d->nWidth, d->nHeight, true, false, true, 1, 1,
@@ -245,7 +222,6 @@ public:
void SubmitLayer(const SubmitLayerPerEye_t (&eyes)[2]) override {
layers_++;
// The first layer of a frame is the compositor's own picture; overlays after it are not drawn yet.
if (layerInFrame_++ == 0) {
for (int e = 0; e < 2; e++) {
frame_.texture[e] = eyes[e].hTexture;
@@ -274,7 +250,6 @@ public:
}
void PostPresent(const Throttling_t *t) override {
// Hold until the tick after the last one declared (ALVR's pacing): a slow frame costs one frame.
auto last = Vsync::LastTick();
auto until = last + Vsync::kInterval * (1 + (t ? t->nFramesToThrottle : 0));
if (until > std::chrono::steady_clock::now()) std::this_thread::sleep_until(until);
@@ -304,12 +279,9 @@ private:
droiddeck::EyeFrame frame_{};
};
// The session's game pad, as the app publishes it for the guest: the absolute-state snapshot at the
// head of fake input ring 0 (app/src/main/cpp/fakeinput_steam.cpp, FakeInputRingHeader), under a
// seqlock. FAKE_EVDEV_MEMFD_PATHS names the rings in every session process's environment.
struct PadState {
uint32_t buttons = 0; // bit order of FakeInputWriter.BUTTON_MAP; bit 11 = the QAM button
int16_t axes[8] = {}; // X, Y, RX, RY (+-32767), GAS = right trigger, BRAKE = left (0..255), HAT0X, HAT0Y
uint32_t buttons = 0;
int16_t axes[8] = {};
};
enum : uint32_t {
PAD_A = 1u << 0, PAD_B = 1u << 1, PAD_X = 1u << 2, PAD_Y = 1u << 3, PAD_LB = 1u << 4, PAD_RB = 1u << 5,
@@ -340,7 +312,7 @@ private:
std::string path;
if (const char *env = getenv("DROIDDECK_VR_PAD_RING")) path = env;
if (path.empty()) {
const char *paths = getenv("FAKE_EVDEV_MEMFD_PATHS"); // "0=/path;1=/path;..."
const char *paths = getenv("FAKE_EVDEV_MEMFD_PATHS");
if (paths && !strncmp(paths, "0=", 2)) path.assign(paths + 2, strcspn(paths + 2, ";"));
}
if (path.empty()) {
@@ -363,10 +335,6 @@ private:
std::chrono::steady_clock::time_point retry_{};
};
// One hand: a Vive-profile controller driven by the game pad. 3DoF, so it is a gaze pointer: it sits
// low in front of its side of the body and points where the head looks, and SteamVR's laser follows the
// view. Right hand: right stick = trackpad, A = trackpad click, RT = trigger, RB = grip, Start = menu,
// the Steam/guide button = system. Left: left stick, X, LT, LB, Select.
class CardboardController : public ITrackedDeviceServerDriver {
public:
explicit CardboardController(bool right) : right_(right) {}
@@ -404,14 +372,12 @@ public:
DriverPose_t GetPose() override { return pose_; }
// From the driver's pose thread: the head's orientation and the pad.
void Update(const HmdQuaternion_t &head, const PadState *pad) {
if (id_ == k_unTrackedDeviceIndexInvalid) return;
DriverPose_t p = {};
p.qWorldFromDriverRotation.w = 1;
p.qDriverFromHeadRotation.w = 1;
p.qRotation = head;
// Low and in front of its side, in head space, then into the room with the head's rotation.
const double off[3] = {right_ ? 0.18 : -0.18, -0.35, -0.30};
double m[3][3];
const double w = head.w, x = head.x, y = head.y, z = head.z;
@@ -460,7 +426,6 @@ public:
if (height_ <= 0) height_ = 1080;
float hz = VRSettings()->GetFloat(kSettingsSection, "displayFrequency");
if (hz <= 0.0f) hz = 60.0f;
// Until the app has drawn an eye: the Cardboard pass's defaults for a 1920x1080 panel.
tanHalf_ = 1.0f;
eyeAspect_ = (width_ * 0.5f) / height_;
droiddeck_headpose hp;
@@ -476,8 +441,6 @@ public:
VRProperties()->SetFloatProperty(c, Prop_DisplayFrequency_Float, hz);
VRProperties()->SetFloatProperty(c, Prop_SecondsFromVsyncToPhotons_Float, 0.011f);
VRProperties()->SetUint64Property(c, Prop_CurrentUniverseId_Uint64, 2);
// Off the desktop: with a direct mode component that sends SteamVR's compositor down the
// driver-direct path; on it, the compositor opens its own direct mode window (VK_KHR_display).
VRProperties()->SetBoolProperty(c, Prop_IsOnDesktop_Bool, false);
VRProperties()->SetBoolProperty(c, Prop_DisplayDebugMode_Bool, false);
directMode_ = VRSettings()->GetBool(kSettingsSection, "directMode");
@@ -489,9 +452,6 @@ public:
VRProperties()->SetBoolProperty(c, Prop_HasDisplayComponent_Bool, true);
virtualDisplay_ = VRSettings()->GetBool(kSettingsSection, "virtualDisplay");
VRProperties()->SetBoolProperty(c, Prop_HasVirtualDisplayComponent_Bool, virtualDisplay_);
// A proximity sensor that reads "worn" while Cardboard mode is on: otherwise SteamVR sees a headset
// lying still (a phone on a table between sessions) and puts the display in standby, after which
// the compositor submits no layers at all.
VRProperties()->SetBoolProperty(c, Prop_ContainsProximitySensor_Bool, true);
VRDriverInput()->CreateBooleanComponent(c, "/proximity", &proximity_);
VRDriverInput()->UpdateBooleanComponent(proximity_, true, 0);
@@ -528,7 +488,7 @@ public:
p.qWorldFromDriverRotation.w = 1;
p.qDriverFromHeadRotation.w = 1;
p.qRotation.w = 1;
p.vecPosition[1] = 1.6; // standing eye height: 3DoF, the head never moves
p.vecPosition[1] = 1.6;
droiddeck_headpose hp;
bool ok = pose_.Read(&hp);
if (ok) {
@@ -543,14 +503,12 @@ public:
return p;
}
// ---- IVRDisplayComponent
void GetWindowBounds(int32_t *x, int32_t *y, uint32_t *w, uint32_t *h) override {
*x = 0; *y = 0; *w = (uint32_t)width_; *h = (uint32_t)height_;
}
bool IsDisplayOnDesktop() override { return !directMode_; }
bool IsDisplayRealDisplay() override { return false; }
void GetRecommendedRenderTargetSize(uint32_t *w, uint32_t *h) override {
// Rendered a little larger than the panel: the lens pass magnifies the middle.
*w = (uint32_t)(width_ / 2 * 1.4f);
*h = (uint32_t)(height_ * 1.4f);
}
@@ -559,7 +517,6 @@ public:
*x = eye == Eye_Left ? 0 : (uint32_t)width_ / 2;
}
void GetProjectionRaw(EVREye, float *left, float *right, float *top, float *bottom) override {
// Exactly what the Cardboard pass samples from each half of a side-by-side frame.
*left = -tanHalf_ * eyeAspect_; *right = tanHalf_ * eyeAspect_;
*top = -tanHalf_; *bottom = tanHalf_;
}
@@ -582,7 +539,6 @@ private:
droiddeck_headpose hp;
bool fresh = pose_.Read(&hp) && hp.seq != lastSeq;
auto now = std::chrono::steady_clock::now();
// A new sample, or a heartbeat so SteamVR never thinks the HMD went away.
PadState pad;
const bool havePad = pad_.Read(&pad);
const bool padChanged = havePad && (pad.buttons != lastPad_.buttons || memcmp(pad.axes, lastPad_.axes, sizeof(pad.axes)));
@@ -657,7 +613,7 @@ private:
Provider g_provider;
} // namespace
}
DD_EXPORT void *HmdDriverFactory(const char *interfaceName, int *returnCode) {
if (!strcmp(interfaceName, IServerTrackedDeviceProvider_Version)) return &g_provider;
File diff suppressed because it is too large. Load diff
+6 -32
View File
@@ -1,4 +1,3 @@
// See presenter.h.
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan_core.h>
typedef struct _XDisplay Display;
@@ -41,7 +40,6 @@ void Log(const char *fmt, ...) {
fprintf(stderr, "[droiddeck] %s\n", buf);
}
// ---------------------------------------------------------------- Xlib, loaded at runtime
struct X11 {
void *lib = nullptr;
@@ -68,7 +66,6 @@ struct X11 {
}
};
// ---------------------------------------------------------------- Vulkan, loaded at runtime
#define VK_GLOBAL(X) X(CreateInstance)
#define VK_INSTANCE(X) \
@@ -124,7 +121,7 @@ public:
std::lock_guard<std::mutex> lock(mutex_);
for (int i = 0; i < 3; i++) {
if (fds[i] < 0) continue;
int fd = dup(fds[i]); // the import owns its fd; the driver keeps its own
int fd = dup(fds[i]);
if (fd >= 0) pending_.push_back({handles[i], fd, format, w, h});
}
EnsureThread();
@@ -163,7 +160,6 @@ private:
}
}
// ------------------------------------------------------------ the presenting thread
void Run() {
const char *mode = getenv("DROIDDECK_VR_PRESENT");
@@ -198,9 +194,6 @@ private:
if (wl_) { wl_display_dispatch_pending(wl_); wl_display_flush(wl_); }
for (auto &p : imports) Import(p);
for (auto h : removals) Forget(h);
// SteamVR hands the textures over at Present with no fence the driver can wait on: give the
// compositor's GPU work a moment to land before copying, as ALVR does (a torn or half-drawn
// frame otherwise).
if (f.texture[0]) std::this_thread::sleep_until(at + guard_);
if (f.texture[0] && Draw(f)) shown++;
auto now = std::chrono::steady_clock::now();
@@ -216,10 +209,6 @@ private:
std::chrono::microseconds guard_{4000};
// ------------------------------------------------------------ Wayland: straight to DroidDeck's compositor
// The compositor the app runs (wayland-0 in the session's runtime dir, beside gamescope's socket)
// takes a fullscreen toplevel at the panel's size: one hop and one scale fewer than the X11 overlay
// through gamescope, whose output is the session's (often smaller) resolution.
struct wl_display *wl_ = nullptr;
struct wl_compositor *wlComp_ = nullptr;
struct xdg_wm_base *wm_ = nullptr;
@@ -272,9 +261,6 @@ private:
xdg_toplevel_set_fullscreen(toplevel_, nullptr);
wl_surface_commit(wlSurf_);
for (int i = 0; i < 20 && !configured_; i++) wl_display_roundtrip(wl_);
// The size: the panel the Cardboard pass draws (two eyes, from the shared pose file), so nothing
// scales the picture down on the way. The compositor's configure carries the session's output
// size, which is often smaller; it is the fallback.
width_ = height_ = 0;
int fd = open("/run/droiddeck/droiddeck-headpose", O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
@@ -291,8 +277,6 @@ private:
bool InitWindow() {
if (const char *g = getenv("DROIDDECK_VR_PRESENT_GUARD_MS")) guard_ = std::chrono::microseconds((long)(atof(g) * 1000));
if (!x_.Load()) { Log("presenter: no libX11"); return false; }
// gamescope's first Xwayland (:0) is where its overlays (mangoapp, Steam's) live; SteamVR's
// processes inherit the games' display (:1), so it is not taken from DISPLAY.
const char *name = getenv("DROIDDECK_VR_DISPLAY");
if (!name || !*name) name = ":0";
dpy_ = x_.OpenDisplay(name);
@@ -302,14 +286,11 @@ private:
height_ = (uint32_t)x_.DisplayHeight(dpy_, scr);
win_ = x_.CreateSimpleWindow(dpy_, x_.DefaultRootWindow(dpy_), 0, 0, width_, height_, 0, 0, 0);
x_.StoreName(dpy_, win_, "DroidDeck Cardboard VR");
// gamescope shows an external overlay above whatever has focus (mangoapp is one).
// gamescope composites one external overlay (mangoapp, the perf HUD, usually holds it) and one Steam
// overlay; the Steam overlay slot is free while nothing is shown over a game.
const char *atom = getenv("DROIDDECK_VR_OVERLAY_ATOM");
if (!atom || !*atom) atom = "STEAM_OVERLAY";
unsigned long cardinal = 6; // XA_CARDINAL
unsigned long one = 1; // format 32 properties are longs in Xlib
x_.ChangeProperty(dpy_, win_, x_.InternAtom(dpy_, atom, 0), cardinal, 32, 0 /* PropModeReplace */,
unsigned long cardinal = 6;
unsigned long one = 1;
x_.ChangeProperty(dpy_, win_, x_.InternAtom(dpy_, atom, 0), cardinal, 32, 0 ,
(const unsigned char *)&one, 1);
x_.MapWindow(dpy_, win_);
x_.Flush(dpy_);
@@ -438,15 +419,10 @@ private:
return -1;
}
// Imports one of SteamVR's shared images with the parameters it was made with (ALVR's recipe):
// optimal tiling, mutable format (which keeps it uncompressed), opaque fd, dedicated memory. UNORM so a
// blit copies the bytes rather than decoding sRGB.
void Import(const PendingImport &p) {
Imported im{p.handle};
im.width = p.width;
im.height = p.height;
// The same format list SteamVR's mutable sRGB images carry: with it Turnip keeps UBWC compression on,
// and the import has to agree on that or it reads compressed data as plain pixels.
const char *fl = getenv("DROIDDECK_VR_IMPORT_FORMAT_LIST");
const bool formatList = !fl || strcmp(fl, "0") != 0;
VkFormat formats[2] = {(VkFormat)p.format, UnormOf(p.format)};
@@ -516,8 +492,6 @@ private:
VkCommandBufferBeginInfo bi = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
vk_.BeginCommandBuffer(cmd_, &bi);
VkImage dst = images_[idx];
// The eye textures come from SteamVR's compositor (another process): take them from the external
// queue family as they are (GENERAL keeps the contents; they are uncompressed).
VkImageMemoryBarrier pre[3] = {
Barrier(dst, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT),
Barrier(eye[0]->image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, 0, VK_ACCESS_TRANSFER_READ_BIT,
@@ -597,11 +571,11 @@ private:
std::vector<Imported> textures_;
};
} // namespace
}
void Presenter::AddTextures(const uint64_t h[3], const int fds[3], uint32_t f, uint32_t w, uint32_t hh) { Impl::Get().Add(h, fds, f, w, hh); }
void Presenter::RemoveTexture(uint64_t h) { Impl::Get().Remove(h); }
void Presenter::Submit(const EyeFrame &f) { Impl::Get().Submit(f); }
void Presenter::Shutdown() { Impl::Get().Shutdown(); }
} // namespace droiddeck
}
+3 -18
View File
@@ -1,34 +1,19 @@
// Puts SteamVR's eye textures on the screen for the Cardboard driver (driver_droiddeck.cpp).
//
// The driver-direct component hands each frame over as two eye textures: shared Vulkan images,
// dmabufs on Linux. The presenter imports them into a Vulkan device of its own and draws them side by
// side into a fullscreen X11 window on gamescope's Xwayland, marked as an external overlay so gamescope
// shows it above whatever app has focus. DroidDeck's compositor, in Cardboard mode with a
// side-by-side source, then puts the lens distortion on it for the viewer.
//
// SteamVR compositor -> eye textures -> [presenter: blit L|R] -> X11 overlay -> gamescope
// -> DroidDeck compositor -> Cardboard lens pass -> panel
//
// Everything is loaded at runtime (libvulkan.so.1, libX11.so.6): the driver links against nothing
// the cross build image lacks.
#pragma once
#include <cstdint>
namespace droiddeck {
struct EyeFrame {
uint64_t texture[2]; // SharedTextureHandle_t per eye
float bounds[2][4]; // uMin, vMin, uMax, vMax per eye
uint64_t texture[2];
float bounds[2][4];
};
class Presenter {
public:
// Called from CreateSwapTextureSet: the three images of one set, as SteamVR made them.
static void AddTextures(const uint64_t handles[3], const int fds[3], uint32_t vkFormat, uint32_t width, uint32_t height);
static void RemoveTexture(uint64_t handle);
// Called from Present: the frame's eye textures; returns at once (a thread of its own presents).
static void Submit(const EyeFrame &frame);
static void Shutdown();
};
} // namespace droiddeck
}
+12 -108
View File
@@ -1,33 +1,4 @@
#define _GNU_SOURCE
/*
* VK_LAYER_DROIDDECK_vr: lets SteamVR's vrcompositor create its Vulkan instance on Turnip/KGSL.
*
* vrcompositor always asks for VK_KHR_display and the direct-mode extensions around it (it opens a
* direct mode window even when a driver-direct-mode driver - tools/vr/src/driver_droiddeck.cpp -
* will receive the frames). Turnip's KGSL backend has no displays and refuses to enumerate any GPU
* on an instance with VK_KHR_display enabled. This layer takes those extensions out of the instance
* it creates below itself and answers the display queries on its own: there are no displays.
*
* Shared semaphores: SteamVR shares a timeline semaphore with every image it shares between its
* processes, exported as an opaque fd. Turnip/KGSL cannot export one. Such a semaphore is created
* unshared here instead, its "fd" is a placeholder (a memfd named droiddeck-detached-sem), and a
* process importing a placeholder keeps a detached semaphore whose GPU waits are dropped and whose
* host waits return at once. Each process still orders its own work; what is lost is only the GPU
* ordering between processes, which SteamVR's own IPC (one frame at a time) mostly covers.
*
* Where it runs: droiddeck-steamvr enables it explicitly in SteamVR's own processes (VK_INSTANCE_LAYERS
* + VK_LAYER_PATH). It is also an implicit layer for the whole session, because processes SteamVR did
* not start share textures with it too: Steam's web helper draws its in-VR overlay through SteamVR,
* needs the exportable semaphores, and without them crashes until Steam quits. As an implicit layer
* it stays out of the way:
* - the display stand-in (taking display extensions off, the fake display) happens only while
* SteamVR runs (droiddeck-steamvr's marker file) or where the layer was enabled by name, never in
* an ordinary session: gamescope and games see the driver's extensions unchanged;
* - the semaphore bridge is active in those same processes, and in Steam's web helper once SteamVR
* is installed (its GPU process outlives SteamVR runs);
* - everything else - every process of a session without SteamVR installed - gets the next layer's
* functions untouched.
*/
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
@@ -51,10 +22,7 @@ static void say(const char *fmt, const char *arg) {
fputc('\n', stderr);
}
/* ------------------------------------------------------------------ crash trace (debug) */
/* DROIDDECK_VR_CRASHTRACE=1: print a backtrace on a fatal signal. vrcompositor's launcher drops
* LD_PRELOAD, but this layer is loaded into it, so this is the way to see where it dies. */
#include <dlfcn.h>
#include <execinfo.h>
#include <signal.h>
@@ -86,7 +54,6 @@ static void crash_trace_install(void) {
static int done;
if (done++) return;
if (!getenv("DROIDDECK_VR_CRASHTRACE")) {
/* Or a marker beside droiddeck-steamvr's, for processes whose environment is not ours (Steam). */
const char *rt = getenv("XDG_RUNTIME_DIR");
char path[512];
snprintf(path, sizeof(path), "%s/droiddeck-steamvr/crashtrace", rt && *rt ? rt : "/run/droiddeck");
@@ -100,33 +67,28 @@ static void crash_trace_install(void) {
sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
int sigs[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};
for (unsigned i = 0; i < sizeof(sigs) / sizeof(*sigs); i++) {
/* Only where nothing handles the signal yet: Wine and FEX (Proton games) take SIGSEGV as part
* of their normal work, and replacing their handler crashes the game. */
struct sigaction old;
if (sigaction(sigs[i], NULL, &old) == 0 && !(old.sa_flags & SA_SIGINFO) && old.sa_handler == SIG_DFL)
sigaction(sigs[i], &sa, NULL);
}
}
/* ------------------------------------------------------------------ dispatch */
struct inst {
VkInstance handle;
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance destroy;
int stripped; /* the app asked for display extensions we took out */
int active; /* see the top of the file */
int stripped;
int active;
};
struct dev {
VkDevice handle;
PFN_vkGetDeviceProcAddr gdpa;
PFN_vkDestroyDevice destroy;
int active;
int display; /* its instance has the pretend display */
int display;
};
/* SteamVR is running (droiddeck-steamvr start/stop keeps this file), or the layer was asked for by
* name. Only then does the layer stand in for a display. */
static int steamvr_running(void) {
const char *layers = getenv("VK_INSTANCE_LAYERS");
if (layers && strstr(layers, "VK_LAYER_DROIDDECK_vr")) return 1;
@@ -137,10 +99,6 @@ static int steamvr_running(void) {
return access(path, F_OK) == 0;
}
/* Whether an instance gets the semaphore bridge. Steam's web helper shares its in-VR overlays with
* SteamVR, and its GPU process lives across SteamVR runs: one created before SteamVR started crashes
* once SteamVR shows the overlay, and after a few of those Steam quits. So it is bridged whenever
* SteamVR is installed, not only while it runs. */
static int bridge_wanted(void) {
if (steamvr_running()) return 1;
if (strcmp(program_invocation_short_name, "steamwebhelper")) return 0;
@@ -155,7 +113,6 @@ static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct inst g_inst[MAX_OBJS];
static struct dev g_dev[MAX_OBJS];
/* The dispatch key: the loader's dispatch table pointer at the start of every dispatchable object. */
static void *key(const void *obj) { return *(void **)obj; }
static struct inst *inst_for(const void *obj) {
@@ -178,7 +135,6 @@ static struct dev *dev_for(const void *obj) {
#define NEXT(dev, fn) ((PFN_vk##fn)dev_for(dev)->gdpa(dev, "vk" #fn))
#define HOOK_AS(str, fn) if (!strcmp(name, str)) return (PFN_vkVoidFunction)fn;
/* Extensions this layer takes off the instance and stands in for. */
static const char *const DISPLAY_EXTS[] = {
"VK_KHR_display", "VK_EXT_direct_mode_display", "VK_EXT_display_surface_counter",
"VK_KHR_get_display_properties2", "VK_EXT_acquire_xlib_display", "VK_EXT_acquire_drm_display",
@@ -189,7 +145,6 @@ static int is_display_ext(const char *name) {
return 0;
}
/* ------------------------------------------------------------------ instance */
static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *alloc,
VkInstance *out) {
@@ -203,7 +158,6 @@ static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const
PFN_vkCreateInstance next_create = (PFN_vkCreateInstance)next_gipa(VK_NULL_HANDLE, "vkCreateInstance");
if (!next_create) return VK_ERROR_INITIALIZATION_FAILED;
/* Outside SteamVR the instance is created exactly as asked: display extensions stay on. */
const int vr = steamvr_running();
VkInstanceCreateInfo mine = *ci;
const char **names = calloc(ci->enabledExtensionCount + 1, sizeof(*names));
@@ -216,7 +170,6 @@ static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const
if (stripped) {
int have = 0;
for (uint32_t i = 0; i < n; i++) have |= !strcmp(names[i], "VK_EXT_headless_surface");
/* The pretend display's surface is a headless one; it needs VK_KHR_surface too. */
const char *more[] = {"VK_EXT_headless_surface", "VK_KHR_surface"};
names = realloc(names, (n + 3) * sizeof(*names));
if (!have) names[n++] = more[0];
@@ -253,7 +206,6 @@ static void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCa
if (d) d(instance, alloc);
}
/* ------------------------------------------------------------------ device */
static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci,
const VkAllocationCallbacks *alloc, VkDevice *out) {
@@ -270,7 +222,6 @@ static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreat
const int active = in && in->active;
const int display = in && in->stripped;
/* VK_EXT_display_control (vblank events on a display) goes too: there is no display. */
VkDeviceCreateInfo mine = *ci;
const char **names = calloc(ci->enabledExtensionCount + 1, sizeof(*names));
uint32_t n = 0;
@@ -307,13 +258,6 @@ static void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallback
if (f) f(device, alloc);
}
/* ------------------------------------------------------------------ the display stand-in
*
* One pretend display with one mode and one plane. vrcompositor keeps a direct mode window on it even
* when a driver-direct driver takes the frames, and waits on that window's presents, so the display
* needs a working swapchain: its surface is a headless one (VK_EXT_headless_surface, Mesa's WSI).
* The vblank side of VK_EXT_display_control is a 60 Hz clock. Size and rate:
* DROIDDECK_VR_DISPLAY_MODE=WIDTHxHEIGHT@HZ (default 1920x1080@60). */
#include <time.h>
@@ -452,8 +396,6 @@ static VkResult VKAPI_CALL GetRandROutputDisplayEXT(VkPhysicalDevice pd, void *d
*d = FAKE_DISPLAY; return VK_SUCCESS;
}
/* VK_EXT_display_control on the device: a 60 Hz clock. A vblank event's fence comes back signalled
* once the next tick has passed (the caller's vblank thread waits right after registering). */
static VkResult VKAPI_CALL DisplayPowerControlEXT(VkDevice d, VkDisplayKHR disp, const VkDisplayPowerInfoEXT *info) { return VK_SUCCESS; }
static VkResult signalled_fence(VkDevice d, const VkAllocationCallbacks *a, VkFence *fence) {
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL, VK_FENCE_CREATE_SIGNALED_BIT};
@@ -477,14 +419,10 @@ static VkResult VKAPI_CALL GetSwapchainCounterEXT(VkDevice d, VkSwapchainKHR sc,
return VK_SUCCESS;
}
/* The pretend display's swapchain, on the headless surface: no swapchain counter (that belongs to
* VK_EXT_display_control, which the device does not have), and a request the headless WSI accepts. */
static VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice d, const VkSwapchainCreateInfoKHR *ci, const VkAllocationCallbacks *a,
VkSwapchainKHR *out) {
PFN_vkCreateSwapchainKHR next = NEXT(d, CreateSwapchainKHR);
VkSwapchainCreateInfoKHR sized = *ci;
/* A headless surface has no size of its own (UINT32_MAX), and SteamVR passes that through: the
* pretend display's mode is the size. */
mode_init();
if (sized.imageExtent.width == UINT32_MAX || sized.imageExtent.height == UINT32_MAX)
sized.imageExtent = (VkExtent2D){g_mode_w, g_mode_h};
@@ -498,13 +436,12 @@ static VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice d, const VkSwapchainCreat
for (const VkBaseInStructure *p = ci->pNext; p && n < (int)sizeof(line) - 16; p = p->pNext) n += snprintf(line + n, sizeof(line) - n, " %d", p->sType);
say("vkCreateSwapchainKHR refused (%s); retrying for the headless surface", line);
VkSwapchainCreateInfoKHR mine = *ci;
mine.pNext = NULL; /* drops VkSwapchainCounterCreateInfoEXT and friends */
mine.pNext = NULL;
mine.presentMode = VK_PRESENT_MODE_FIFO_KHR;
mine.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
if (mine.minImageCount < 2) mine.minImageCount = 2;
r = next(d, &mine, a, out);
if (r != VK_SUCCESS) {
/* Last resort: the plainest swapchain the surface can take. */
mine.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
mine.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
mine.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
@@ -524,16 +461,6 @@ static PFN_vkVoidFunction display_device_hook(const char *name) {
return NULL;
}
/* ------------------------------------------------------------------ bridged shared semaphores
*
* SteamVR shares a timeline semaphore with every image it shares between processes, exported as an
* opaque fd; Turnip/KGSL cannot export one. Here such a semaphore is created unshared, and its "fd" is
* a memfd (named droiddeck-shared-sem) holding a 64-bit counter. Every process that has the semaphore -
* the creator and each importer - keeps its own real timeline semaphore, and a poller thread in each
* process carries values both ways: a value reached locally goes up into the counter, a value the
* counter shows (another process got there) is signalled locally from the host. GPU waits then work
* as written, about a poll period late. A binary semaphore cannot be bridged that way; GPU waits on an
* imported binary one are dropped (each process still orders its own work). */
#include <sched.h>
#include <stdatomic.h>
@@ -547,14 +474,14 @@ struct bridged {
VkSemaphore sem;
VkDevice dev;
_Atomic uint64_t *counter;
int fd; /* the memfd, kept by the creator so every export can dup it; -1 for an importer */
int timeline; /* 0: binary, bridged only by dropping its waits */
unsigned long ino; /* the memfd's inode, which names the semaphore across processes in traces */
uint64_t submitted; /* the highest value this process has queued a signal of */
int fd;
int timeline;
unsigned long ino;
uint64_t submitted;
};
static pthread_mutex_t g_br_lock = PTHREAD_MUTEX_INITIALIZER;
static struct bridged g_br[MAX_SEMS];
static VkSemaphore g_timeline_sems[MAX_TYPED]; /* every timeline semaphore this process made */
static VkSemaphore g_timeline_sems[MAX_TYPED];
static pthread_t g_poller;
static int g_poller_started;
@@ -573,7 +500,6 @@ static void timeline_note(VkSemaphore s, int add) {
pthread_mutex_unlock(&g_br_lock);
}
/* Under g_br_lock. */
static struct bridged *bridged_find(VkSemaphore s) {
for (int i = 0; i < MAX_SEMS; i++) if (g_br[i].sem == s) return &g_br[i];
return NULL;
@@ -585,7 +511,6 @@ static void bridged_drop(struct bridged *b) {
b->fd = -1;
}
/* A `semtrace` file beside droiddeck-steamvr's marker: log every bridged semaphore every 2 s. */
static int sem_trace_on(void) {
static int checked, on;
if (!checked++) {
@@ -673,7 +598,6 @@ static VkResult VKAPI_CALL CreateSemaphore(VkDevice d, const VkSemaphoreCreateIn
return r;
}
if (!export_info) return r;
/* Rebuild the chain without the export request. */
VkSemaphoreTypeCreateInfo type = {0};
VkSemaphoreCreateInfo mine = *ci;
mine.pNext = NULL;
@@ -688,7 +612,7 @@ static VkResult VKAPI_CALL CreateSemaphore(VkDevice d, const VkSemaphoreCreateIn
int fd = memfd_create(SHARED_NAME, MFD_CLOEXEC);
_Atomic uint64_t *counter = NULL;
if (fd >= 0 && ftruncate(fd, 4096) == 0) counter = map_counter(fd);
if (!counter) { if (fd >= 0) close(fd); return r; } /* unshared, unbridged */
if (!counter) { if (fd >= 0) close(fd); return r; }
atomic_store(counter, timeline ? type_info->initialValue : 0);
pthread_mutex_lock(&g_br_lock);
struct bridged *slot = bridged_find(VK_NULL_HANDLE);
@@ -732,7 +656,7 @@ static VkResult VKAPI_CALL ImportSemaphoreFdKHR(VkDevice d, const VkImportSemaph
if (info->fd < 0 || !is_shared_counter(info->fd)) return NEXT(d, ImportSemaphoreFdKHR)(d, info);
_Atomic uint64_t *counter = map_counter(info->fd);
const unsigned long ino = fd_ino(info->fd);
close(info->fd); /* a successful import owns the fd */
close(info->fd);
const int timeline = timeline_known(info->semaphore);
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(info->semaphore);
@@ -748,7 +672,6 @@ static VkResult VKAPI_CALL ImportSemaphoreFdKHR(VkDevice d, const VkImportSemaph
return VK_SUCCESS;
}
/* An imported binary one: nothing here will ever signal it. */
static int drop_wait(VkSemaphore s) {
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(s);
@@ -763,17 +686,8 @@ static uint64_t now_us(void) {
return (uint64_t)ts.tv_sec * 1000000u + (uint64_t)ts.tv_nsec / 1000u;
}
/* How long a submit may wait for another process to reach a shared value before the wait is dropped. */
#define SUBMIT_GRACE_US 3000
/* Whether a submit should drop its GPU wait on s for value.
*
* Turnip on KGSL does not defer a submit that waits on a timeline value nobody has signalled yet ("wait
* before signal"): vkQueueSubmit blocks the calling thread until the value is signalled. SteamVR's
* client waits on a value of the compositor's that the compositor signals only after the client has
* submitted and told it so, which on Turnip deadlocks the client before its first frame (helloxr's
* acquire, DXVK's submit thread in Proton games). For an imported timeline semaphore whose value is
* neither reached nor queued here, the counter gets a short grace period, then the wait goes. */
static int submit_drop_wait(VkSemaphore s, uint64_t value) {
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(s);
@@ -787,7 +701,6 @@ static int submit_drop_wait(VkSemaphore s, uint64_t value) {
if (!imported || !value || value <= queued) return 0;
struct dev *d = dev_for(dev);
if (!d) return 0;
/* A Vulkan 1.0 device (SteamVR's client interop) has only the KHR names. */
PFN_vkGetSemaphoreCounterValue get = (PFN_vkGetSemaphoreCounterValue)d->gdpa(dev, "vkGetSemaphoreCounterValue");
if (!get) get = (PFN_vkGetSemaphoreCounterValue)d->gdpa(dev, "vkGetSemaphoreCounterValueKHR");
PFN_vkSignalSemaphore sig = (PFN_vkSignalSemaphore)d->gdpa(dev, "vkSignalSemaphore");
@@ -812,7 +725,6 @@ static int submit_drop_wait(VkSemaphore s, uint64_t value) {
return 1;
}
/* Notes the values this process queues signals of, so its own later waits on them are kept. */
static void note_signal(VkSemaphore s, uint64_t value) {
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(s);
@@ -836,7 +748,6 @@ static void note_submit2_signals(uint32_t count, const VkSubmitInfo2 *submits) {
note_signal(submits[i].pSignalSemaphoreInfos[j].semaphore, submits[i].pSignalSemaphoreInfos[j].value);
}
/* Drops waits on detached semaphores from a list; returns the new count. */
static uint32_t keep_waits(const VkSemaphore *in, const VkPipelineStageFlags *stages, const uint64_t *values, uint32_t n,
VkSemaphore *out, VkPipelineStageFlags *out_stages, uint64_t *out_values) {
uint32_t k = 0;
@@ -850,7 +761,6 @@ static uint32_t keep_waits(const VkSemaphore *in, const VkPipelineStageFlags *st
return k;
}
/* semtrace: the first wait and the first signal of each shared semaphore, and its first few values. */
static void trace_sem(const char *what, VkSemaphore sem, uint64_t value) {
if (!sem_trace_on() || value > 3) return;
pthread_mutex_lock(&g_br_lock);
@@ -876,8 +786,6 @@ static VkResult VKAPI_CALL QueueSubmit(VkQueue q, uint32_t count, const VkSubmit
for (uint32_t j = 0; j < submits[i].signalSemaphoreCount; j++)
trace_sem("signals", submits[i].pSignalSemaphores[j], t && j < t->signalSemaphoreValueCount ? t->pSignalSemaphoreValues[j] : 0);
}
/* Waits are judged before this submit's own signals count as queued: an acquire may wait on one
* value and signal the next on the same semaphore. */
int any = 0;
for (uint32_t i = 0; i < count && !any; i++) {
const VkTimelineSemaphoreSubmitInfo *t = NULL;
@@ -911,7 +819,6 @@ static VkResult VKAPI_CALL QueueSubmit(VkQueue q, uint32_t count, const VkSubmit
copy[i].pWaitSemaphores = sems;
copy[i].pWaitDstStageMask = stages;
if (t) {
/* Only this struct is replaced; the rest of the chain is kept behind it. */
tl[i] = *t;
tl[i].waitSemaphoreValueCount = t->waitSemaphoreValueCount ? k : 0;
tl[i].pWaitSemaphoreValues = vals;
@@ -920,7 +827,7 @@ static VkResult VKAPI_CALL QueueSubmit(VkQueue q, uint32_t count, const VkSubmit
for (const VkBaseInStructure *p = submits[i].pNext; p; prev = p, p = p->pNext) if (p == (const void *)t) { rest = p->pNext; break; }
(void)prev;
tl[i].pNext = rest;
copy[i].pNext = &tl[i]; /* other structs before it are dropped: SteamVR chains only this one */
copy[i].pNext = &tl[i];
}
}
VkResult r = next(q, count, copy, fence);
@@ -989,7 +896,6 @@ static VkResult VKAPI_CALL GetSemaphoreCounterValue(VkDevice d, VkSemaphore s, u
return next(d, s, value);
}
/* semtrace also logs how shared (external memory) images are created, to compare both sides. */
static VkResult VKAPI_CALL CreateImage(VkDevice d, const VkImageCreateInfo *ci, const VkAllocationCallbacks *a, VkImage *out) {
VkResult r = NEXT(d, CreateImage)(d, ci, a, out);
if (!sem_trace_on()) return r;
@@ -1026,7 +932,6 @@ static PFN_vkVoidFunction semaphore_hook(const char *name) {
return NULL;
}
/* ------------------------------------------------------------------ proc addr */
#define HOOK(fn) if (!strcmp(name, "vk" #fn)) return (PFN_vkVoidFunction)fn;
@@ -1085,7 +990,6 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVr_GetDeviceProcAddr(Vk
if (f) return f;
}
if (d) {
/* Only where the driver has the function: the hooks call through to it. */
PFN_vkVoidFunction mine = semaphore_hook(name);
if (mine && d->gdpa(device, name)) return mine;
}
-3
View File
@@ -1,6 +1,3 @@
/* Link-time stand-in for libwayland-client.so.0 (tools/vr/build.sh): the symbols the presenter uses, so
* the driver links with -z defs against a library the build machine does not have. Never loaded: the
* runtime's real libwayland-client.so.0 satisfies the dependency on the device. */
#include <stdint.h>
#include <stddef.h>
#include "wayland-util.h"