Compare commits

..
Author SHA1 Message Date
maxjivi05 83a05b2960 build(gamescope): stage the gamescope that presses after the hover 2026-11-29 17:41:07 -05:00
maxjivi05 53b5432ebb fix(gamescope): name the idle tap step so it does not clash with the X11 None macro 2026-11-29 17:31:11 -05:00
maxjivi05 9d6d7b677d fix(gamescope): a touch click presses after the pointer has moved to the finger 2026-11-29 17:27:23 -05:00
d7fcea74b4 fix(mali): Auto respects Venus turned off and picks the bridge on Mali-G2-Ultra (#3198)
* fix(mali): Auto respects Venus turned off and picks the bridge on Mali-G2-Ultra

With GPU drivers on Auto, Mali (Venus) was turned back on after the user turned it off. Auto now respects that choice, and picks the bridge on Mali-G2-Ultra, where Steam's web helper dies on its first window through Venus (#2879). When Auto itself turns Venus off it clears the stored key, so its own decision does not read as the user's later.

* fix(mali): clear Auto-owned Venus preference when fallback ends

---------

Co-authored-by: Unixcision <14082251+Unixcision@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 17:17:51 -05:00
sergeymetallicandsergeymetallic 44b429ca20 fix(game-env): resolve store launcher executable from sidecar (#3288)
* fix(game-env): resolve store launcher executable from sidecar

Store titles launched through .droiddeck-launch.bat passed the wrapper
path directly into engine_fixes and other exe-based checks, so stem
checks saw .droiddeck-launch and game_files scanned from the install
root rather than the executable's folder. For Epic's Batman: Arkham
City, Binaries/Win32/BatmanAC.exe sat one level deeper than game_files
scans, so arkham_city_x87 never set FEX_X87REDUCEDPRECISION=0.

Resolve .droiddeck-launch.bat to the validated exe entry from
.droiddeck-store.json when inspecting the game, while keeping the
launcher path in the Proton command.

* fix(game-env): reject parent segments before normpath in store_game_exe

os.path.normpath lexically collapses symlink/../file before the
filesystem is consulted, which could validate a different file than a
symlinked subdirectory path denotes. Reject any ".." path component
after separator normalization before calling os.path.normpath.

---------

Co-authored-by: sergeymetallic <6938136+sergeymetallic@users.noreply.github.com>
2026-11-29 16:18:43 -05:00
Dhiman SealandKurt Himebauch c91b100bc1 fix(game-env): run Inno Setup installers with the FEX Stability settings (#3069)
* fix(game-env): run Inno Setup installers with the FEX Stability settings

An Inno Setup installer added as a game stops with Wine's "Path not
fpund." dialog under the default FEX preset. The 32-bit setup stub
corrupts its own paths before it opens its archive (#1277, #3067). #1174
avoids the stub only for GOG installs, by extracting them natively.

droiddeck-game-env now finds the stub by the setup loader's offset-table
ID in its resources, or the "Inno" marker older loaders keep at 0x30, and
launches it with the Stability preset's FEX settings. A FEX preset chosen
for the game itself still wins.

Fixes #3067

* fix(game-env): name only the preset seen to corrupt Inno Setup paths

The launch note and the docs said the faster presets corrupt the setup
stub. Only the default Performance + TSO preset was seen doing it.

* fix(game-env): give Inno Setup installers started with run the Stability settings

The run verb skips engine_fixes and gets only the sync settings, so an installer started that way kept the inherited Performance + TSO preset. Apply the Stability values on that path too; explicit game settings still win in apply_config.

* fix(game-env): keep the game's own FEX settings for installers started with run

The run path filtered the game entry down to sync keys, so a FEX preset
chosen for the game was replaced by the installer's Stability settings,
and a null could not unset a preset key. Copy the game's Stability FEX
keys into the synced config before applying it, so the game's own
settings still win on every launch path.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 16:18:35 -05:00
LarzVader 90df30f4d7 fix(venus): OpenGL quads no longer crash Mali's shader compiler through Zink (#3283)
* fix(venus): OpenGL quads no longer crash Mali's shader compiler through Zink

The Mali-G610's driver crashes compiling Zink's geometry shaders
(SIGSEGV at 0x40 in cmpbe_v2_compile_multiple_shaders), and the render
server and the application die with it. A plain geometry shader that
only passes triangles on does not crash it, but draws nothing. Zink
draws GL_QUADS through a geometry shader when the device has the
feature, so OpenGL programs died on their first quad.

The Mali layer now reports no geometryShader to Zink on ARM GPUs.
Mesa then splits quads into triangles itself. DXVK keeps the feature,
which it needs for D3D10 and 11. DROIDDECK_MALI_COMPAT_NO_GS=0 keeps
it for Zink, =1 hides it from every application.

* test(venus): clear DROIDDECK_MALI_COMPAT_NO_GS before the layer tests

The geometry shader test checks the default first. With the variable
exported in the shell, it failed before it reached its own settings.

* test(venus): check that other ARM applications keep the geometry shader
2026-11-29 16:18:27 -05:00
devu92 2b6ded9fd4 Fix persistent black video after delayed GPU fences (#3400)
fix(vulkan): keep presenting after delayed GPU fence completion
2026-11-29 16:18:19 -05:00
btns29andbtns29 38c2c00c86 Keep safe webhelper layout on Mali bridge (#3420)
* Keep safe webhelper layout on Mali bridge

* Name the zygote regression in the layout test

---------

Co-authored-by: btns29 <btns29@users.noreply.github.com>
2026-11-29 15:53:48 -05:00
Kurt Himebauch 678057d727 Prompt for shared folders named Android/data, and reload after any regrant (#3435)
Prompt for shared folders named Android/data, and reload the folder after any regrant
2026-11-29 15:06:47 -05:00
Kurt Himebauch ae94009382 Ask for all-files access when a shared drive is opened, not on first launch (#3429) 2026-11-29 15:02:25 -05:00
Kurt Himebauch fd93a35b72 Start Steam by itself when first-run setup finishes (#3430) 2026-11-29 15:02:11 -05:00
MaxsTechReview 12fa3ac343 fix(input): a trigger key sent before its axis no longer counts as two presses (#3431)
A trigger key that fires before its axis no longer reads as two presses
2026-11-29 14:20:14 -05:00
MaxsTechReview 422b339af8 fix(display): release zero-copy display buffers at latch (#3424)
* Release zero-copy display buffers at latch; gamescope waits for scanout before reusing an image

* Test that zero-copy releases follow the kernel's fence attach, not the buffer kind

* Pin the gamescope build that waits for scanout before reusing an image

* Probe the fallback output image for scanout so the composite waits on it too

* Pin the gamescope build that probes the fallback output image
2026-11-29 13:54:16 -05:00
FryMcNugget 1d155b2fe0 Quest: SteamVR runs cleanly at close to 72 Hz (right-eye glitch, black voids, frame rate) (#3360) 2026-11-29 12:56:29 -05:00
FryMcNugget 131a351f3f fix(runtime): Unity 5 games no longer crash on their first HTTPS request (#3394) 2026-11-29 12:55:45 -05:00
FX1922 a4c2fa8aec fix(compositor): preserve layer state when zero-copy callbacks fail (#3398)
## Problem

Zero-copy layer transitions could leave the compositor in an
inconsistent state when allocating an `ASurfaceTransaction` completion
callback failed.

Some failure paths released the current or previous `ASurfaceControl`
even though the transaction had not been applied. This could invalidate
layer state or release resources before the transition completed.

## Fix

- Cancel and delete transactions when completion callback allocation
fails.
- Preserve the current layer and buffer state instead of releasing
resources prematurely.
- Roll back surface swaps when presentation cannot proceed.
- Return an error from failed presentation paths and leave the layer
available for recovery.
- Apply the same failure handling to presentation, layer hiding and
surface retirement.

## Tests

- `git diff --check`: passed.
- Native build: not run locally.
- Device testing: 
> Tested on one device and helped with his problem, test build is up for
further testing.
2026-11-29 20:20:42 +03:00
LunaDL fe4f619973 chore: trigger CI rerun 2026-11-29 12:51:13 -04:00
LunaDL 9b7ce457a5 Keep current buffer attached when hide callback allocation fails 2026-11-29 01:51:24 -04:00
LunaDL d2031ba384 Fix deferred layer hide when callback allocation fails 2026-11-29 01:43:57 -04:00
LunaDL c833514757 Restore HDR caches when rolling back layer swap 2026-11-29 01:17:14 -04:00
LunaDL 97a998a3b9 Defer pool cleanup only for layers still in use 2026-11-29 01:04:11 -04:00
LunaDL 31ee95250c Keep layer recovery pending when surface creation fails 2026-11-29 01:03:58 -04:00
LunaDL 689ecc40ad Guard pool drain against pending layer callbacks 2026-11-29 01:03:36 -04:00
LunaDL 3bef9a4200 Fix deferred zero-copy layer retirement and rollback 2026-11-29 01:03:25 -04:00
LunaDL cd1e9dde15 Fix zero-copy layer transition callback failures 2026-11-29 00:47:47 -04:00
57 changed files with 2122 additions and 460 deletions

No files matched your search

+5 -2
View File
@@ -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) {
@@ -133,10 +133,10 @@ static void handle_released(uint64_t id, int fd) {
if (fd >= 0) {
struct droiddeck_dma_buf_sync_file imp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = fd};
int dmabuf_fd = droiddeck_dmabuf_fd(ab->b);
if (!ab->display && dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
close(fd);
} else {
if (!ab->display && !g_import_failed_logged) {
if (!g_import_failed_logged) {
g_import_failed_logged = 1;
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_IMPORT_SYNC_FILE failed (%s): releases wait for the display's fence here instead",
strerror(errno));
+108 -33
View File
@@ -148,6 +148,7 @@ struct slot {
uint32_t fmt;
int release_fd;
int busy;
uint64_t generation;
};
struct layer {
@@ -175,6 +176,7 @@ struct layer {
int votes_rate;
float fps_applied;
int recreate_pending;
int pending_callbacks;
int32_t ds_applied;
@@ -222,6 +224,7 @@ struct complete_ctx {
ASurfaceControl *sc;
int layer;
int prev_slot;
uint64_t prev_generation;
void *prev_token;
int retire;
};
@@ -288,12 +291,16 @@ static void on_complete(void *context, ASurfaceTransactionStats *stats) {
pthread_mutex_lock(&g_lock);
if (ctx->layer >= 0 && ctx->layer < SC_LAYER_COUNT && ctx->prev_slot >= 0 && ctx->prev_slot < POOL_MAX) {
struct slot *s = &g_layers[ctx->layer].slots[ctx->prev_slot];
int fd = (stats && ctx->sc) ? api.prevReleaseFence(stats, ctx->sc) : -1;
if (s->release_fd >= 0) close(s->release_fd);
s->release_fd = fd;
s->busy = 0;
if (s->generation == ctx->prev_generation) {
int fd = (stats && ctx->sc) ? api.prevReleaseFence(stats, ctx->sc) : -1;
if (s->release_fd >= 0) close(s->release_fd);
s->release_fd = fd;
s->busy = 0;
}
}
if (g_pending_cb > 0) g_pending_cb--;
if (ctx->layer >= 0 && ctx->layer < SC_LAYER_COUNT && g_layers[ctx->layer].pending_callbacks > 0)
g_layers[ctx->layer].pending_callbacks--;
pthread_mutex_unlock(&g_lock);
if (ctx->prev_token) {
int fd = (stats && ctx->sc) ? api.prevReleaseFence(stats, ctx->sc) : -1;
@@ -308,9 +315,15 @@ static int add_complete_on(ASurfaceTransaction *tx, struct layer *l, ASurfaceCon
struct complete_ctx *ctx = calloc(1, sizeof(*ctx));
if (!ctx) return -1;
ctx->sc = sc; ctx->layer = (int)(l - g_layers); ctx->prev_slot = prev_slot;
if (prev_slot >= 0 && prev_slot < POOL_MAX) {
pthread_mutex_lock(&g_lock);
ctx->prev_generation = l->slots[prev_slot].generation;
pthread_mutex_unlock(&g_lock);
}
ctx->prev_token = prev_token; ctx->retire = retire;
pthread_mutex_lock(&g_lock);
g_pending_cb++;
l->pending_callbacks++;
pthread_mutex_unlock(&g_lock);
api.setOnComplete(tx, ctx, on_complete);
return 0;
@@ -397,12 +410,16 @@ static void retire_sc(struct layer *l) {
ASurfaceTransaction *tx = api.txCreate();
if (tx) {
retire_ops(tx, l->sc);
if (add_complete(tx, l, l->cur_slot, l->cur_token, 1) != 0) api.release(l->sc);
if (add_complete(tx, l, l->cur_slot, l->cur_token, 1) != 0) {
api.txDelete(tx);
droiddeck_log("layer", "%s: retirement deferred because its release callback could not be allocated", l->name);
return;
}
api.txApply(tx);
api.txDelete(tx);
} else {
if (l->cur_token) ahb_swapchain_layer_released(l->cur_token, -1);
api.release(l->sc);
droiddeck_log("layer", "%s: retirement deferred because a transaction could not be allocated", l->name);
return;
}
droiddeck_log("layer", "%s: SurfaceControl retired (window %p)", l->name, (void *)l->win);
l->sc = NULL; l->win = NULL;
@@ -421,20 +438,28 @@ static void drain_and_free_pools(void) {
if (!pending || now_ns() > deadline) break;
usleep(2000);
}
pthread_mutex_lock(&g_lock);
for (int i = 0; i < SC_LAYER_COUNT; i++) {
struct layer *l = &g_layers[i];
pthread_mutex_lock(&g_lock);
const int pending = l->pending_callbacks;
if (pending || l->sc) {
pthread_mutex_unlock(&g_lock);
droiddeck_log("layer", "pool drain deferred for %s (%s)", l->name,
pending ? "SurfaceControl callbacks are pending" : "SurfaceControl retirement is deferred");
continue;
}
for (int j = 0; j < POOL_MAX; j++) {
struct slot *s = &g_layers[i].slots[j];
struct slot *s = &l->slots[j];
if (s->release_fd >= 0) { struct pollfd p = {.fd = s->release_fd, .events = POLLIN}; poll(&p, 1, 100); close(s->release_fd); }
if (s->img) vkp_image_destroy(s->img);
if (s->ahb) AHardwareBuffer_release(s->ahb);
memset(s, 0, sizeof(*s));
s->release_fd = -1;
}
g_layers[i].first_logged = 0;
g_layers[i].logged_w = g_layers[i].logged_h = 0;
l->first_logged = 0;
l->logged_w = l->logged_h = 0;
pthread_mutex_unlock(&g_lock);
}
pthread_mutex_unlock(&g_lock);
}
static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) {
@@ -612,7 +637,10 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait
if (pending < 0) pending = i;
}
if (idx < 0) idx = pending;
if (idx >= 0) { fd = l->slots[idx].release_fd; l->slots[idx].release_fd = -1; }
if (idx >= 0) {
fd = l->slots[idx].release_fd; l->slots[idx].release_fd = -1;
l->slots[idx].generation++;
}
pthread_mutex_unlock(&g_lock);
if (idx < 0) return -1;
if (fd >= 0 && fence_signalled(fd)) { close(fd); fd = -1; }
@@ -620,7 +648,8 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait
if (s->ahb && (s->w != w || s->h != h || s->fmt != fmt)) {
if (fd >= 0) { close(fd); fd = -1; }
vkp_image_destroy(s->img); AHardwareBuffer_release(s->ahb);
memset(s, 0, sizeof(*s)); s->release_fd = -1;
const uint64_t generation = s->generation;
memset(s, 0, sizeof(*s)); s->release_fd = -1; s->generation = generation;
}
if (fd >= 0 && !vkp_can_wait_sync_fd()) {
if (fence_wait(fd, 100) == 0) { slot_keep_fence(s, fd); return -1; }
@@ -659,7 +688,13 @@ static int ensure_sc(struct layer *l) {
if (load_api() != 0) return -1;
ANativeWindow *win = vkp_window();
if (!win) return -1;
if (l->sc && l->win != win) retire_sc(l);
if (l->sc && l->win != win) {
retire_sc(l);
if (l->sc) {
droiddeck_log("layer", "%s: keeping the old SurfaceControl until retirement completes", l->name);
return -1;
}
}
if (!l->sc) {
l->sc = api.createFromWindow(win, l->name);
if (!l->sc) { droiddeck_log("error", "layer: ASurfaceControl_createFromWindow(%s) failed", l->name); return -1; }
@@ -818,6 +853,7 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) {
if (!win || win != l->win) return NULL;
ASurfaceControl *fresh = api.createFromWindow(win, l->name);
if (!fresh) {
l->recreate_pending = 1;
droiddeck_log("error", "layer: %s: composition recovery could not create a new SurfaceControl", l->name);
return NULL;
}
@@ -832,24 +868,45 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) {
return old;
}
static void rollback_swap_sc(struct layer *l, ASurfaceControl *old, int was_shown,
int32_t ds_applied, uint32_t md_applied, float hr_applied) {
if (!old) return;
ASurfaceControl *fresh = l->sc;
l->sc = old;
l->shown = was_shown;
l->recreate_pending = 1;
l->geo_valid = 0;
l->fps_applied = -1.0f;
l->ds_applied = ds_applied; l->md_applied = md_applied; l->hr_applied = hr_applied;
if (fresh) api.release(fresh);
}
static int present_slot(struct layer *l, int idx, const int r[8], const struct droiddeck_color *color,
int translucent) {
struct slot *s = &l->slots[idx];
ASurfaceTransaction *tx = api.txCreate();
if (!tx) return -1;
const int was_shown = l->shown;
const int32_t ds_applied = l->ds_applied;
const uint32_t md_applied = l->md_applied;
const float hr_applied = l->hr_applied;
ASurfaceControl *old = swap_sc_begin(l);
if (old) api.setZOrder(tx, l->sc, l->z);
api.setBuffer(tx, l->sc, s->ahb, -1);
if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true);
api.setBufferTransparency(tx, l->sc,
translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE);
if (!l->shown) api.setVisibility(tx, l->sc, ASC_VISIBILITY_SHOW);
if (old) retire_ops(tx, old);
if (add_complete_on(tx, l, old ? old : l->sc, l->cur_slot, l->cur_token, old ? 1 : 0) != 0) {
api.txDelete(tx);
rollback_swap_sc(l, old, was_shown, ds_applied, md_applied, hr_applied);
droiddeck_log("layer", "%s: frame transition skipped because its release callback could not be allocated", l->name);
return -1;
}
apply_geometry(tx, l, r);
apply_frame_rate(tx, l);
apply_colour(tx, l, color);
if (!l->shown) api.setVisibility(tx, l->sc, ASC_VISIBILITY_SHOW);
if (old) retire_ops(tx, old);
if (add_complete_on(tx, l, old ? old : l->sc, l->cur_slot, l->cur_token, old ? 1 : 0) != 0 && old)
api.release(old);
pthread_mutex_lock(&g_lock);
s->busy = 1;
pthread_mutex_unlock(&g_lock);
@@ -904,23 +961,27 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi
}
ASurfaceTransaction *tx = api.txCreate();
if (!tx) goto unavailable;
const int was_shown = l->shown;
const int32_t ds_applied = l->ds_applied;
const uint32_t md_applied = l->md_applied;
const float hr_applied = l->hr_applied;
ASurfaceControl *old = swap_sc_begin(l);
if (old) api.setZOrder(tx, l->sc, l->z);
api.setBuffer(tx, l->sc, ahb, acquire_fd);
if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true);
api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE);
apply_geometry(tx, l, r);
apply_frame_rate(tx, l);
apply_colour(tx, l, color);
if (!l->shown) api.setVisibility(tx, l->sc, ASC_VISIBILITY_SHOW);
if (old) retire_ops(tx, old);
if (add_complete_on(tx, l, old ? old : l->sc, l->cur_slot,
l->cur_token == token ? NULL : l->cur_token, old ? 1 : 0) != 0) {
api.txDelete(tx);
if (old) api.release(old);
l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f;
rollback_swap_sc(l, old, was_shown, ds_applied, md_applied, hr_applied);
droiddeck_log("layer", "zero-copy: frame transition skipped because its release callback could not be allocated");
return -1;
}
apply_geometry(tx, l, r);
apply_frame_rate(tx, l);
apply_colour(tx, l, color);
apply_present_time(tx, 1);
api.txApply(tx);
api.txDelete(tx);
@@ -1167,15 +1228,26 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
return 0;
}
static void hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return;
static int hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return 0;
ASurfaceTransaction *tx = api.txCreate();
if (!tx) return;
replace_with_blank(tx, l);
if (!tx) return -1;
api.setVisibility(tx, l->sc, ASC_VISIBILITY_HIDE);
add_complete(tx, l, l->cur_slot, l->cur_token, 0);
if (add_complete(tx, l, l->cur_slot, l->cur_token, 0) != 0) {
/*
* Keep the current buffer attached when its release callback cannot
* be allocated. The hide can still apply without releasing the slot.
*/
api.txApply(tx);
api.txDelete(tx);
l->shown = 0;
droiddeck_log("layer", "%s: hidden; buffer release deferred because its callback could not be allocated", l->name);
return 0;
}
replace_with_blank(tx, l);
api.txApply(tx); api.txDelete(tx);
l->shown = 0; l->cur_slot = -1; l->cur_token = NULL;
return 0;
}
void sc_layer_hide(void) {
@@ -1183,17 +1255,20 @@ void sc_layer_hide(void) {
int said = g_layers[SC_LAYER_GAME].shown || g_layers[SC_LAYER_OVERLAY].sc;
if (g_layers[SC_LAYER_OVERLAY].sc) sc_layer_hide_overlay();
if (g_layers[SC_LAYER_GAME].shown) hide_layer(&g_layers[SC_LAYER_GAME]);
if (said) droiddeck_log("layer", "layers hidden (scene is not a single fullscreen window)");
if (said && !g_layers[SC_LAYER_GAME].shown && !g_layers[SC_LAYER_OVERLAY].shown)
droiddeck_log("layer", "layers hidden (scene is not a single fullscreen window)");
}
void sc_layer_hide_overlay(void) {
layers_init();
struct layer *l = &g_layers[SC_LAYER_OVERLAY];
if (!l->sc) return;
if (l->shown) hide_layer(l);
if (l->shown && hide_layer(l) != 0) return;
retire_sc(l);
droiddeck_log("layer", "%s: gone (nothing is above the game any more)", l->name);
if (g_layers[SC_LAYER_GAME].sc) g_layers[SC_LAYER_GAME].recreate_pending = 1;
if (!l->sc) {
droiddeck_log("layer", "%s: gone (nothing is above the game any more)", l->name);
if (g_layers[SC_LAYER_GAME].sc) g_layers[SC_LAYER_GAME].recreate_pending = 1;
}
}
void sc_layer_window_gone(void) {
@@ -232,6 +232,16 @@ static VkResult timed_wait(VkFence fence, uint64_t timeout) {
return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
int64_t t0 = perf_now();
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
if (r == VK_TIMEOUT) {
droiddeck_log("gpu", "GPU fence delayed: retaining frame resources until completion");
/* A scheduling delay does not invalidate the device. Keep this submission's
* resources and call stack alive, as the main render path already does. */
do {
r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, UINT64_MAX);
} while (r == VK_TIMEOUT);
if (r == VK_SUCCESS)
droiddeck_log("gpu", "GPU fence completed: continuing presentation");
}
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
quarantine_pending_work(r, "fence wait");
@@ -430,21 +430,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
*/
private fun useMaliFallback(missing: String?): String {
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
val venusByUser = venusExplicit()
val venus = MaliAutoRoute.venusStandsIn(
com.droiddeck.launcher.session.VenusComponent.available(activity), oldVulkan == null,
SessionPrefs.venus(activity), venusByUser, gpu.name,
)
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
val ownership = MaliAutoRoute.fallbackOwnership(
venus,
SessionPrefs.vkBridge(activity), bridgeExplicit(),
SessionPrefs.venus(activity), venusExplicit(),
SessionPrefs.venus(activity), venusByUser,
)
if (venus && !SessionPrefs.venus(activity)) {
SessionPrefs.setVenus(activity, true)
if (SessionPrefs.vkBridge(activity) && !bridgeExplicit())
SessionPrefs.setVkBridge(activity, false)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
SessionPrefs.setVkBridge(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (!venus) {
val venusOff = SessionPrefs.venus(activity) && !venusByUser
val bridgeOn = !SessionPrefs.vkBridge(activity)
if (venusOff) SessionPrefs.clearVenus(activity)
if (bridgeOn) SessionPrefs.setVkBridge(activity, true)
if (venusOff || bridgeOn || ownership != MaliAutoRoute.NONE) SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (ownership != MaliAutoRoute.NONE) {
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
}
@@ -467,7 +474,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
/** A pair is installed for this Mali: the route Auto switched on in its place goes off again. */
private fun endMaliFallback() {
when (SessionPrefs.maliFallbackByAuto(activity)) {
"venus" -> SessionPrefs.setVenus(activity, false)
"venus" -> SessionPrefs.clearVenus(activity)
"bridge" -> SessionPrefs.setVkBridge(activity, false)
else -> return
}
@@ -1993,11 +1993,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
val askAllFiles = Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.files.AllFilesAccess.missing() &&
!SessionPrefs.allFilesAsked(this)
if (savedInstanceState == null) {
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
saved?.let { state ->
restoreCompatLaunch(state)
pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH)
@@ -2005,13 +2001,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
val wanted = ArrayList<String>()
if (Build.VERSION.SDK_INT >= 30) {
// From targetSdk 30, shared storage outside the app's own folders is all-files access or nothing.
if (askAllFiles) {
SessionPrefs.setAllFilesAsked(this)
com.droiddeck.launcher.files.AllFilesAccess.open(this)
}
} else if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// From Android 11, shared storage outside the app's own folders is all-files access, which the file picker asks for when a shared drive is opened.
if (Build.VERSION.SDK_INT < 30 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this)
@@ -2020,6 +2011,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setMicAsked(this)
}
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
com.droiddeck.launcher.session.Onboarding.onFirstRunReady = firstRunReady
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
if (!SessionState.running) Thread({
com.droiddeck.launcher.session.LogMigration.run(this)
@@ -2299,7 +2291,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return super.dispatchGenericMotionEvent(event)
}
@Volatile private var inFront = false
private var autoSteamPending = false
/** Runs on the worker thread that finishes setup, so the foreground state is read as setup completes, not when the UI thread gets to it. */
private val firstRunReady: () -> Unit = {
val front = inFront
runOnUiThread { if (front) autoStartSteam() }
}
private fun autoStartSteam() {
if (isFinishing || isDestroyed || SessionState.running || !inFront) return
if (busy) autoSteamPending = true else playSteam()
}
override fun onPause() {
inFront = false
stopRightStickScroll()
compatLaunchVisible = false
if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, true)
@@ -2308,6 +2315,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onResume() {
super.onResume()
inFront = true
if (!homeChoiceOpen) {
HomeApp.releaseUnusedHomeEntry(this)
refreshHomeAppState()
@@ -2443,6 +2451,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onDestroy() {
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
if (com.droiddeck.launcher.session.Onboarding.onFirstRunReady === firstRunReady) com.droiddeck.launcher.session.Onboarding.onFirstRunReady = null
queuedLaunchRunner.destroy()
triggerKeys.cancel()
launchCoordinator.cancelAll()
@@ -3742,6 +3751,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
if (autoSteamPending) { autoSteamPending = false; autoStartSteam() }
}
}, "runtime-operation").start()
}
@@ -26,6 +26,12 @@ internal object MaliAutoRoute {
fun userChoice(keyStored: Boolean, owner: String, route: String): Boolean = keyStored && owner != route
fun venusStandsIn(available: Boolean, hostVulkanOk: Boolean, venusOn: Boolean, venusExplicit: Boolean, gpuName: String): Boolean =
available && hostVulkanOk && if (venusExplicit) venusOn else !venusStallsOn(gpuName)
// Steam's web helper dies on its first window through Venus on these (#2879), so the bridge stands in.
fun venusStallsOn(gpuName: String): Boolean = gpuName.contains("G2-Ultra", ignoreCase = true)
fun shouldEnd(ownsRoute: String, mali: Boolean, installedPair: Boolean): Boolean =
mali && installedPair && ownsRoute != NONE
}
@@ -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
}
}
@@ -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
@@ -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)
@@ -18,18 +18,15 @@ public class DirectAudioRelayComponent extends SessionPart {
private File logFile;
private final File micFifoPath;
private volatile int pid = -1;
private final Object stateLock = new Object();
private final Object micLock = new Object();
private boolean micHot;
private boolean outputStopped;
private final File micControl;
private final File outputControl;
public java.util.function.Consumer<Boolean> onMicEnabled;
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
this.socketPath = socketPath;
this.micFifoPath = micFifoPath;
this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
this.outputControl = new File(socketPath.getParentFile(), "output-enabled");
}
public void setLogFile(File file) {
@@ -39,11 +36,9 @@ public class DirectAudioRelayComponent extends SessionPart {
@Override
public void start() {
stop();
synchronized (stateLock) {
synchronized (micLock) {
micHot = false;
outputStopped = false;
}
outputControl.delete();
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
if (!binary.isFile()) {
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
@@ -72,7 +67,6 @@ public class DirectAudioRelayComponent extends SessionPart {
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
command.append(" --socket ").append(socketPath.getAbsolutePath());
command.append(" --log");
command.append(" --output-control ").append(outputControl.getAbsolutePath());
final boolean withMic = micFifoPath != null && setMicEnabled(true);
if (withMic) {
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
@@ -99,7 +93,6 @@ public class DirectAudioRelayComponent extends SessionPart {
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
trackOutput(line);
if (withMic) trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
});
@@ -108,27 +101,9 @@ public class DirectAudioRelayComponent extends SessionPart {
}
public synchronized boolean setMicEnabled(boolean enabled) {
return micControl != null && writeControl(micControl, enabled);
}
public boolean setOutputEnabled(boolean enabled) {
synchronized (stateLock) {
outputStopped = false;
}
return writeControl(outputControl, enabled);
}
private static boolean writeControl(File control, boolean enabled) {
File next = new File(control.getPath() + ".new");
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(control);
}
private void trackOutput(String line) {
if (!line.equals("DA-Relay: output enabled=0")) return;
synchronized (stateLock) {
outputStopped = true;
stateLock.notifyAll();
}
if (micControl == null) return false;
File next = new File(micControl.getPath() + ".new");
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
}
private void trackMic(String line) {
@@ -137,28 +112,20 @@ public class DirectAudioRelayComponent extends SessionPart {
}
boolean start = line.startsWith("DA-Relay: mic start ");
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
synchronized (stateLock) {
synchronized (micLock) {
micHot = start;
stateLock.notifyAll();
micLock.notifyAll();
}
}
public boolean awaitMicReleased(long timeoutMs) {
return await(() -> !micHot, timeoutMs);
}
public boolean awaitOutputStopped(long timeoutMs) {
return pid == -1 || await(() -> outputStopped, timeoutMs);
}
private boolean await(java.util.function.BooleanSupplier done, long timeoutMs) {
long deadline = System.currentTimeMillis() + timeoutMs;
synchronized (stateLock) {
while (!done.getAsBoolean()) {
synchronized (micLock) {
while (micHot) {
long left = deadline - System.currentTimeMillis();
if (left <= 0) return false;
try {
stateLock.wait(left);
micLock.wait(left);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
@@ -8,9 +8,18 @@ import android.os.Environment
import android.provider.Settings
object AllFilesAccess {
private val VOLUME = Regex("^(/storage/emulated/\\d+|/storage/[^/]+|/sdcard)(/.*)?$")
private val APP_FOLDERS = listOf("/Android/data", "/Android/obb")
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
sdk >= Build.VERSION_CODES.R && !granted()
/** Whether reading [path] takes all-files access: shared storage, outside the per-app folders directly under a volume's root, which Android always lets the app use. */
fun covers(path: String): Boolean {
val inside = VOLUME.matchEntire(path)?.groupValues?.get(2) ?: return false
return APP_FOLDERS.none { inside == it || inside.startsWith("$it/") }
}
fun open(context: Context) {
val app = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + context.packageName))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -504,13 +504,15 @@ fun FileManagerScreen(
}
val drives = remember(storageTick) { StorageRoots.list(context) }
var accessDrive by remember { mutableStateOf<String?>(null) }
var accessWasMissing by remember { mutableStateOf(AllFilesAccess.missing()) }
var accessDeclined by remember { mutableStateOf(false) }
fun unreadable(drive: StorageRoot) {
if (AllFilesAccess.missing()) accessDrive = drive.label
else Toast.makeText(context, context.getString(R.string.fm_drive_not_readable, drive.label), Toast.LENGTH_SHORT).show()
}
accessDrive?.let { label ->
OutlinedAlertDialog(
onDismissRequest = { accessDrive = null },
onDismissRequest = { accessDrive = null; accessDeclined = true },
title = { Text(stringResource(R.string.fm_drive_access_title, label)) },
text = { Text(stringResource(R.string.fm_drive_access_text)) },
confirmButton = {
@@ -519,9 +521,17 @@ fun FileManagerScreen(
AllFilesAccess.open(context)
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) }
},
dismissButton = { TextButton(onClick = { accessDrive = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { accessDrive = null; accessDeclined = true }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
LaunchedEffect(currentDir, storageTick) {
if (!AllFilesAccess.missing()) {
if (accessWasMissing) { accessWasMissing = false; loadDirectory(currentDir, resetScroll = false, record = false) }
} else {
accessWasMissing = true
if (!accessDeclined && accessDrive == null && AllFilesAccess.covers(currentDir.path)) accessDrive = drives.firstOrNull { currentDir.path.startsWith(it.dir.path) }?.label ?: context.getString(R.string.fm_drive_internal)
}
}
val linuxRoot = remember(storageTick) {
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
}
@@ -59,7 +59,7 @@ public final class PadBridge {
private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4];
private final Map<Integer, Boolean> rightStickLayouts = new HashMap<>();
private final boolean[][] keyTriggers = new boolean[SLOTS][2];
private final TriggerKey[][] keyTriggers = TriggerKey.slots(SLOTS);
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
@@ -484,7 +484,7 @@ public final class PadBridge {
stateFor(slot).clear();
retainedSticks[slot] = 0;
Arrays.fill(rawSticks[slot], 0f);
Arrays.fill(keyTriggers[slot], false);
for (TriggerKey key : keyTriggers[slot]) key.reset();
}
private void mutateState(java.util.function.Consumer<PadState> mutation) {
@@ -570,26 +570,76 @@ public final class PadBridge {
return true;
}
static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog, boolean[] held, int side) {
static final class TriggerKey {
static final float RELEASE_FROM_PEAK = 0.05f;
boolean held;
boolean handoff;
boolean axisLive;
boolean axisMovedWhilePressed;
float peak;
float axis;
static TriggerKey[][] slots(int count) {
TriggerKey[][] keys = new TriggerKey[count][2];
for (TriggerKey[] pair : keys) {
pair[0] = new TriggerKey();
pair[1] = new TriggerKey();
}
return keys;
}
void reset() {
held = false;
handoff = false;
axisLive = false;
axisMovedWhilePressed = false;
peak = 0f;
axis = 0f;
}
}
static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog, TriggerKey[] keys, int side) {
TriggerKey key = keys[side];
if (repeatCount > 0) return current;
if (!analog) {
held[side] = pressed;
key.held = pressed;
return pressed ? 1f : 0f;
}
if (pressed) {
if (current != 0f) return current;
held[side] = true;
key.axisMovedWhilePressed = false;
if (key.axisLive || current != 0f) return current;
key.held = true;
return 1f;
}
if (!held[side]) return current;
held[side] = false;
if (!key.axisMovedWhilePressed) key.axisLive = false;
if (key.handoff) {
key.handoff = false;
return key.axis;
}
if (!key.held) return current;
key.held = false;
return 0f;
}
static float axisTrigger(float value, boolean[] held, int side) {
if (!held[side]) return value;
if (value == 0f) return 1f;
held[side] = false;
static float axisTrigger(float value, TriggerKey[] keys, int side) {
TriggerKey key = keys[side];
key.axis = value;
if (value != 0f) {
key.axisLive = true;
key.axisMovedWhilePressed = true;
}
if (key.held) {
if (value == 0f) return 1f;
key.held = false;
key.handoff = true;
key.peak = value;
return 1f;
}
if (key.handoff) {
key.peak = Math.max(key.peak, value);
if (value > key.peak - TriggerKey.RELEASE_FROM_PEAK) return 1f;
key.handoff = false;
}
return value;
}
@@ -302,9 +302,9 @@ class LinuxNetworkLinkComponent(
val etc = File(rootDir, "etc")
replace(File(etc, "resolv.conf"), text)
val hosts = File(etc, "hosts")
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
}
val existing = if (hosts.isFile) hosts.readText() else null
val wanted = hostsText(existing)
if (wanted != existing) replace(hosts, wanted)
Log.i(TAG, "resolver: " + servers.joinToString(" "))
} catch (e: IOException) {
Log.w(TAG, "Could not write the resolver", e)
@@ -338,6 +338,42 @@ class LinuxNetworkLinkComponent(
companion object {
private val WRITES = Any()
private const val HOSTS_BLOCK_START = "# DroidDeck: Unity telemetry is refused (start)"
private const val HOSTS_BLOCK_END = "# DroidDeck: Unity telemetry is refused (end)"
// Unity 5's player seeds its bundled OpenSSL before its first HTTPS request, and that code jumps
// to a bad address under FEX (Windlands, 428370). Refusing these telemetry hosts makes the request
// fail before TLS starts; the games run without them.
internal val UNITY_TELEMETRY_HOSTS = listOf(
"config.uca.cloud.unity3d.com", "api.uca.cloud.unity3d.com", "cdp.cloud.unity3d.com",
"stats.unity3d.com", "perf-events.cloud.unity3d.com",
)
internal fun hostsText(existing: String?): String {
val kept = mutableListOf<String>()
var block: MutableList<String>? = null
for (line in existing.orEmpty().lines()) {
when {
line == HOSTS_BLOCK_START -> {
block?.let(kept::addAll)
block = mutableListOf()
}
line == HOSTS_BLOCK_END -> block = null
block != null -> block!!.add(line)
else -> kept.add(line)
}
}
block?.let(kept::addAll)
kept.removeAll { it.isBlank() }
return buildString {
if (kept.none { it.substringBefore('#').contains("localhost") }) append("127.0.0.1 localhost\n::1 localhost\n")
kept.forEach { append(it).append('\n') }
append(HOSTS_BLOCK_START).append('\n')
append("0.0.0.0 ").append(UNITY_TELEMETRY_HOSTS.joinToString(" ")).append('\n')
append(HOSTS_BLOCK_END).append('\n')
}
}
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty()
@@ -29,6 +29,10 @@ object Onboarding {
/** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */
val firstRun = MutableStateFlow(true)
/** Called once, when this process finishes the first-run downloads itself; not when everything was already in place. */
@Volatile var onFirstRunReady: (() -> Unit)? = null
@Volatile private var worked = false
fun attach(context: Context) {
appContext = context.applicationContext
val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
@@ -52,8 +56,10 @@ object Onboarding {
private fun markFirstRunDone() {
val context = appContext ?: return
val live = firstRun.value && worked
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
firstRun.value = false
if (live) onFirstRunReady?.invoke()
}
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
@@ -90,6 +96,7 @@ object Onboarding {
}
fun report(step: Step, label: String, percent: Int) {
worked = true
failed.value = failed.value - step
active.value = active.value + (step to Progress(label, percent))
keepAlive()
@@ -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()
}
@@ -960,12 +960,6 @@ object SessionPrefs {
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
fun allFilesAsked(context: Context): Boolean = prefs(context).getBoolean("allFilesAsked", false)
fun setAllFilesAsked(context: Context) {
prefs(context).edit().putBoolean("allFilesAsked", true).apply()
}
fun bluetoothAsked(context: Context): Boolean = prefs(context).getBoolean("bluetoothAsked", false)
fun setBluetoothAsked(context: Context) {
@@ -1235,6 +1229,11 @@ object SessionPrefs {
prefs(context).edit().putBoolean("venus", on).apply()
}
/** Venus off with no choice stored, so that Auto turning it off does not read as the user's own choice. */
fun clearVenus(context: Context) {
prefs(context).edit().remove("venus").apply()
}
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
}
@@ -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
@@ -903,23 +904,16 @@ class SessionService : Service() {
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 })
},
suspendAudio = {
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
val relayOutputStopping = relay?.setOutputEnabled(false)
if (relayOutputStopping == false) Log.w(TAG, "could not stop DirectAudio output")
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
if (!pulse.setMicSuspended(true)) Log.w(TAG, "could not suspend microphone source")
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay != null && !relay.awaitMicReleased(MIC_RELEASE_TIMEOUT_MS)) {
Log.w(TAG, "microphone still open after ${MIC_RELEASE_TIMEOUT_MS} ms; suspending anyway")
}
if (relay != null && relayOutputStopping == true && !relay.awaitOutputStopped(OUTPUT_RELEASE_TIMEOUT_MS)) {
Log.w(TAG, "DirectAudio output still started after ${OUTPUT_RELEASE_TIMEOUT_MS} ms; suspending anyway")
}
},
resumeAudio = {
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay?.setOutputEnabled(true) == false) Log.w(TAG, "could not resume DirectAudio output")
},
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.dd-zram"),
clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.dd-clock"),
@@ -2658,7 +2652,6 @@ class SessionService : Service() {
private const val TAG = "SessionService"
private const val TRACER_NICE = -6
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
private const val OUTPUT_RELEASE_TIMEOUT_MS = 2_000L
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
private const val GAME_PREFIX = "DROIDDECK_GAME_"
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
@@ -50,4 +50,28 @@ class MaliAutoRouteTest {
assertTrue(MaliAutoRoute.userChoice(true, MaliAutoRoute.VENUS, MaliAutoRoute.BRIDGE))
assertFalse(MaliAutoRoute.userChoice(false, MaliAutoRoute.NONE, MaliAutoRoute.BRIDGE))
}
@Test
fun venusTheUserSwitchedOffIsNotSwitchedBackOn() {
assertFalse(MaliAutoRoute.venusStandsIn(true, true, false, true, "Mali-G715"))
assertTrue(MaliAutoRoute.venusStandsIn(true, true, true, true, "Mali-G2-Ultra-NX MC12"))
}
@Test
fun venusIsAutosStandInOnlyWhereSteamStartsThroughIt() {
assertTrue(MaliAutoRoute.venusStandsIn(true, true, false, false, "Mali-G715"))
assertFalse(MaliAutoRoute.venusStandsIn(true, true, false, false, "Mali-G2-Ultra-NX MC12"))
assertFalse(MaliAutoRoute.venusStandsIn(true, true, true, false, "Mali-G2-Ultra-NX MC16"))
assertFalse(MaliAutoRoute.venusStandsIn(false, true, true, true, "Mali-G715"))
assertFalse(MaliAutoRoute.venusStandsIn(true, false, true, true, "Mali-G715"))
}
@Test
fun venusThatAutoTurnedOffIsStillAutosToTurnOn() {
// Auto clears the stored key when it moves to the bridge: a stored "off" would read as the user's own choice.
val cleared = MaliAutoRoute.userChoice(keyStored = false, owner = MaliAutoRoute.BRIDGE, route = MaliAutoRoute.VENUS)
val writtenOff = MaliAutoRoute.userChoice(keyStored = true, owner = MaliAutoRoute.BRIDGE, route = MaliAutoRoute.VENUS)
assertTrue(MaliAutoRoute.venusStandsIn(true, true, false, cleared, "Mali-G715"))
assertFalse(MaliAutoRoute.venusStandsIn(true, true, false, writtenOff, "Mali-G715"))
}
}
@@ -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))
}
}
@@ -1,109 +0,0 @@
package com.droiddeck.launcher.audio
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class DirectAudioOutputTest {
@get:Rule val folder = TemporaryFolder()
@Test fun outputControlIsWrittenWithAndWithoutTheMicrophone() {
for (fifo in listOf(null, File(folder.root, "mic.fifo"))) {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), fifo)
val control = File(folder.root, "output-enabled")
assertTrue(relay.setOutputEnabled(false))
assertEquals("0", control.readText())
assertTrue(relay.setOutputEnabled(true))
assertEquals("1", control.readText())
}
}
@Test fun suspendWaitsForTheRelayToStopItsOutput() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), File(folder.root, "mic.fifo"))
ReflectionHelpers.setField(relay, "pid", 4242)
assertTrue(relay.setOutputEnabled(false))
assertFalse(relay.awaitOutputStopped(0))
output(relay, "DA-Relay: mic stop (session toggle)")
output(relay, "DA-Relay: output enabled=1")
assertFalse(relay.awaitOutputStopped(0))
output(relay, "DA-Relay: output enabled=0")
assertTrue(relay.awaitOutputStopped(0))
assertTrue(relay.setOutputEnabled(true))
assertFalse(relay.awaitOutputStopped(0))
}
@Test fun lateAcknowledgementReleasesAWaitingSuspend() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
ReflectionHelpers.setField(relay, "pid", 4242)
assertTrue(relay.setOutputEnabled(false))
val ack = Thread {
Thread.sleep(100)
output(relay, "DA-Relay: output enabled=0")
}
ack.start()
assertTrue(relay.awaitOutputStopped(5_000))
ack.join()
}
@Test fun outputAcknowledgementLeavesTheMicrophoneWait() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), File(folder.root, "mic.fifo"))
ReflectionHelpers.setField(relay, "pid", 4242)
mic(relay, "DA-Relay: mic start (game wants it, 1 consumer(s))")
output(relay, "DA-Relay: output enabled=0")
assertFalse(relay.awaitMicReleased(0))
mic(relay, "DA-Relay: mic stop (game)")
assertTrue(relay.awaitMicReleased(0))
}
@Test fun relayThatIsNotRunningDoesNotDelaySuspend() {
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
assertTrue(relay.setOutputEnabled(false))
assertTrue(relay.awaitOutputStopped(5_000))
}
@Test fun startClearsAStaleStopAndPassesTheOutputControl() {
val context = RuntimeEnvironment.getApplication()
val info = context.applicationInfo
val previous = info.nativeLibraryDir
val nativeDir = folder.newFolder("native")
val args = File(folder.root, "arguments")
File(nativeDir, DirectAudioRelayComponent.BINARY).apply {
writeText("#!/bin/sh\nprintf '%s\\n' \"\$@\" > '${args.path}.new'\nmv '${args.path}.new' '${args.path}'\n")
setExecutable(true)
}
val control = File(folder.root, "output-enabled").apply { writeText("0") }
val relay = DirectAudioRelayComponent(File(folder.root, "relay.sock"), null)
relay.attach(context)
try {
info.nativeLibraryDir = nativeDir.path
relay.start()
val deadline = System.nanoTime() + 3_000_000_000L
while (!args.isFile && System.nanoTime() < deadline) Thread.sleep(10)
assertTrue("Playback helper did not start", args.isFile)
assertFalse(control.exists())
val command = args.readLines()
val at = command.indexOf("--output-control")
assertTrue(at >= 0)
assertEquals(control.absolutePath, command[at + 1])
assertFalse(command.contains("--mic-fifo"))
} finally {
info.nativeLibraryDir = previous
}
}
private fun output(relay: DirectAudioRelayComponent, line: String) = call(relay, "trackOutput", line)
private fun mic(relay: DirectAudioRelayComponent, line: String) = call(relay, "trackMic", line)
private fun call(relay: DirectAudioRelayComponent, method: String, line: String) =
ReflectionHelpers.callInstanceMethod<Unit>(relay, method, ReflectionHelpers.ClassParameter.from(String::class.java, line))
}
@@ -21,4 +21,20 @@ class AllFilesAccessTest {
assertTrue(AllFilesAccess.missing(sdk = 35) { false })
assertFalse(AllFilesAccess.missing(sdk = 35) { true })
}
@Test
fun onlySharedStorageNeedsIt() {
assertTrue(AllFilesAccess.covers("/storage/emulated/0"))
assertTrue(AllFilesAccess.covers("/storage/1A2B-3C4D/Games"))
assertTrue(AllFilesAccess.covers("/sdcard/Download"))
assertFalse(AllFilesAccess.covers("/storage/emulated/0/Android/data"))
assertFalse(AllFilesAccess.covers("/storage/1A2B-3C4D/Android/obb"))
assertTrue(AllFilesAccess.covers("/storage/emulated/0/Android"))
assertTrue(AllFilesAccess.covers("/storage/emulated/0/Android/database"))
assertTrue(AllFilesAccess.covers("/storage/emulated/0/Download/Android/data"))
assertTrue(AllFilesAccess.covers("/storage/1A2B-3C4D/Games/Android/obb/x"))
assertFalse(AllFilesAccess.covers("/storage/emulated/0/Android/data/com.droiddeck.launcher/files"))
assertFalse(AllFilesAccess.covers("/storage/1A2B-3C4D/Android/obb/com.droiddeck.launcher"))
assertFalse(AllFilesAccess.covers("/data/user/0/com.droiddeck.launcher/files"))
}
}
@@ -259,7 +259,7 @@ class PadPartialAxesTest {
}
@Test fun keyTriggerDecision() {
val held = BooleanArray(2)
val held = PadBridge.TriggerKey.slots(1)[0]
assertEquals(1f, PadBridge.keyTrigger(0f, true, 0, false, held, 0))
assertEquals(0f, PadBridge.keyTrigger(1f, false, 0, false, held, 0))
assertEquals(0.25f, PadBridge.keyTrigger(0.25f, true, 1, false, held, 0))
@@ -271,6 +271,64 @@ class PadPartialAxesTest {
assertEquals(0f, PadBridge.axisTrigger(0f, held, 1))
}
@Test fun keyBeforeAxisOnAFullPullIsOnePress() {
val device = device(MotionEvent.AXIS_GAS)
motion(device)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
assertEquals(1f, pad().rightTrigger)
for (value in listOf(0.1f, 0.3f, 0.6f, 1f, 0.98f)) {
motion(device, MotionEvent.AXIS_GAS to value)
assertEquals(1f, pad().rightTrigger)
}
motion(device, MotionEvent.AXIS_GAS to 0.7f)
assertEquals(0.7f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0.7f, pad().rightTrigger)
motion(device, MotionEvent.AXIS_GAS to 0f)
assertEquals(0f, pad().rightTrigger)
}
@Test fun releasingDuringTheHandoffFollowsTheAxis() {
val device = device(MotionEvent.AXIS_GAS)
motion(device)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
motion(device, MotionEvent.AXIS_GAS to 0.4f)
assertEquals(1f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0.4f, pad().rightTrigger)
}
@Test fun movingTriggerAxisStaysAnalogWhenItsKeyFiresFirst() {
val device = device(MotionEvent.AXIS_GAS)
motion(device, MotionEvent.AXIS_GAS to 0.5f)
motion(device, MotionEvent.AXIS_GAS to 0f)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
assertEquals(0f, pad().rightTrigger)
motion(device, MotionEvent.AXIS_GAS to 0.1f)
assertEquals(0.1f, pad().rightTrigger)
motion(device, MotionEvent.AXIS_GAS to 0.35f)
assertEquals(0.35f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
motion(device, MotionEvent.AXIS_GAS to 0f)
assertEquals(0f, pad().rightTrigger)
}
@Test fun triggerSwitchedToDigitalPressesAgainAfterOneSilentPress() {
val device = device(MotionEvent.AXIS_GAS)
motion(device, MotionEvent.AXIS_GAS to 0.5f)
motion(device, MotionEvent.AXIS_GAS to 0f)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
motion(device)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
assertEquals(1f, pad().rightTrigger)
motion(device)
assertEquals(1f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0f, pad().rightTrigger)
}
@Test fun silentTriggerAxesLetTheirKeysPress() {
val device = device(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER)
motion(device)
@@ -294,11 +352,15 @@ class PadPartialAxesTest {
key(device, KeyEvent.KEYCODE_BUTTON_L2)
assertEquals(1f, pad().leftTrigger)
motion(device, MotionEvent.AXIS_LTRIGGER to 0.4f)
assertEquals(0.4f, pad().leftTrigger)
assertEquals(1f, pad().leftTrigger)
motion(device, MotionEvent.AXIS_LTRIGGER to 0f)
assertEquals(0f, pad().leftTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.ACTION_UP)
assertEquals(0f, pad().leftTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_L2)
assertEquals(0f, pad().leftTrigger)
motion(device, MotionEvent.AXIS_LTRIGGER to 0.4f)
assertEquals(0.4f, pad().leftTrigger)
}
private fun pad(): PadState = requireNotNull(JoyConPadTest.RecordingWriter.pads[0])
@@ -188,4 +188,57 @@ class LinuxNetworkLinkComponentTest {
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n"))
assertEquals("nameserver 8.8.8.8\n", file.readText())
}
private val telemetryLine = "0.0.0.0 " + LinuxNetworkLinkComponent.UNITY_TELEMETRY_HOSTS.joinToString(" ")
@Test
fun newHostsFileHasLocalhostAndRefusesUnityTelemetry() {
val text = LinuxNetworkLinkComponent.hostsText(null)
assertTrue(text.startsWith("127.0.0.1 localhost\n::1 localhost\n"))
assertTrue(text.contains("$telemetryLine\n"))
assertTrue("stats.unity3d.com" in LinuxNetworkLinkComponent.UNITY_TELEMETRY_HOSTS)
}
@Test
fun hostsKeepsTheUsersLinesAndWritesTheBlockOnce() {
val user = "127.0.0.1 localhost\n::1 localhost\n10.0.0.5 nas.lan\n"
val once = LinuxNetworkLinkComponent.hostsText(user)
assertTrue(once.startsWith(user))
assertEquals(once, LinuxNetworkLinkComponent.hostsText(once))
assertEquals(1, once.lines().count { it == telemetryLine })
}
@Test
fun hostsReplacesAnOlderBlockWithTheCurrentList() {
val old = "127.0.0.1 localhost\n# DroidDeck: Unity telemetry is refused (start)\n0.0.0.0 old.example\n" +
"# DroidDeck: Unity telemetry is refused (end)\n10.0.0.5 nas.lan\n"
val text = LinuxNetworkLinkComponent.hostsText(old)
assertFalse(text.contains("old.example"))
assertTrue(text.contains("10.0.0.5 nas.lan\n"))
assertTrue(text.contains("$telemetryLine\n"))
}
@Test
fun hostsKeepsTheUsersLinesAfterAStartMarkerWithoutAnEnd() {
val broken = "127.0.0.1 localhost\n# DroidDeck: Unity telemetry is refused (start)\n10.0.0.5 nas.lan\n"
val once = LinuxNetworkLinkComponent.hostsText(broken)
assertTrue(once.contains("10.0.0.5 nas.lan\n"))
assertEquals(1, once.lines().count { it == "# DroidDeck: Unity telemetry is refused (start)" })
val twice = LinuxNetworkLinkComponent.hostsText(once)
assertTrue(twice.contains("10.0.0.5 nas.lan\n"))
assertEquals(once, twice)
}
@Test
fun hostsDropsAStrayEndMarker() {
val text = LinuxNetworkLinkComponent.hostsText("127.0.0.1 localhost\n# DroidDeck: Unity telemetry is refused (end)\n10.0.0.5 nas.lan\n")
assertTrue(text.startsWith("127.0.0.1 localhost\n10.0.0.5 nas.lan\n"))
assertEquals(1, text.lines().count { it == "# DroidDeck: Unity telemetry is refused (end)" })
}
@Test
fun hostsAddsLocalhostOnlyWhenItIsMissing() {
assertTrue(LinuxNetworkLinkComponent.hostsText("10.0.0.5 nas.lan\n").startsWith("127.0.0.1 localhost\n::1 localhost\n10.0.0.5 nas.lan\n"))
assertEquals(1, LinuxNetworkLinkComponent.hostsText("127.0.0.1 localhost\n").lines().count { "localhost" in it })
}
}
+9
View File
@@ -193,6 +193,15 @@ A Unity game under FEX (`UnityPlayer.dll` for Windows builds under Proton,
turns it off: without TSO such games can deadlock or crash (seen with Megabonk
and Crab Game). A FEX preset chosen for the game itself still applies.
An Inno Setup installer added as a game runs with the Stability preset's FEX
settings (full TSO, full x87 precision, no multiblock). Under the default
Performance + TSO preset the 32-bit setup stub corrupts its own paths and stops
with Wine's "Path not fpund." dialog (#1277, #3067). The stub is found by the
setup loader's offset-table ID in its resources, or by the `Inno` marker that
loaders older than 5.1.5 keep at offset 0x30. GOG installs avoid the stub by
extracting natively. A FEX preset chosen for the installer's own entry still
applies.
Games launched through Proton get `vblank_mode=0`, so OpenGL does not wait for
each screen refresh. Wine asks for a swap interval of 1 on every OpenGL window, and WineD3D's front-buffer
drawing (DirectDraw, Direct3D 1–7) never lowers it, so those games ran at the
+13
View File
@@ -150,6 +150,19 @@ The SPIR-V version the driver gets:
- This is what Dawn ("Disable SPIR-V 1.4 on Android ARM"), ANGLE (`supportsSPIRV14`) and naga
(`AVOID_SPIRV_COPY_LOGICAL`) do for a proprietary compiler they cannot trust.
Geometry shaders:
- The Mali-G610's driver (r38p1) crashes compiling Zink's geometry shaders, always at the same
place (SIGSEGV at 0x40 in `cmpbe_v2_compile_multiple_shaders`): its shader for `GL_QUADS`, and
a GLSL geometry shader that only passes triangles on.
- A geometry shader that only passes triangles on, from a plain Vulkan program, does not crash it
but draws nothing, in SPIR-V 1.0, 1.3 and 1.6, with and without the layer.
- Zink writes them in SPIR-V 1.6 with the Vulkan memory model, which the version cap leaves alone.
Lowering them would not help, since the plain shader draws nothing at 1.0 and 1.3 either.
- On ARM GPUs the layer reports no `geometryShader` to Zink (engine name `mesa zink`). Mesa then
splits quads into triangles itself, and Zink still offers OpenGL 3.2. DXVK keeps the feature: it
needs it for D3D10 and 11.
- `DROIDDECK_MALI_COMPAT_NO_GS=0` keeps the feature for Zink, `=1` hides it from every application.
Files:
- `layer.c`: loader plumbing, feature and limit reporting, device creation, the hook table.
- `pipeline.c`: pipelines, shader modules, viewports.
-1
View File
@@ -11,7 +11,6 @@ case "$(uname -s)" in
esac
toolchain="$NDK/toolchains/llvm/prebuilt/$host/bin"
patch -d "$source_dir" -p1 < "$repo_root/tools/directaudio/microphone-toggle.patch"
patch -d "$source_dir" -p1 < "$repo_root/tools/directaudio/output-pause.patch"
"$toolchain/aarch64-linux-android28-clang" -O2 -Wl,-z,max-page-size=16384 \
"$source_dir/directaudio-relay.c" -o "$repo_root/app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so" \
-laaudio -llog -pthread
-127
View File
@@ -1,127 +0,0 @@
--- a/directaudio-relay.c
+++ b/directaudio-relay.c
@@ -73,6 +73,9 @@
static const char *g_mic_control;
static int g_mic_enabled = 1;
static pthread_mutex_t g_mic_operations = PTHREAD_MUTEX_INITIALIZER;
+static const char *g_output_control;
+static int g_output_enabled = 1;
+static pthread_mutex_t g_output_operations = PTHREAD_MUTEX_INITIALIZER;
static void rlog(const char *fmt, ...)
{
@@ -495,8 +498,11 @@
AAudioStream_getPerformanceMode(aq), c->share, AAudioStream_getSharingMode(aq),
c->out->target_frames);
- r = AAudioStream_requestStart(aq);
- if (r != AAUDIO_OK) { AAudioStream_close(aq); return r; }
+ if (__atomic_load_n(&g_output_enabled, __ATOMIC_ACQUIRE))
+ {
+ r = AAudioStream_requestStart(aq);
+ if (r != AAUDIO_OK) { AAudioStream_close(aq); return r; }
+ }
__atomic_store_n(&c->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
c->wd_last_tick_ns = 0;
@@ -517,6 +523,7 @@
__atomic_store_n(&c->reopen_redo, 0, __ATOMIC_SEQ_CST);
if (c->dead) break;
+ pthread_mutex_lock(&g_output_operations);
if (open_output(c, &neu) == AAUDIO_OK)
{
pthread_mutex_lock(&c->lock);
@@ -532,6 +539,7 @@
AAudioStream_close(old);
RLOG("[%d] reopened output", c->pid);
}
+ pthread_mutex_unlock(&g_output_operations);
if (__atomic_load_n(&c->reopen_redo, __ATOMIC_SEQ_CST)) { usleep(20000); continue; }
__atomic_store_n(&c->reopen_running, 0, __ATOMIC_SEQ_CST);
@@ -570,6 +578,7 @@
if (!c->watchdog) return;
if (!__atomic_load_n(&c->aq, __ATOMIC_SEQ_CST)) return;
+ if (!__atomic_load_n(&g_output_enabled, __ATOMIC_ACQUIRE)) return;
prev_tick = c->wd_last_tick_ns;
c->wd_last_tick_ns = now;
@@ -882,6 +891,39 @@
REVENT("mic enabled=%d", enabled);
}
+static void output_control_update(void)
+{
+ FILE *f;
+ int enabled;
+ struct client *c;
+ if (!g_output_control) return;
+ f = fopen(g_output_control, "r");
+ enabled = !f || fgetc(f) != '0';
+ if (f) fclose(f);
+ if (enabled == __atomic_load_n(&g_output_enabled, __ATOMIC_ACQUIRE)) return;
+ pthread_mutex_lock(&g_output_operations);
+ __atomic_store_n(&g_output_enabled, enabled, __ATOMIC_RELEASE);
+ pthread_mutex_lock(&g_clients_lock);
+ for (c = g_clients; c; c = c->next)
+ {
+ AAudioStream *aq;
+ if (c->dead) continue;
+ pthread_mutex_lock(&c->lock);
+ aq = c->aq;
+ if (aq && enabled)
+ {
+ c->wd_last_tick_ns = 0;
+ __atomic_store_n(&c->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
+ if (AAudioStream_requestStart(aq) != AAUDIO_OK) request_reopen(c, "restart failed");
+ }
+ else if (aq) AAudioStream_requestStop(aq);
+ pthread_mutex_unlock(&c->lock);
+ }
+ pthread_mutex_unlock(&g_clients_lock);
+ pthread_mutex_unlock(&g_output_operations);
+ REVENT("output enabled=%d", enabled);
+}
+
static void *mic_reopen_thread(void *unused)
{
(void)unused;
@@ -1313,7 +1355,9 @@
ack.status = AAUDIO_ERROR_NO_MEMORY;
goto reply;
}
+ pthread_mutex_lock(&g_output_operations);
r = open_output(c, &c->aq);
+ pthread_mutex_unlock(&g_output_operations);
if (r != AAUDIO_OK)
{
REVENT("[%d] output open failed: %d", c->pid, r);
@@ -1383,6 +1427,7 @@
nanosleep(&iv, NULL);
mic_control_update();
+ output_control_update();
if (++tick % 10) continue;
if (g_rt_path[0])
@@ -1430,8 +1475,9 @@
if (!strcmp(argv[i], "--socket") && i + 1 < argc) path = argv[++i];
else if (!strcmp(argv[i], "--mic-fifo") && i + 1 < argc) fifo_path = argv[++i];
else if (!strcmp(argv[i], "--mic-control") && i + 1 < argc) g_mic_control = argv[++i];
+ else if (!strcmp(argv[i], "--output-control") && i + 1 < argc) g_output_control = argv[++i];
else if (!strcmp(argv[i], "--log")) g_verbose = 1;
- else { fprintf(stderr, "usage: directaudio-relay --socket <path> [--mic-fifo <path>] [--mic-control <path>] [--log]\n"); return 2; }
+ else { fprintf(stderr, "usage: directaudio-relay --socket <path> [--mic-fifo <path>] [--mic-control <path>] [--output-control <path>] [--log]\n"); return 2; }
}
if (!path)
{
@@ -1459,6 +1505,7 @@
mic_control_update();
REVENT("mic enabled=%d", __atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE));
+ output_control_update();
if (pthread_create(&th, NULL, housekeeping_thread, NULL) == 0) pthread_detach(th);
if (fifo_path && fifo_setup(fifo_path) != 0)
REVENT("mic-fifo: disabled");
+21
View File
@@ -474,3 +474,24 @@ Short strokes never released it, and taps kept landing at the relative pointer i
counts its touch-down warps, and a frame that contains one is left out of the hold decision. Touch drags, mouse motion
and mouse warps still count, so a drag on a game that follows the pointer releases the hold and a recentring game is
still held. `tools/tests/test_gamescope_pointer_hold_touch_down.py` compiles the rule with the 0133 rule.
## 0146 rendervulkan: composite only into output images the display has finished scanning out
The host compositor now releases a zero-copy display buffer as soon as the display latches the next one, and attaches
the display's release fence to the buffer's dma-buf instead of waiting for it on the CPU. That wait had held every
release back by about one refresh, so a chain of three buffers ran at two thirds of the refresh rate. KGSL Turnip does
not wait on fences attached to a dma-buf, so the composite now checks each output image's dma-buf with `poll(POLLOUT)`.
It picks the next image that is neither held by the host nor still being scanned out. Only when every free image is
still on the display does it wait for one, up to 100 ms. On kernels that cannot attach the fence, the host keeps
waiting itself and nothing changes. `tools/gamescope/tests/nested-swapchain.cpp` covers the choice and the busy check.
## 0147 wlserver: a touch click presses after the pointer has moved to the finger
In the Left, Right and Middle touch click modes a touch-down warped the pointer to the finger and pressed the button in
the same instant. A game that handles the press before it updates the hovered item on that frame acted on the item
under the previous tap. When the touch-down moves the pointer, the press now waits 34 ms, about one frame at 30 fps, so
the game sees the hover first. A tap that lifts sooner, or within 50 ms of the press, keeps the button down for 50 ms,
so the game still sees a press and a release on separate frames. A finger that moves more than 16 pixels before the
press presses at once where it touched, so drags start under the finger. A new touch first finishes the previous tap.
A touch that does not move the pointer, and trackpad mode, press at once as before.
`tools/tests/test_gamescope_touch_click_hover.py` compiles the rule from this patch.
@@ -0,0 +1,106 @@
diff --git a/src/output_image_pick.hpp b/src/output_image_pick.hpp
new file mode 100644
index 0000000..193d9de
--- /dev/null
+++ b/src/output_image_pick.hpp
@@ -0,0 +1,50 @@
+#pragma once
+#include <cstdint>
+#include <poll.h>
+
+namespace gamescope
+{
+struct OutputImagePick
+{
+ uint32_t image;
+ bool scanoutPending;
+};
+
+template <typename Held, typename Busy>
+inline OutputImagePick PickOutputImage( uint32_t count, uint32_t first, uint32_t last, uint32_t deferred,
+ Held &&held, Busy &&busy )
+{
+ for ( int pass = 0; pass < 2; pass++ )
+ {
+ for ( uint32_t i = 0; i < count; i++ )
+ {
+ const uint32_t image = ( first + i ) % count;
+ if ( count > 3 && ( image == last || image == deferred ) )
+ continue;
+ if ( held( image ) )
+ continue;
+ const bool pending = busy( image );
+ if ( pass == 0 && pending )
+ continue;
+ return { image, pending };
+ }
+ }
+ return { first, busy( first ) };
+}
+
+inline bool DmabufScanoutPending( int fd )
+{
+ if ( fd < 0 )
+ return false;
+ pollfd p = { .fd = fd, .events = POLLOUT, .revents = 0 };
+ return poll( &p, 1, 0 ) == 0;
+}
+
+inline void WaitDmabufScanout( int fd, int timeoutMs )
+{
+ if ( fd < 0 )
+ return;
+ pollfd p = { .fd = fd, .events = POLLOUT, .revents = 0 };
+ poll( &p, 1, timeoutMs );
+}
+}
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 1d3a80c..3668a10 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -37,6 +37,7 @@
#include "steamcompmgr.hpp"
#include "log.hpp"
#include "Utils/Process.h"
+#include "output_image_pick.hpp"
#include "cs_composite_blit.h"
#include "cs_composite_blur.h"
@@ -4297,18 +4298,29 @@ static bool vulkan_output_image_held( uint32_t nImage )
return false;
}
+static bool vulkan_output_image_scanout_pending( uint32_t nImage )
+{
+ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } )
+ {
+ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && gamescope::DmabufScanoutPending( pImage->dmabuf().fd[0] ) )
+ return true;
+ }
+ return false;
+}
+
static uint32_t vulkan_free_output_image( uint32_t nFirst )
{
- const uint32_t uCount = g_output.outputImages.size();
- for ( uint32_t i = 0; i < uCount; i++ )
+ const gamescope::OutputImagePick pick = gamescope::PickOutputImage( g_output.outputImages.size(), nFirst,
+ g_output.nLastOutImage, g_output.nDeferredOutImage, vulkan_output_image_held, vulkan_output_image_scanout_pending );
+ if ( pick.scanoutPending )
{
- const uint32_t nImage = ( nFirst + i ) % uCount;
- if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) )
- continue;
- if ( !vulkan_output_image_held( nImage ) )
- return nImage;
+ for ( const auto &pImage : { g_output.outputImages[ pick.image ], g_output.outputImagesPartialOverlay[ pick.image ] } )
+ {
+ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr )
+ gamescope::WaitDmabufScanout( pImage->dmabuf().fd[0], 100 );
+ }
}
- return nFirst;
+ return pick.image;
}
std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc<CVulkanTexture> pPipewireTexture, bool partial, gamescope::Rc<CVulkanTexture> pOutputOverride, bool increment, std::unique_ptr<CVulkanCmdBuffer> pInCommandBuffer )
@@ -0,0 +1,248 @@
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -3315,6 +3315,167 @@ static bool touch_click_lift( TouchClickState &state, int nTouchId )
return !bTracked && state.nOwner < 0;
}
+static bool touch_click_release_held( uint32_t time )
+{
+ bool bReleasedAny = false;
+ for ( int i = 0; i < WLSERVER_BUTTON_COUNT; i++ )
+ {
+ if ( wlserver.button_held[ i ] == true )
+ {
+ uint32_t button = TouchClickModeToLinuxButton( (gamescope::TouchClickMode) i );
+
+ if ( button != 0 )
+ {
+ wlr_seat_pointer_notify_button( wlserver.wlr.seat, time, button, WL_POINTER_BUTTON_STATE_RELEASED );
+ bReleasedAny = true;
+ }
+
+ wlserver.button_held[ i ] = false;
+ }
+ }
+
+ if ( bReleasedAny == true )
+ {
+ wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ }
+ return bReleasedAny;
+}
+
+static constexpr uint64_t k_ulTouchClickHoverNs = 34'000'000ul;
+static constexpr uint64_t k_ulTouchClickHoldNs = 50'000'000ul;
+static constexpr double k_flTouchClickSlop = 16.0;
+
+enum class TouchClickStep { Idle, Press, Release };
+
+struct TouchClickTap
+{
+ uint32_t uButton = 0;
+ uint32_t uTime = 0;
+ uint64_t ulEventAt = 0;
+ uint64_t ulPressedAt = 0;
+ double flDownX = 0.0;
+ double flDownY = 0.0;
+ bool bPressPending = false;
+ bool bLifted = false;
+};
+
+static uint64_t touch_click_tap_down( TouchClickTap &tap, uint32_t uButton, uint32_t uTime, uint64_t ulNow, double flX, double flY, bool bMoved )
+{
+ tap = TouchClickTap{};
+ tap.uButton = uButton;
+ tap.uTime = uTime;
+ tap.ulEventAt = ulNow;
+ tap.flDownX = flX;
+ tap.flDownY = flY;
+ tap.bPressPending = bMoved;
+ if ( !bMoved )
+ tap.ulPressedAt = ulNow;
+ return bMoved ? k_ulTouchClickHoverNs : 0;
+}
+
+static bool touch_click_tap_motion( const TouchClickTap &tap, double flX, double flY )
+{
+ return tap.bPressPending && std::hypot( flX - tap.flDownX, flY - tap.flDownY ) > k_flTouchClickSlop;
+}
+
+static void touch_click_tap_pressed( TouchClickTap &tap, uint64_t ulNow )
+{
+ tap.bPressPending = false;
+ tap.ulPressedAt = ulNow;
+}
+
+static bool touch_click_tap_up( TouchClickTap &tap, uint32_t uTime, uint64_t ulNow, uint64_t *pDelay )
+{
+ tap.bLifted = true;
+ tap.uTime = uTime;
+ tap.ulEventAt = ulNow;
+ *pDelay = 0;
+ if ( tap.bPressPending )
+ return true;
+ const uint64_t ulHeld = ulNow - tap.ulPressedAt;
+ if ( ulHeld >= k_ulTouchClickHoldNs )
+ {
+ tap = TouchClickTap{};
+ return false;
+ }
+ *pDelay = k_ulTouchClickHoldNs - ulHeld;
+ return true;
+}
+
+static TouchClickStep touch_click_tap_fire( TouchClickTap &tap, uint64_t ulNow, uint64_t *pDelay )
+{
+ *pDelay = 0;
+ if ( tap.bPressPending )
+ {
+ touch_click_tap_pressed( tap, ulNow );
+ if ( tap.bLifted )
+ *pDelay = k_ulTouchClickHoldNs;
+ return TouchClickStep::Press;
+ }
+ if ( tap.bLifted )
+ {
+ tap = TouchClickTap{};
+ return TouchClickStep::Release;
+ }
+ return TouchClickStep::Idle;
+}
+
+static uint32_t touch_click_tap_time( const TouchClickTap &tap, uint64_t ulNow )
+{
+ return tap.uTime + uint32_t( ( ulNow - tap.ulEventAt ) / 1'000'000ul );
+}
+
+static TouchClickTap s_TouchTap;
+static struct wl_event_source *s_pTouchTapTimer = nullptr;
+
+static bool touch_click_tap_arm( uint64_t ulDelay )
+{
+ if ( !s_pTouchTapTimer )
+ s_pTouchTapTimer = wl_event_loop_add_timer( wlserver.event_loop, []( void * ) -> int
+ {
+ uint64_t ulDelay = 0;
+ const uint64_t ulNow = get_time_in_nanos();
+ const uint32_t uTime = touch_click_tap_time( s_TouchTap, ulNow );
+ const uint32_t uButton = s_TouchTap.uButton;
+ const TouchClickStep eStep = touch_click_tap_fire( s_TouchTap, ulNow, &ulDelay );
+ if ( eStep == TouchClickStep::Press )
+ {
+ wlr_seat_pointer_notify_button( wlserver.wlr.seat, uTime, uButton, WL_POINTER_BUTTON_STATE_PRESSED );
+ wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ if ( ulDelay )
+ touch_click_tap_arm( ulDelay );
+ }
+ else if ( eStep == TouchClickStep::Release )
+ {
+ touch_click_release_held( uTime );
+ }
+ bump_input_counter();
+ return 0;
+ }, nullptr );
+ if ( !s_pTouchTapTimer )
+ return false;
+ wl_event_source_timer_update( s_pTouchTapTimer, int( std::max<uint64_t>( 1, ( ulDelay + 999'999ul ) / 1'000'000ul ) ) );
+ return true;
+}
+
+static void touch_click_tap_settle( uint64_t ulNow )
+{
+ if ( s_pTouchTapTimer )
+ wl_event_source_timer_update( s_pTouchTapTimer, 0 );
+ uint64_t ulDelay = 0;
+ const uint32_t uTime = touch_click_tap_time( s_TouchTap, ulNow );
+ const uint32_t uButton = s_TouchTap.uButton;
+ TouchClickStep eStep = touch_click_tap_fire( s_TouchTap, ulNow, &ulDelay );
+ if ( eStep == TouchClickStep::Press )
+ {
+ wlr_seat_pointer_notify_button( wlserver.wlr.seat, uTime, uButton, WL_POINTER_BUTTON_STATE_PRESSED );
+ wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ eStep = touch_click_tap_fire( s_TouchTap, ulNow, &ulDelay );
+ }
+ if ( eStep == TouchClickStep::Release )
+ touch_click_release_held( uTime );
+}
+
void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool bAlwaysWarpCursor, gamescope::IBackendConnector* connector )
{
assert( wlserver_is_lock_held() );
@@ -3372,6 +3533,9 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
{
g_bPendingTouchMovement = true;
+ if ( touch_click_drives( s_TouchClick, touch_id ) && touch_click_tap_motion( s_TouchTap, tx, ty ) )
+ touch_click_tap_settle( get_time_in_nanos() );
+
wlserver_mousewarp( tx, ty, time, false, !bAlwaysWarpCursor );
}
}
@@ -3426,18 +3590,30 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
{
g_bPendingTouchMovement = true;
+ const uint64_t ulNow = get_time_in_nanos();
+ touch_click_tap_settle( ulNow );
+
+ bool bMoved = false;
if ( eMode != gamescope::TouchClickModes::Trackpad )
{
+ const double flFromX = wlserver.mouse_surface_cursorx;
+ const double flFromY = wlserver.mouse_surface_cursory;
wlserver_mousewarp( tx, ty, time, false, true );
wlserver.ulTouchDownWarps++;
+ bMoved = flFromX != wlserver.mouse_surface_cursorx || flFromY != wlserver.mouse_surface_cursory;
}
uint32_t button = TouchClickModeToLinuxButton( eMode );
if ( touch_click_press( wlserver.button_held, eMode, button ) )
{
- wlr_seat_pointer_notify_button( wlserver.wlr.seat, time, button, WL_POINTER_BUTTON_STATE_PRESSED );
- wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ const uint64_t ulDelay = touch_click_tap_down( s_TouchTap, button, time, ulNow, tx, ty, bMoved );
+ if ( !ulDelay || !touch_click_tap_arm( ulDelay ) )
+ {
+ touch_click_tap_pressed( s_TouchTap, ulNow );
+ wlr_seat_pointer_notify_button( wlserver.wlr.seat, time, button, WL_POINTER_BUTTON_STATE_PRESSED );
+ wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
+ }
}
}
}
@@ -3450,28 +3626,12 @@ void wlserver_touchup( int touch_id, uint32_t time )
assert( wlserver_is_lock_held() );
// Release whatever the touch pressed even if its surface is gone, or the seat keeps the button down.
- bool bReleasedAny = false;
const bool bClickTouch = touch_click_lift( s_TouchClick, touch_id );
- for ( int i = 0; bClickTouch && i < WLSERVER_BUTTON_COUNT; i++ )
- {
- if ( wlserver.button_held[ i ] == true )
- {
- uint32_t button = TouchClickModeToLinuxButton( (gamescope::TouchClickMode) i );
-
- if ( button != 0 )
- {
- wlr_seat_pointer_notify_button( wlserver.wlr.seat, time, button, WL_POINTER_BUTTON_STATE_RELEASED );
- bReleasedAny = true;
- }
-
- wlserver.button_held[ i ] = false;
- }
- }
-
- if ( bReleasedAny == true )
- {
- wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
- }
+ uint64_t ulDelay = 0;
+ if ( bClickTouch && !touch_click_tap_up( s_TouchTap, time, get_time_in_nanos(), &ulDelay ) )
+ touch_click_release_held( time );
+ else if ( bClickTouch && ulDelay && !touch_click_tap_arm( ulDelay ) )
+ touch_click_tap_settle( get_time_in_nanos() );
if ( wlserver.touch_down_ids.count( touch_id ) > 0 )
{
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d
GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02
GAMESCOPE_TAG=gamescope-3.16.29-53b5432e
GAMESCOPE_SHA256=f88afe15f6b0fbb980cf4c7d9b757819c92131adf69eebf2c40a3dd53153df1f
@@ -2,6 +2,9 @@
#include "nested_surface_format.hpp"
#include "dmabuf_import.hpp"
#include "sdl_refresh.hpp"
#include "output_image_pick.hpp"
#include <fcntl.h>
#include <unistd.h>
#include <cassert>
#include <cstdio>
@@ -152,5 +155,43 @@ int main()
assert(DmabufMemoryType(memory, 7, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX);
assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == UINT32_MAX);
using gamescope::PickOutputImage;
auto none = [](uint32_t) { return false; };
auto pick = PickOutputImage(5, 2, 1, 0, none, none);
assert(pick.image == 2 && !pick.scanoutPending);
auto heldTwo = [](uint32_t i) { return i == 2; };
pick = PickOutputImage(5, 2, 1, 0, heldTwo, none);
assert(pick.image == 3 && !pick.scanoutPending);
auto scanningTwo = [](uint32_t i) { return i == 2; };
pick = PickOutputImage(5, 2, 1, 0, none, scanningTwo);
assert(pick.image == 3 && !pick.scanoutPending);
auto scanningAll = [](uint32_t) { return true; };
pick = PickOutputImage(5, 2, 1, 0, heldTwo, scanningAll);
assert(pick.image == 3 && pick.scanoutPending);
auto heldAll = [](uint32_t) { return true; };
auto scanningOne = [](uint32_t i) { return i == 1; };
pick = PickOutputImage(5, 2, 1, 0, heldAll, none);
assert(pick.image == 2 && !pick.scanoutPending);
pick = PickOutputImage(5, 1, 0, 1, heldAll, scanningOne);
assert(pick.image == 1 && pick.scanoutPending);
pick = PickOutputImage(3, 1, 0, 2, none, none);
assert(pick.image == 1 && !pick.scanoutPending);
pick = PickOutputImage(3, 1, 0, 2, none, scanningOne);
assert(pick.image == 2 && !pick.scanoutPending);
int fds[2];
assert(pipe(fds) == 0);
assert(!gamescope::DmabufScanoutPending(fds[1]));
assert(!gamescope::DmabufScanoutPending(-1));
fcntl(fds[1], F_SETFL, O_NONBLOCK);
char block[4096] = {};
while (write(fds[1], block, sizeof(block)) > 0) {}
assert(gamescope::DmabufScanoutPending(fds[1]));
gamescope::WaitDmabufScanout(fds[1], 1);
while (read(fds[0], block, sizeof(block)) == sizeof(block) && gamescope::DmabufScanoutPending(fds[1])) {}
assert(!gamescope::DmabufScanoutPending(fds[1]));
close(fds[0]);
close(fds[1]);
std::puts("Gamescope presentation and DMA-BUF import tests passed");
}
@@ -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"))
@@ -66,6 +66,69 @@ DOTNET_FEX = {
"FEX_HALFBARRIERTSOENABLED": "1",
"FEX_X87REDUCEDPRECISION": "0",
}
STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0")
# Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders
# from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30.
INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj")
INNO_RESOURCE_LIMIT = 4 << 20
def is_inno_setup(path):
try:
with open(path, "rb") as exe:
head = exe.read(4096)
if head[:2] != b"MZ":
return False
if head[0x30:0x34] == b"Inno":
return True
pe = int.from_bytes(head[0x3C:0x40], "little")
if head[pe:pe + 4] != b"PE\0\0" or int.from_bytes(head[pe + 4:pe + 6], "little") != 0x14C:
return False
count = int.from_bytes(head[pe + 6:pe + 8], "little")
table = pe + 24 + int.from_bytes(head[pe + 20:pe + 22], "little")
for entry in range(table, table + 40 * count, 40):
if head[entry:entry + 8].rstrip(b"\0") == b".rsrc":
exe.seek(int.from_bytes(head[entry + 20:entry + 24], "little"))
size = int.from_bytes(head[entry + 16:entry + 20], "little")
resources = exe.read(min(size, INNO_RESOURCE_LIMIT))
return any(marker in resources for marker in INNO_LOADER_IDS)
except OSError:
pass
return False
STORE_LAUNCHER = ".droiddeck-launch.bat"
STORE_SIDECAR = ".droiddeck-store.json"
def store_game_exe(exe):
if os.path.basename(exe).lower() != STORE_LAUNCHER:
return exe
folder = os.path.dirname(exe)
try:
with open(os.path.join(folder, STORE_SIDECAR), encoding="utf-8") as source:
sidecar = json.load(source)
except (OSError, ValueError):
return exe
target = sidecar.get("exe") if isinstance(sidecar, dict) else None
if not isinstance(target, str) or not target.strip() or "\0" in target:
return exe
normalized = target.replace("\\", "/")
if ":" in normalized or normalized.startswith("/") or ".." in normalized.split("/"):
return exe
relative = os.path.normpath(normalized)
if os.path.isabs(relative) or relative in (".", "..") or relative.startswith(".." + os.sep):
return exe
candidate = os.path.join(folder, relative)
if not os.path.isfile(candidate):
return exe
root = os.path.realpath(folder)
try:
if os.path.commonpath((root, os.path.realpath(candidate))) != root:
return exe
except ValueError:
return exe
return candidate
def game_files(exe):
@@ -89,6 +152,7 @@ def game_files(exe):
class Game:
def __init__(self, exe, args, app_id=""):
exe = store_game_exe(exe)
self.exe = exe
self.args = args
self.app_id = app_id
@@ -191,6 +255,12 @@ def split_second_x87_fip(game):
return {"FEX_JITFEATURES": "enablex87fip"}, [], "Split/Second: FEX x87 FIP emulation on (its SecuROM stops with error 8016 without it)"
@fix
def inno_setup_stability(game):
if is_inno_setup(game.exe):
return STABILITY_FEX, [], "Inno Setup installer: FEX Stability settings (under Performance + TSO the 32-bit setup stub corrupts its own paths)"
@fix
def doom_2016_swapchain_images(game):
if "doomx64vk.exe" in game.files and game.stem in ("doomx64", "doomx64vk"):
@@ -273,7 +343,7 @@ def with_system_settings(text, settings):
# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch.
def dragon_quest_monsters_4_mesh_detail(exe, env):
project = Path(exe).stem.split("-", 1)[0]
project = Path(store_game_exe(exe)).stem.split("-", 1)[0]
if not project.lower().startswith("dragonquestmonsters4"):
return
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
@@ -398,7 +468,7 @@ def zomboid_rewrite(node):
def project_zomboid_jvm(command):
if len(command) <= 2:
return
exe = Path(command[2])
exe = Path(store_game_exe(command[2]))
if not exe.stem.lower().startswith("projectzomboid"):
return
settings = exe.with_suffix(".json")
@@ -721,12 +791,15 @@ def apply_config(env, config, app_id, fixes=None):
def render_path_defaults(command, env):
if len(command) < 3 or command[1] != "waitforexitandrun" or Path(command[2]).name.lower() != "spintires.exe":
if len(command) < 3 or command[1] != "waitforexitandrun":
return None
exe = Path(store_game_exe(command[2]))
if exe.name.lower() != "spintires.exe":
return None
own = env.get("DXVK_CONFIG", "")
if re.search(r"(?:^|;)\s*dxvk\.tilerMode\s*=", own) or env.get("DXVK_CONFIG_FILE"):
return None
if Path("dxvk.conf").is_file() or Path(command[2]).with_name("dxvk.conf").is_file():
if Path("dxvk.conf").is_file() or exe.with_name("dxvk.conf").is_file():
return None
driver = env.get("VK_DRIVER_FILES", env.get("VK_ICD_FILENAMES", ""))
if Path(driver).parent.name != "DD-Turnip_v0.4.0":
@@ -1290,7 +1363,7 @@ def dirt_ws2_wanted(command, env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if len(command) < 3 or not prefix or not os.path.isfile(DIRT_WS2):
return None
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(command[2]))[0].lower())
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(store_game_exe(command[2])))[0].lower())
if not game or not dirt_telemetry_on(prefix, game) or proton_has_dirt_fix(command[0]):
return None
return prefix if os.path.lexists(prefix_ws2(prefix)) else None
@@ -1347,7 +1420,7 @@ def ego_core_plan(command, env):
count = windows_core_count(env)
if not count or len(command) < 3:
return None
folder = Path(command[2]).parent
folder = Path(store_game_exe(command[2])).parent
path = folder / EGO_RESTRICTIONS
try:
raw = path.read_bytes()
@@ -1676,14 +1749,26 @@ def main():
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
else:
# An installer started with the run verb gets the same Stability settings as one started with
# waitforexitandrun; explicit game settings still win over them in apply_config.
installer = {}
if len(command) > 2 and command[1] == "run" and is_inno_setup(command[2]):
installer = dict(STABILITY_FEX)
print("droiddeck-game-env: Inno Setup installer: FEX Stability settings", file=sys.stderr)
path = Path.home() / ".config/droiddeck/game-environment.json"
try:
with path.open(encoding="utf-8") as source:
config = json.load(source)
env = apply_config(env, sync_config(config, app_id), app_id)
synced = sync_config(config, app_id)
if installer:
# A FEX preset chosen for the game itself still wins, as on every other launch path.
game = config.get("games", {}).get(app_id, {})
synced["games"][app_id].update({k: v for k, v in game.items() if k in STABILITY_FEX})
env = apply_config(env, synced, app_id, installer)
except FileNotFoundError:
pass
env = dict(env, **installer)
except (OSError, ValueError, TypeError, AttributeError):
env = dict(env, **installer)
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if waiting:
before_debug = env
@@ -224,15 +224,23 @@ if [ -n "${DD_VK_DRIVER:-}" ]; then
unset dd_icd_lib
fi
dd_webhelper_layout() {
local layout
if [ -n "${DD_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then
printf '%s\n' "$DD_VKBRIDGE_WEBHELPER_ARGS"
elif [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then
echo stock
elif [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
echo "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
else
echo "--use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE"
return
fi
if [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then
echo stock
return
fi
# ANGLE switches must not replace the helper's stable single-process layout.
layout="--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
if [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
layout="$layout --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
else
layout="$layout --use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE"
fi
printf '%s\n' "$layout"
}
dd_now_ms() {
if [ -n "${EPOCHREALTIME:-}" ]; then
@@ -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
@@ -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
+57 -1
View File
@@ -203,10 +203,17 @@ static void test_handle_map_null_key(void)
map_free(&map);
}
static int zink_instance_table;
static struct object mock_zink_instance = {&zink_instance_table};
static struct object mock_arm = {&instance_table};
static struct object mock_zink_arm = {&zink_instance_table}, mock_zink_other = {&zink_instance_table};
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance)
{
*instance = (VkInstance)&mock_instance;
const VkApplicationInfo *app = info->pApplicationInfo;
bool zink = app && app->pEngineName && !strcmp(app->pEngineName, "mesa zink");
*instance = (VkInstance)(zink ? &mock_zink_instance : &mock_instance);
return VK_SUCCESS;
}
@@ -223,6 +230,7 @@ static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDevice
{
memset(features, 0, sizeof(*features));
features->dualSrcBlend = physical == (VkPhysicalDevice)&mock_capable;
features->geometryShader = VK_TRUE;
}
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features)
@@ -234,6 +242,8 @@ static void VKAPI_CALL mock_properties(VkPhysicalDevice physical, VkPhysicalDevi
{
memset(properties, 0, sizeof(*properties));
strcpy(properties->deviceName, "mock");
bool arm = physical == (VkPhysicalDevice)&mock_arm || physical == (VkPhysicalDevice)&mock_zink_arm;
properties->vendorID = arm ? 0x13b5 : 0;
properties->limits.maxFragmentDualSrcAttachments = physical == (VkPhysicalDevice)&mock_capable;
}
@@ -385,6 +395,50 @@ static void destroy_device(VkDevice device)
((PFN_vkDestroyDevice)layer_gdpa(device, "vkDestroyDevice"))(device, NULL);
}
static void test_geometry_shader_hidden_from_zink(void)
{
VkPhysicalDeviceFeatures features;
PFN_vkGetPhysicalDeviceFeatures plain_features =
(PFN_vkGetPhysicalDeviceFeatures)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures");
PFN_vkGetPhysicalDeviceFeatures2 plain_features2 =
(PFN_vkGetPhysicalDeviceFeatures2)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures2");
VkPhysicalDeviceFeatures2 queried = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
plain_features((VkPhysicalDevice)&mock_lacking, &features);
assert(features.geometryShader);
plain_features((VkPhysicalDevice)&mock_arm, &features);
assert(features.geometryShader);
plain_features2((VkPhysicalDevice)&mock_arm, &queried);
assert(queried.features.geometryShader);
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pEngineName = "mesa zink"};
VkLayerInstanceLink link = {NULL, mock_gipa, NULL};
VkLayerInstanceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO, {&link}};
VkInstanceCreateInfo info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &loader,
.pApplicationInfo = &app};
VkInstance zink;
assert(((PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance"))(&info, NULL, &zink) == VK_SUCCESS);
assert(zink == (VkInstance)&mock_zink_instance);
PFN_vkGetPhysicalDeviceFeatures zink_features =
(PFN_vkGetPhysicalDeviceFeatures)layer_gipa(zink, "vkGetPhysicalDeviceFeatures");
PFN_vkGetPhysicalDeviceFeatures2 zink_features2 =
(PFN_vkGetPhysicalDeviceFeatures2)layer_gipa(zink, "vkGetPhysicalDeviceFeatures2");
zink_features((VkPhysicalDevice)&mock_zink_arm, &features);
assert(!features.geometryShader && features.dualSrcBlend);
zink_features2((VkPhysicalDevice)&mock_zink_arm, &queried);
assert(!queried.features.geometryShader && queried.features.dualSrcBlend);
zink_features((VkPhysicalDevice)&mock_zink_other, &features);
assert(features.geometryShader);
setenv("DROIDDECK_MALI_COMPAT_NO_GS", "0", 1);
zink_features((VkPhysicalDevice)&mock_zink_arm, &features);
assert(features.geometryShader);
setenv("DROIDDECK_MALI_COMPAT_NO_GS", "1", 1);
plain_features((VkPhysicalDevice)&mock_lacking, &features);
assert(!features.geometryShader);
unsetenv("DROIDDECK_MALI_COMPAT_NO_GS");
((PFN_vkDestroyInstance)layer_gipa(zink, "vkDestroyInstance"))(zink, NULL);
}
static const VkPipelineColorBlendAttachmentState dual_attachment = {
VK_TRUE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_OP_ADD, 0xf,
@@ -575,6 +629,7 @@ int main(int argc, char **argv)
setenv("WINEPREFIX", "/nonexistent", 1);
unsetenv("DROIDDECK_MALI_COMPAT");
unsetenv("DROIDDECK_MALI_COMPAT_TRACE");
unsetenv("DROIDDECK_MALI_COMPAT_NO_GS");
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
layer_gipa = negotiate.pfnGetInstanceProcAddr;
@@ -587,6 +642,7 @@ int main(int argc, char **argv)
PFN_vkCreateInstance create_instance = (PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance");
assert(create_instance(&info, NULL, &instance) == VK_SUCCESS);
test_geometry_shader_hidden_from_zink();
test_lacking_device();
test_capable_device();
test_depth_compare_op();
+158
View File
@@ -1741,6 +1741,94 @@ class GameEnvironmentTest(unittest.TestCase):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_store_launcher_resolves_the_game_executable_from_the_sidecar(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "BatmanArkhamCity"
bin_dir = root / "Binaries/Win32"
bin_dir.mkdir(parents=True)
for name in ("Batman2.exe", "BatmanAC.exe"):
(bin_dir / name).touch()
launcher = root / ".droiddeck-launch.bat"
launcher.touch()
(root / ".droiddeck-store.json").write_text(json.dumps({
"store": "epic", "id": "Egret", "title": "Batman Arkham City",
"exe": "Binaries/Win32/Batman2.exe", "launcher": ".droiddeck-launch.bat",
}))
env, extra, notes = MODULE["engine_fixes"](str(launcher), [])
self.assertEqual((env, extra), ({"FEX_X87REDUCEDPRECISION": "0"}, []))
self.assertTrue(notes)
home = Path(tmp) / "home"
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"}}))
probe = home / "proton"
probe.write_text("#!" + sys.executable + "\nimport os, sys\n"
"print(os.environ.get('FEX_X87REDUCEDPRECISION', ''))\n"
"print(sys.argv[2])\n")
probe.chmod(0o755)
base = {k: v for k, v in os.environ.items() if not k.startswith(("FEX_", "WINE", "PROTON", "DROIDDECK", "DD_", "STEAM"))}
base.update(HOME=str(home), STEAM_COMPAT_DATA_PATH=str(home / "compatdata/3648205350"))
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", str(launcher)],
env=base, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.splitlines(), ["0", str(launcher)])
self.assertIn("Batman: Arkham City: FEX with full x87 precision", result.stderr)
rebirth = Path(tmp) / "FF7Rebirth"
rebirth_exe = rebirth / "End/Binaries/Win64/ff7rebirth_.exe"
rebirth_exe.parent.mkdir(parents=True)
rebirth_exe.touch()
rebirth_launcher = rebirth / ".droiddeck-launch.bat"
rebirth_launcher.touch()
(rebirth / ".droiddeck-store.json").write_text(json.dumps({
"store": "epic", "id": "ff7", "title": "FF7 Rebirth",
"exe": r"End\Binaries\Win64\ff7rebirth_.exe", "launcher": ".droiddeck-launch.bat",
}))
self.assertEqual(MODULE["engine_fixes"](str(rebirth_launcher), [])[0], {"VKD3D_FEATURE_LEVEL": "12_2"})
def test_store_launcher_ignores_missing_invalid_or_escaping_sidecar_paths(self):
with tempfile.TemporaryDirectory() as tmp:
outside = Path(tmp) / "Outside"
outside.mkdir()
outside_exe = outside / "BatmanAC.exe"
outside_exe.touch()
root = Path(tmp) / "Game"
sub = root / "sub"
sub.mkdir(parents=True)
(root / "real.exe").touch()
(sub / "nested.exe").touch()
(root / "escape.exe").symlink_to(outside_exe)
(root / "linkdir").symlink_to(outside)
launcher = root / ".droiddeck-launch.bat"
launcher.touch()
sidecar = root / ".droiddeck-store.json"
resolve = MODULE["store_game_exe"]
self.assertEqual(resolve(str(launcher)), str(launcher))
for payload in ("not-json", "[]", json.dumps({"exe": ""}), json.dumps({"exe": 123}),
json.dumps({"exe": "missing.exe"}), json.dumps({"exe": "sub"}),
json.dumps({"exe": "../Outside/BatmanAC.exe"}),
json.dumps({"exe": "sub/../real.exe"}),
json.dumps({"exe": r"sub\..\real.exe"}),
json.dumps({"exe": "linkdir/../real.exe"}),
json.dumps({"exe": "sub/../../Outside/BatmanAC.exe"}),
json.dumps({"exe": str(outside_exe)}),
json.dumps({"exe": r"C:\Windows\notepad.exe"}),
json.dumps({"exe": "escape.exe"})):
with self.subTest(payload=payload):
sidecar.write_text(payload)
self.assertEqual(resolve(str(launcher)), str(launcher))
sidecar.write_text(json.dumps({"exe": "real.exe"}))
self.assertEqual(resolve(str(launcher)), str(root / "real.exe"))
sidecar.write_text(json.dumps({"exe": "sub/nested.exe"}))
self.assertEqual(resolve(str(launcher)), str(sub / "nested.exe"))
other_bat = root / "custom.bat"
other_bat.touch()
self.assertEqual(resolve(str(other_bat)), str(other_bat))
def test_split_second_gets_x87_fip_unless_the_game_sets_jit_features(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "SplitSecond"
@@ -1762,6 +1850,76 @@ class GameEnvironmentTest(unittest.TestCase):
config["games"] = {"297860": {"FEX_JITFEATURES": "off"}}
self.assertEqual(MODULE["apply_config"]({}, config, "297860", env)["FEX_JITFEATURES"], "off")
def test_inno_setup_installers_get_the_stability_preset_over_the_default(self):
stability = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "1", "FEX_MEMCPYSETTSOENABLED": "1",
"FEX_HALFBARRIERTSOENABLED": "1", "FEX_X87REDUCEDPRECISION": "0", "FEX_MULTIBLOCK": "0"}
performance_tso = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "0", "FEX_MEMCPYSETTSOENABLED": "0",
"FEX_HALFBARRIERTSOENABLED": "0", "FEX_X87REDUCEDPRECISION": "1", "FEX_MULTIBLOCK": "1"}
def loader(path, resources=b"", machine=0x14C, section=b".rsrc", legacy=False):
dos = bytearray(0x80)
dos[:2] = b"MZ"
dos[0x3C:0x40] = (0x80).to_bytes(4, "little")
if legacy:
dos[0x30:0x34] = b"Inno"
header = b"PE\0\0" + machine.to_bytes(2, "little") + (1).to_bytes(2, "little") + bytes(12) \
+ (0xE0).to_bytes(2, "little") + bytes(2)
entry = section.ljust(8, b"\0") + bytes(8) + len(resources).to_bytes(4, "little") \
+ (0x400).to_bytes(4, "little") + bytes(16)
path.write_bytes((bytes(dos) + header + bytes(0xE0) + entry).ljust(0x400, b"\0") + resources)
return str(path)
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
table = bytes(64) + b"rDlPtS\xcd\xe6\xd7{\x0b*" + bytes(64)
installers = [
loader(folder / "setup.exe", table),
loader(folder / "setup_game_1.0.exe", bytes(64) + b"nS5W7dT\x83\xaa\x1b\x0fj"),
loader(folder / "old_setup.exe", legacy=True),
]
for installer in installers:
env, extra, notes = MODULE["engine_fixes"](installer, [])
self.assertEqual((env, extra), (stability, []), installer)
self.assertTrue(notes)
config = {"version": 1, "shared": performance_tso}
self.assertEqual({k: v for k, v in MODULE["apply_config"]({}, config, "42", env).items() if k in stability},
stability)
config["games"] = {"42": {"FEX_MULTIBLOCK": "1"}}
self.assertEqual(MODULE["apply_config"]({}, config, "42", env)["FEX_MULTIBLOCK"], "1")
not_installers = [
loader(folder / "Game.exe", bytes(256)),
loader(folder / "Game64.exe", table, machine=0x8664),
loader(folder / "Data.exe", table, section=b".data"),
folder / "missing.exe",
]
(folder / "notes.exe").write_bytes(b"rDlPtS\xcd\xe6\xd7{\x0b*")
not_installers.append(folder / "notes.exe")
for other in not_installers:
self.assertEqual(MODULE["engine_fixes"](str(other), []), ({}, [], []), other)
# The run verb skips engine_fixes; an installer started that way still gets Stability.
probe = folder / "proton"
probe.write_text("#!" + sys.executable + "\nimport json, os\nprint(json.dumps(dict(os.environ)))\n")
probe.chmod(0o755)
base = {**os.environ, **performance_tso, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(folder / "compatdata/42")}
def run_verb(program):
out = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "run", program],
env=base, text=True, capture_output=True, check=True).stdout
return {name: value for name, value in json.loads(out).items() if name in stability}
self.assertEqual(run_verb(installers[0]), stability)
self.assertEqual(run_verb(str(folder / "Game.exe")), performance_tso)
config_path = folder / ".config/droiddeck/game-environment.json"
config_path.parent.mkdir(parents=True)
config_path.write_text(json.dumps({"version": 1, "shared": {"WINEESYNC": "1"}}))
self.assertEqual(run_verb(installers[0]), stability)
config_path.write_text(json.dumps({"version": 1, "games": {"42": {"FEX_MULTIBLOCK": "1"}}}))
self.assertEqual(run_verb(installers[0]), {**stability, "FEX_MULTIBLOCK": "1"})
config_path.write_text(json.dumps({"version": 1, "games": {"42": {"FEX_MULTIBLOCK": None}}}))
self.assertNotIn("FEX_MULTIBLOCK", run_verb(installers[0]))
def test_d3dgear_capture_hook_beside_the_game_is_turned_off(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "The Crew 2"
@@ -0,0 +1,92 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0147-touch-click-press-after-hover.patch"
def added_source(patch):
return "\n".join(line[1:] for line in patch.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
def rules(text):
begin = text.index("static constexpr uint64_t k_ulTouchClickHoverNs")
end = text.index("static TouchClickTap s_TouchTap;")
return text[begin:end]
PREAMBLE = r'''
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#define None 0L
'''
MAIN = r'''
static const uint64_t MS = 1'000'000ul;
int main() {
TouchClickTap tap;
uint64_t delay = 0;
assert(touch_click_tap_down(tap, 272, 10, 100 * MS, 50.0, 60.0, true) == k_ulTouchClickHoverNs);
assert(tap.bPressPending);
assert(!touch_click_tap_motion(tap, 55.0, 64.0));
assert(touch_click_tap_motion(tap, 80.0, 60.0));
assert(touch_click_tap_fire(tap, 134 * MS, &delay) == TouchClickStep::Press);
assert(delay == 0);
assert(!touch_click_tap_motion(tap, 300.0, 300.0));
assert(!touch_click_tap_up(tap, 400, 500 * MS, &delay));
assert(touch_click_tap_down(tap, 272, 10, 100 * MS, 50.0, 60.0, true) > 0);
assert(touch_click_tap_up(tap, 15, 105 * MS, &delay));
assert(delay == 0);
assert(touch_click_tap_fire(tap, 134 * MS, &delay) == TouchClickStep::Press);
assert(delay == k_ulTouchClickHoldNs);
assert(touch_click_tap_time(tap, 134 * MS) == 44);
assert(touch_click_tap_fire(tap, 184 * MS, &delay) == TouchClickStep::Release);
assert(touch_click_tap_fire(tap, 200 * MS, &delay) == TouchClickStep::Idle);
assert(touch_click_tap_down(tap, 272, 10, 100 * MS, 50.0, 60.0, false) == 0);
assert(!tap.bPressPending);
assert(touch_click_tap_up(tap, 30, 120 * MS, &delay));
assert(delay == 30 * MS);
assert(touch_click_tap_fire(tap, 150 * MS, &delay) == TouchClickStep::Release);
assert(touch_click_tap_down(tap, 273, 10, 100 * MS, 0.0, 0.0, false) == 0);
assert(!touch_click_tap_up(tap, 90, 180 * MS, &delay));
assert(touch_click_tap_fire(tap, 190 * MS, &delay) == TouchClickStep::Idle);
return 0;
}
'''
class GamescopeTouchClickHoverTest(unittest.TestCase):
def test_press_waits_for_the_hover_and_a_tap_is_held(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
source = PREAMBLE + rules(added_source(PATCH)) + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "touch_click_hover.cpp"
exe = Path(tmp) / "touch_click_hover"
src.write_text(source)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
def test_touch_down_defers_only_a_moved_press(self):
added = added_source(PATCH)
self.assertIn("bMoved = flFromX != wlserver.mouse_surface_cursorx || flFromY != wlserver.mouse_surface_cursory;", added)
self.assertIn("if ( !ulDelay || !touch_click_tap_arm( ulDelay ) )", added)
self.assertIn("touch_click_tap_settle( ulNow );", added)
self.assertEqual(1, added.count("touch_click_tap_motion( s_TouchTap, tx, ty )"))
self.assertIn("if ( bClickTouch && !touch_click_tap_up( s_TouchTap, time, get_time_in_nanos(), &ulDelay ) )", added)
if __name__ == "__main__":
unittest.main()
+9 -8
View File
@@ -6,6 +6,7 @@ from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
KEYS = ("DD_VKBRIDGE_WEBHELPER_ARGS", "DD_VKBRIDGE_CEF_ANGLE", "DD_VKBRIDGE_CEF_VULKAN")
BASE = "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
def layout_function():
@@ -27,14 +28,14 @@ class WebhelperLayoutTest(unittest.TestCase):
def test_angle_on_vulkan_brings_chromiums_vulkan_compositing(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan"),
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
BASE + " --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
def test_vulkan_compositing_can_be_left_off(self):
def test_vulkan_compositing_can_be_left_off_without_zygotes(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan", DD_VKBRIDGE_CEF_VULKAN="0"),
"--use-gl=angle --use-angle=vulkan")
BASE + " --use-gl=angle --use-angle=vulkan")
def test_other_angle_backends_get_only_the_angle_switches(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl")
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="gl"), BASE + " --use-gl=angle --use-angle=gl")
def test_explicit_layout_wins(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan", DD_VKBRIDGE_WEBHELPER_ARGS="--x +Y"),
@@ -57,10 +58,10 @@ class WebhelperLayoutTest(unittest.TestCase):
env = {k: v for k, v in os.environ.items() if k not in KEYS}
run = lambda **s: subprocess.run(["bash", "-c", "set -u\n" + script], env={**env, **s},
capture_output=True, text=True, check=True).stdout.strip()
self.assertEqual(run(), "--use-gl=angle --use-angle=vulkan")
self.assertEqual(run(), BASE + " --use-gl=angle --use-angle=vulkan")
self.assertEqual(run(DD_VKBRIDGE_CEF_VULKAN="1"),
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl")
BASE + " --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE="gl"), BASE + " --use-gl=angle --use-angle=gl")
def test_empty_settings_are_kept_as_set(self):
script = ': "${DD_VKBRIDGE_CEF_ANGLE=vulkan}" "${DD_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "dd_webhelper_layout\n"
@@ -69,7 +70,7 @@ class WebhelperLayoutTest(unittest.TestCase):
capture_output=True, text=True, check=True).stdout.strip()
self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE=""), "stock")
self.assertEqual(run(DD_VKBRIDGE_CEF_VULKAN=""),
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
BASE + " --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
if __name__ == "__main__":
+27 -1
View File
@@ -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'
+17 -5
View File
@@ -47,13 +47,18 @@ static int g_dev_state, g_base_black;
static uintptr_t g_dev = 1;
static struct { int64_t wait_ns, wait_max_ns; unsigned waits; } g_perf;
static VkResult answer;
static unsigned timeouts, wait_calls;
static unsigned destroyed, unmapped, freed_memory, forgotten, errors;
static int64_t perf_now(void) { return 10; }
static void perf_add(int64_t *s, int64_t *m, unsigned *c, int64_t d) { *s+=d; *m=d; ++*c; }
static void __attribute__((unused)) droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++errors; }
#define LOGE(...) droiddeck_log("error", __VA_ARGS__)
static VkResult wait_fn(uintptr_t dev, unsigned n, const VkFence *f, int all, uint64_t timeout) {
(void)dev; (void)n; (void)f; (void)all; (void)timeout; return answer;
(void)dev; (void)n; (void)f; (void)all;
++wait_calls;
if (wait_calls > 1) assert(timeout == UINT64_MAX);
if (timeouts) { --timeouts; return VK_TIMEOUT; }
return answer;
}
static void unmap_fn(uintptr_t dev, uintptr_t mem) { (void)dev; (void)mem; ++unmapped; }
static void destroy_fn(uintptr_t dev, uintptr_t img, void *allocator) { (void)dev; (void)img; (void)allocator; ++destroyed; }
@@ -104,8 +109,15 @@ int main(void) {
vkp_image_destroy(image());
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
g_dev_state=1; g_base_black=1; answer=VK_TIMEOUT;
assert(timed_wait(1, 1000)==VK_TIMEOUT);
for (unsigned delays=1; delays<=3; ++delays) {
g_dev_state=1; g_base_black=1; answer=VK_SUCCESS;
timeouts=delays; wait_calls=0;
assert(timed_wait(1, 1000)==VK_SUCCESS);
assert(g_dev_state==1 && g_base_black==1 && wait_calls==delays+1);
}
g_dev_state=1; g_base_black=1; answer=VK_ERROR_UNKNOWN; wait_calls=0;
assert(timed_wait(1, 1000)==VK_ERROR_UNKNOWN);
assert(g_dev_state!=1 && g_dev_state!=-2); /* pending work is not DEVICE_LOST */
struct vkp_image *pending=image();
vkp_image_destroy(pending);
@@ -116,14 +128,14 @@ int main(void) {
assert(errors==first_errors); /* one terminal diagnostic, no repeated recovery */
free(pending); /* fake GPU exists only in this test */
g_dev_state=1; answer=VK_ERROR_OUT_OF_HOST_MEMORY;
g_dev_state=1; answer=VK_ERROR_OUT_OF_HOST_MEMORY; wait_calls=0; timeouts=1;
assert(timed_wait(1, 1000)==VK_ERROR_OUT_OF_HOST_MEMORY);
assert(g_dev_state!=1 && g_dev_state!=-2);
pending=image(); vkp_image_destroy(pending);
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
free(pending);
g_dev_state=1; answer=VK_ERROR_DEVICE_LOST;
g_dev_state=1; answer=VK_ERROR_DEVICE_LOST; wait_calls=0; timeouts=2;
assert(timed_wait(1, 1000)==VK_ERROR_DEVICE_LOST);
assert(g_dev_state==1); /* existing caller performs genuine device-loss cleanup */
return 0;
+7 -4
View File
@@ -111,15 +111,18 @@ int __android_log_print(int, const char *, const char *, ...);
def test_later_framegen_surface_lost_idle_failure(self):
self.run_scenario('later-surface-lost')
def test_finite_blit_timeout_same_size_shm_upload(self):
self.run_scenario('shm-timeout')
def test_blit_wait_error_same_size_shm_upload(self):
self.run_scenario('shm-wait-error')
def test_finite_blit_timeout_same_size_pixel_upload(self):
self.run_scenario('pixel-timeout')
def test_blit_wait_error_same_size_pixel_upload(self):
self.run_scenario('pixel-wait-error')
def test_lost_device_shm_upload_keeps_cpu_snapshot(self):
self.run_scenario('lost-shm-upload')
def test_delayed_blit_completes_and_next_frame_renders(self):
self.run_scenario('blit-delayed')
def test_normal_present(self):
self.run_scenario('normal')
@@ -0,0 +1,141 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
from test_vk_pending_completion import function
ROOT = Path(__file__).resolve().parents[2]
SRC = ROOT / 'app/src/main/cpp/waylandcomp/src'
HARNESS = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <poll.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wayland-util.h>
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
struct wl_event_source { int unused; };
struct wl_event_loop;
enum { WL_EVENT_READABLE = 1 };
struct wl_client;
struct wl_resource { int unused; };
struct surface;
struct dmabuf_buffer { int fd; };
typedef struct AHardwareBuffer { int unused; } AHardwareBuffer;
DEFINES
STRUCT
static struct wl_list g_bufs;
static struct wl_event_loop *g_loop;
static int g_import_failed_logged;
static int import_ok, imports, imported_flags, deferred_releases, frees, sources;
static struct wl_event_source g_source;
void wl_list_init(struct wl_list *l) { l->prev = l; l->next = l; }
void wl_list_insert(struct wl_list *l, struct wl_list *e) {
e->next = l->next; e->prev = l; l->next->prev = e; l->next = e;
}
static int fake_ioctl(int fd, unsigned long req, void *arg) {
struct droiddeck_dma_buf_sync_file *f = arg;
(void)fd;
assert(req == DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE);
++imports; imported_flags = (int)f->flags;
if (import_ok) return 0;
errno = ENOTTY; return -1;
}
#define ioctl fake_ioctl
static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; }
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t m,
int (*cb)(int, uint32_t, void *), void *d) {
(void)l; (void)fd; (void)m; (void)cb; (void)d; ++sources; return &g_source;
}
static int on_fence_readable(int fd, uint32_t mask, void *data) { (void)fd; (void)mask; (void)data; return 0; }
static void send_deferred_release(struct ahb_buf *ab) { ++deferred_releases; ab->release_pending = 0; }
static void maybe_free(struct ahb_buf *ab) { (void)ab; ++frees; }
FUNCTIONS
static void reset(void) { import_ok = imports = imported_flags = deferred_releases = frees = sources = 0; }
static void run(int display, int can_import, int fence_signalled) {
reset();
wl_list_init(&g_bufs);
struct dmabuf_buffer b = {.fd = 7};
struct ahb_buf ab;
memset(&ab, 0, sizeof(ab));
ab.id = 42; ab.b = &b; ab.display = display; ab.on_layer = 1; ab.release_pending = 1; ab.fence_fd = -1;
wl_list_insert(&g_bufs, &ab.link);
int fds[2]; assert(pipe(fds) == 0);
if (fence_signalled) assert(write(fds[1], "x", 1) == 1);
import_ok = can_import;
handle_released(42, fds[0]);
assert(!ab.on_layer && imports == 1 && imported_flags == DROIDDECK_DMA_BUF_SYNC_READ);
if (can_import || fence_signalled) {
assert(deferred_releases == 1 && frees == 1 && !ab.fence_src && ab.fence_fd == -1);
errno = 0; assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
} else {
assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_source && ab.fence_fd == fds[0]);
close(fds[0]);
}
close(fds[1]);
}
int main(int argc, char **argv) {
assert(argc == 4);
run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]));
return 0;
}
'''
class ZeroCopyReleaseAtLatchTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cc = shutil.which(os.environ.get('CC', 'cc'))
if not cc:
raise AssertionError('C compiler required')
source_dir = Path(os.environ.get('DROIDDECK_DMABUF_TEST_SOURCE', SRC))
ahb = (source_dir / 'ahb_swapchain.c').read_text()
defines = '\n'.join(re.findall(r'^(?:struct droiddeck_dma_buf_sync_file \{.*?\};|#define DROIDDECK_DMA_BUF_\w+ .*)$',
ahb, re.M))
struct = re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group()
functions = '\n'.join(function(ahb, n) for n in ('find_buf', 'handle_released'))
source = HARNESS.replace('DEFINES', '#include <fcntl.h>\n#include <sys/ioctl.h>\n' + defines)
source = source.replace('STRUCT', struct).replace('FUNCTIONS', functions)
cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-release-latch-')
cls.addClassCleanup(cls.tmp.cleanup)
probe = Path(cls.tmp.name) / 'probe.c'
probe.write_text(source)
cls.binary = probe.with_suffix('')
built = subprocess.run([cc, '-std=c11', '-Wall', '-Wextra', '-Werror', '-Wno-unused-function', '-UNDEBUG',
'-I', str(SRC.parent / 'prebuilt/include'), str(probe), '-o', str(cls.binary)],
capture_output=True, text=True)
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
def scenario(self, display, can_import, fence_signalled):
result = subprocess.run([str(self.binary), str(display), str(can_import), str(fence_signalled)],
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_display_buffer_released_at_latch_when_fence_attaches(self):
self.scenario(1, 1, 0)
def test_swapchain_buffer_released_at_latch_when_fence_attaches(self):
self.scenario(0, 1, 0)
def test_display_buffer_waits_for_fence_when_kernel_cannot_attach(self):
self.scenario(1, 0, 0)
def test_swapchain_buffer_waits_for_fence_when_kernel_cannot_attach(self):
self.scenario(0, 0, 0)
def test_signalled_fence_releases_without_waiting(self):
self.scenario(1, 0, 1)
if __name__ == '__main__':
unittest.main()
+19 -6
View File
@@ -7,7 +7,7 @@ struct vk_api g_vk;
static unsigned operations, acquires, submits, markers, waits, idle_calls, resets;
static unsigned destroys, releases, lost_notifications, presented_notifications;
static VkResult idle_answer, fence_answer, acquire_answer, present_answer;
static unsigned fail_acquire_at;
static unsigned fail_acquire_at, fence_timeouts;
static int generated;
/* Every work-issuing callback is an oracle: no GPU operation after a terminal
@@ -19,7 +19,9 @@ static VkResult acquire(VkDevice d, VkSwapchainKHR s, uint64_t t, VkSemaphore a,
}
static VkResult idle(VkDevice d) { live(); ++idle_calls; return idle_answer; }
static VkResult wait_fences(VkDevice d, uint32_t n, const VkFence *f, VkBool32 all, uint64_t t) {
live(); ++waits; return fence_answer;
live(); ++waits;
if (fence_timeouts) { --fence_timeouts; return VK_TIMEOUT; }
return fence_answer;
}
static VkResult submit(VkQueue q, uint32_t n, const VkSubmitInfo *s, VkFence f) {
live(); ++submits; if (!s->commandBufferCount) ++markers; return VK_SUCCESS;
@@ -235,7 +237,7 @@ static void acquire_failure(int later, VkResult result) {
free(g_images); /* test-owned fake resources only */
}
static void upload_timeout(int single_pixel) {
static void upload_wait_error(int single_pixel) {
setup(0);
uint8_t bytes[48], saved[48], data[16];
memset(bytes, 0xa5, sizeof(bytes)); memset(data, 0x3c, sizeof(data));
@@ -251,7 +253,7 @@ static void upload_timeout(int single_pixel) {
assert(bytes[3] == 0x3c && bytes[0] == 0xa5 && releases == 1);
memcpy(saved, bytes, sizeof(saved));
struct vkp_image dst = {.image = (VkImage)(uintptr_t)9, .blit_dst = 1, .w = img->w, .h = img->h};
fence_answer = VK_TIMEOUT;
fence_answer = VK_ERROR_OUT_OF_HOST_MEMORY;
assert(vkp_blit_image(img, &dst, -1) == -1);
assert(g_dev_state == -3 && submits == 1 && waits == 1);
memset(data, 0x7e, sizeof(data));
@@ -279,8 +281,8 @@ int main(int argc, char **argv) {
else if (!strcmp(name, "first-surface-lost")) acquire_failure(0, VK_ERROR_SURFACE_LOST_KHR);
else if (!strcmp(name, "later-out-of-date")) acquire_failure(1, VK_ERROR_OUT_OF_DATE_KHR);
else if (!strcmp(name, "later-surface-lost")) acquire_failure(1, VK_ERROR_SURFACE_LOST_KHR);
else if (!strcmp(name, "shm-timeout")) upload_timeout(0);
else if (!strcmp(name, "pixel-timeout")) upload_timeout(1);
else if (!strcmp(name, "shm-wait-error")) upload_wait_error(0);
else if (!strcmp(name, "pixel-wait-error")) upload_wait_error(1);
else if (!strcmp(name, "lost-shm-upload")) {
setup(0);
uint8_t bytes[64], data[16];
@@ -295,6 +297,17 @@ int main(int argc, char **argv) {
free(img.recovery_pixels);
free(g_images);
} else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
else if (!strcmp(name, "blit-delayed")) {
setup(0);
struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1};
struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1};
fence_timeouts = 3;
assert(vkp_blit_image(&src, &dst, -1) == 0);
assert(g_dev_state == 1 && submits == 1 && waits == 4 && destroys == 0);
assert(vkp_blit_image(&src, &dst, -1) == 0);
assert(g_dev_state == 1 && submits == 2 && waits == 5 && destroys == 0);
free(g_images);
}
else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) {
int extra = !strcmp(name, "framegen"); setup(extra);
assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1);
+26
View File
@@ -344,12 +344,31 @@ static void report_limits(VkPhysicalDeviceLimits *limits, uint32_t gaps)
}
}
/* Mali's driver crashes compiling Zink's geometry shaders (SIGSEGV at 0x40 in
* cmpbe_v2_compile_multiple_shaders) and takes the render server and the application with it; a plain
* one draws nothing. Zink draws GL_QUADS through one; without the feature Mesa splits quads into
* triangles itself. DXVK needs the feature for D3D10 and 11, so only Zink loses it.
* DROIDDECK_MALI_COMPAT_NO_GS=0 keeps it for Zink, =1 hides it from every application. */
static bool hide_geometry_shader(struct instance *inst, VkPhysicalDevice physical_device)
{
const char *setting = getenv("DROIDDECK_MALI_COMPAT_NO_GS");
if (setting && *setting)
return strcmp(setting, "1") == 0;
if (!inst->zink)
return false;
VkPhysicalDeviceProperties properties;
inst->GetPhysicalDeviceProperties(physical_device, &properties);
return properties.vendorID == 0x13b5; /* ARM */
}
static VKAPI_ATTR void VKAPI_CALL GetPhysicalDeviceFeatures(VkPhysicalDevice physical_device,
VkPhysicalDeviceFeatures *features)
{
struct instance *inst = instance_from_handle(physical_device);
inst->GetPhysicalDeviceFeatures(physical_device, features);
report_features(features, physical_device_gaps(inst, physical_device));
if (hide_geometry_shader(inst, physical_device))
features->geometryShader = VK_FALSE;
}
static VKAPI_ATTR void VKAPI_CALL GetPhysicalDeviceFeatures2(VkPhysicalDevice physical_device,
@@ -363,6 +382,8 @@ static VKAPI_ATTR void VKAPI_CALL GetPhysicalDeviceFeatures2(VkPhysicalDevice ph
inst->GetPhysicalDeviceFeatures2(physical_device, features);
relink(dropped, dropped_count);
report_features(&features->features, gaps);
if (hide_geometry_shader(inst, physical_device))
features->features.geometryShader = VK_FALSE;
if (tracing()) {
char chain[512] = "";
size_t used = 0;
@@ -463,6 +484,8 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo
inst->key = dispatch_key(*instance);
inst->handle = *instance;
inst->active = wanted();
const char *engine = info->pApplicationInfo ? info->pApplicationInfo->pEngineName : NULL;
inst->zink = engine && strcmp(engine, "mesa zink") == 0;
inst->gipa = gipa;
pthread_mutex_init(&inst->lock, NULL);
#define LOAD(name) inst->name = (PFN_vk##name)gipa(*instance, "vk" #name);
@@ -624,6 +647,9 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
if (properties.limits.maxFragmentInputComponents < components)
components = properties.limits.maxFragmentInputComponents;
dev->max_varying_locations = components / 4;
if (inst->active && hide_geometry_shader(inst, physical_device))
layer_log("geometryShader is hidden from %s: the driver crashes compiling geometry shaders",
inst->zink ? "Zink" : "every application");
pthread_mutex_lock(&global_lock);
dev->next = devices;
+1
View File
@@ -63,6 +63,7 @@ struct instance {
void *key;
VkInstance handle;
bool active;
bool zink; /* the engine is Mesa's Zink */
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumerateDeviceExtensionProperties EnumerateDeviceExtensionProperties;
+60 -23
View File
@@ -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<std::mutex> 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_;
+35
View File
@@ -1,8 +1,11 @@
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <linux/capability.h>
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/syscall.h>
@@ -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; }
+120 -2
View File
@@ -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;
+69 -8
View File
@@ -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<VkImage> images;
std::vector<VkSemaphore> ready;
std::vector<std::pair<CaptureSlot *, uint64_t>> copying;
std::array<CaptureSlot, 3> 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<std::pair<uint64_t, CaptureSlot *>> 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<std::mutex> 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<std::mutex> lock(sendMutex);
std::fprintf(stderr, "[droiddeck-vr-layer] WSI headset stopped acknowledging frames; restart SteamVR\n");
failed = true; return;
}
CaptureSlot *slot;
{
std::unique_lock<std::mutex> 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<uint32_t>(slot - slots.data()), flags)) result = VK_ERROR_DEVICE_LOST;
if (!gpuSender.Post(header, static_cast<uint32_t>(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<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex); swapchains.erase(chain);
}
+1
View File
@@ -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
+15
View File
@@ -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 <typename Visit> 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;
+43 -1
View File
@@ -2,6 +2,7 @@
#include "xr_tracking.h"
#include <cstring>
#include <cmath>
#include <dlfcn.h>
#include <mutex>
#include <string>
#include <fcntl.h>
@@ -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<ClockGettime>(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_, &copy, 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<DroidDeckXrTracking *>(mapping);
return true;
}
DroidDeckXrTracking *mapping_ = nullptr;
bool attempted_ = false;
};