Compare commits

..
Author SHA1 Message Date
The412Banner d1c9a958e5 fix(game-env): Windows sees the same cores when Android pauses some
The core list given to Wine came from sched_getaffinity, which the
kernel masks with the cores active at that instant. Qualcomm kernels
pause cores under load and thermal limits, so the count and order
Windows saw changed from launch to launch on the same phone. Read the
task's allowed cores from /proc/self/status instead.
2026-11-29 08:19:48 +00:00
36 changed files with 180 additions and 1234 deletions

No files matched your search

+2 -5
View File
@@ -614,13 +614,10 @@ 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_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);
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);
}
}
} 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 (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
if (!ab->display && dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
close(fd);
} else {
if (!g_import_failed_logged) {
if (!ab->display && !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));
+33 -108
View File
@@ -148,7 +148,6 @@ struct slot {
uint32_t fmt;
int release_fd;
int busy;
uint64_t generation;
};
struct layer {
@@ -176,7 +175,6 @@ struct layer {
int votes_rate;
float fps_applied;
int recreate_pending;
int pending_callbacks;
int32_t ds_applied;
@@ -224,7 +222,6 @@ struct complete_ctx {
ASurfaceControl *sc;
int layer;
int prev_slot;
uint64_t prev_generation;
void *prev_token;
int retire;
};
@@ -291,16 +288,12 @@ 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];
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;
}
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;
@@ -315,15 +308,9 @@ 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;
@@ -410,16 +397,12 @@ 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.txDelete(tx);
droiddeck_log("layer", "%s: retirement deferred because its release callback could not be allocated", l->name);
return;
}
if (add_complete(tx, l, l->cur_slot, l->cur_token, 1) != 0) api.release(l->sc);
api.txApply(tx);
api.txDelete(tx);
} else {
droiddeck_log("layer", "%s: retirement deferred because a transaction could not be allocated", l->name);
return;
if (l->cur_token) ahb_swapchain_layer_released(l->cur_token, -1);
api.release(l->sc);
}
droiddeck_log("layer", "%s: SurfaceControl retired (window %p)", l->name, (void *)l->win);
l->sc = NULL; l->win = NULL;
@@ -438,28 +421,20 @@ 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 = &l->slots[j];
struct slot *s = &g_layers[i].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;
}
l->first_logged = 0;
l->logged_w = l->logged_h = 0;
pthread_mutex_unlock(&g_lock);
g_layers[i].first_logged = 0;
g_layers[i].logged_w = g_layers[i].logged_h = 0;
}
pthread_mutex_unlock(&g_lock);
}
static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) {
@@ -637,10 +612,7 @@ 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;
l->slots[idx].generation++;
}
if (idx >= 0) { fd = l->slots[idx].release_fd; l->slots[idx].release_fd = -1; }
pthread_mutex_unlock(&g_lock);
if (idx < 0) return -1;
if (fd >= 0 && fence_signalled(fd)) { close(fd); fd = -1; }
@@ -648,8 +620,7 @@ 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);
const uint64_t generation = s->generation;
memset(s, 0, sizeof(*s)); s->release_fd = -1; s->generation = generation;
memset(s, 0, sizeof(*s)); s->release_fd = -1;
}
if (fd >= 0 && !vkp_can_wait_sync_fd()) {
if (fence_wait(fd, 100) == 0) { slot_keep_fence(s, fd); return -1; }
@@ -688,13 +659,7 @@ 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) {
droiddeck_log("layer", "%s: keeping the old SurfaceControl until retirement completes", l->name);
return -1;
}
}
if (l->sc && l->win != win) retire_sc(l);
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; }
@@ -853,7 +818,6 @@ 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;
}
@@ -868,45 +832,24 @@ 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);
@@ -961,27 +904,23 @@ 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);
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");
if (old) api.release(old);
l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f;
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);
@@ -1228,26 +1167,15 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
return 0;
}
static int hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return 0;
static void hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return;
ASurfaceTransaction *tx = api.txCreate();
if (!tx) return -1;
api.setVisibility(tx, l->sc, ASC_VISIBILITY_HIDE);
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;
}
if (!tx) return;
replace_with_blank(tx, l);
api.setVisibility(tx, l->sc, ASC_VISIBILITY_HIDE);
add_complete(tx, l, l->cur_slot, l->cur_token, 0);
api.txApply(tx); api.txDelete(tx);
l->shown = 0; l->cur_slot = -1; l->cur_token = NULL;
return 0;
}
void sc_layer_hide(void) {
@@ -1255,20 +1183,17 @@ 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 && !g_layers[SC_LAYER_GAME].shown && !g_layers[SC_LAYER_OVERLAY].shown)
droiddeck_log("layer", "layers hidden (scene is not a single fullscreen window)");
if (said) 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) != 0) return;
if (l->shown) hide_layer(l);
retire_sc(l);
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;
}
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) {
@@ -1,36 +0,0 @@
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,17 +52,18 @@ class QuestXrActivity : NativeActivity() {
if (!closing) leaveXr("SteamVR start failed", sessionAlive())
return@Thread
}
val watch = QuestSteamVrWatch(SystemClock.elapsedRealtime())
val startupDeadline = SystemClock.elapsedRealtime() + 30_000
var lastRunning: Long? = null
while (!closing) {
if (!sessionAlive()) {
leaveXr("Steam session ended", false)
break
}
val pausedBefore = guestPaused()
val status = SteamVr.status(this)
val paused = pausedBefore || guestPaused()
if (!paused) steamVrStatus = status
if (watch.stopped(SystemClock.elapsedRealtime(), status, paused)) {
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) {
leaveXr("SteamVR stopped or did not finish starting", true)
break
}
@@ -80,8 +81,6 @@ class QuestXrActivity : NativeActivity() {
}
}
private fun guestPaused() = SessionState.suspending || SessionState.suspended || SessionState.resuming
private fun sessionAlive() = SessionState.running && !SessionState.stopRequested &&
sessionId != null && SessionState.sessionId == sessionId
@@ -54,7 +54,6 @@ import com.droiddeck.launcher.stores.StoreAchievements
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreLaunchRequests
import com.droiddeck.launcher.stores.epic.EpicClient
import com.droiddeck.launcher.ui.extendIntoCutout
import com.droiddeck.launcher.ui.SessionAchievements
import com.droiddeck.launcher.ui.screenIsOff
import com.droiddeck.launcher.gpu.Cardboard
@@ -2917,7 +2916,6 @@ 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")
@@ -6373,8 +6371,6 @@ 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)
@@ -6434,19 +6430,10 @@ 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)
@@ -7098,7 +7085,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
window.extendIntoCutout()
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.apply {
layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= 30)
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
}
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
@@ -302,9 +302,9 @@ class LinuxNetworkLinkComponent(
val etc = File(rootDir, "etc")
replace(File(etc, "resolv.conf"), text)
val hosts = File(etc, "hosts")
val existing = if (hosts.isFile) hosts.readText() else null
val wanted = hostsText(existing)
if (wanted != existing) replace(hosts, wanted)
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
}
Log.i(TAG, "resolver: " + servers.joinToString(" "))
} catch (e: IOException) {
Log.w(TAG, "Could not write the resolver", e)
@@ -338,42 +338,6 @@ 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()
@@ -1,35 +0,0 @@
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()
}
@@ -417,7 +417,6 @@ 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
@@ -57,17 +57,12 @@ import com.droiddeck.launcher.stores.StoresState
/** What the Library pretends while a developer previews it. Nothing here is saved: a restart always comes back to [OFF]. */
internal enum class LibraryPreview { OFF, NOTHING_INSTALLED, SIGNED_OUT, SAMPLE }
/** How many games the Steam home pretends are installed. Nothing here is saved. */
internal enum class SteamHomePreview(val games: Int) { OFF(-1), NONE(0), FEW(3), MANY(12) }
internal enum class DrawerPreview { STEAM, DESKTOP, GAME }
/** Developer tools' preview states: screens that are otherwise hard to reach, shown without changing anything real. */
internal object DevPreview {
var library by mutableStateOf(LibraryPreview.OFF)
var drawer by mutableStateOf<DrawerPreview?>(null)
var steamHome by mutableStateOf(SteamHomePreview.OFF)
var openSteam by mutableStateOf(false)
/** The UI zoo sheet: where previews are picked, one at a time, only when asked for. */
var zoo by mutableStateOf(false)
/** Opt-in: a preview button where its state lives (the Library's toolbar), for switching states without the zoo. */
@@ -92,41 +87,6 @@ internal fun sampleOwned(store: Store): List<CatalogItem> =
internal fun sampleInstalled(owned: Map<Store, List<CatalogItem>>): Set<String> =
owned.values.flatMap { items -> items.take(SAMPLE_INSTALLED).map { it.key } }.toSet()
/** The Steam home's games while a developer previews it: this many invented titles, no art, nothing installed. */
internal fun sampleSteamHomeGames(count: Int): List<com.droiddeck.launcher.frontend.Library.SteamGame> = listOf(
"Portal 2", "Hades", "Celeste", "Stardew Valley", "Hollow Knight", "Balatro",
"Dead Cells", "Terraria", "Vampire Survivors", "Slay the Spire", "Cuphead", "Inscryption",
).take(count).mapIndexed { i, name ->
com.droiddeck.launcher.frontend.Library.SteamGame(1000 + i, name, art = null, library = "steam", lastPlayed = 1_700_000_000_000L - i * 86_400_000L)
}
/** The pill a previewed Steam home shows, so the fake state is never mistaken for the real one. */
@Composable
internal fun SteamHomePreviewPill(modifier: Modifier = Modifier) {
val preview = DevPreview.steamHome
if (preview == SteamHomePreview.OFF) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val label = stringResource(
when (preview) {
SteamHomePreview.NONE -> R.string.dev_preview_steam_none
SteamHomePreview.FEW -> R.string.dev_preview_steam_few
else -> R.string.dev_preview_steam_many
},
)
val end = stringResource(R.string.dev_preview_end)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.background(colors.surface, CircleShape).border(1.dp, pal.signal, CircleShape)
.clickable(role = Role.Button, onClickLabel = end) { DevPreview.steamHome = SteamHomePreview.OFF }
.padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp).testTag("dev-preview-steam-end"),
) {
Icon(Icons.Outlined.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp))
Text(stringResource(R.string.dev_preview_banner, label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Icon(Icons.Filled.Close, end, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
}
/** The pill a previewed Library shows, so the fake state is never mistaken for the real one. */
@Composable
internal fun LibraryPreviewPill(modifier: Modifier = Modifier) {
@@ -255,17 +215,6 @@ internal fun UiZooSheet() {
DrawerPreview.GAME to R.string.session_title_game,
)) ActionRow(stringResource(label), null, show, onClick = { close(); DevPreview.drawer = mode }, modifier = Modifier.testTag("zoo-drawer-${mode.name.lowercase()}"))
}
SettingsGroup(stringResource(R.string.dev_preview_steam_home)) {
for ((mode, label) in listOf(
SteamHomePreview.NONE to R.string.dev_preview_steam_none,
SteamHomePreview.FEW to R.string.dev_preview_steam_few,
SteamHomePreview.MANY to R.string.dev_preview_steam_many,
)) ActionRow(
stringResource(label), null, show,
onClick = { close(); DevPreview.steamHome = mode; DevPreview.openSteam = true },
modifier = Modifier.testTag("zoo-steam-${mode.name.lowercase()}"),
)
}
SettingsGroup(stringResource(R.string.dev_preview_library)) {
for ((mode, label) in listOf(
LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed,
@@ -272,10 +272,7 @@ private fun Content(
return
}
if (selected == "steam") {
Box(modifier) {
SteamHome(s, a, Modifier.fillMaxSize())
SteamHomePreviewPill(Modifier.align(androidx.compose.ui.Alignment.BottomCenter).padding(bottom = 20.dp))
}
SteamHome(s, a, modifier)
return
}
if (selected == "store") {
@@ -658,11 +658,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
LaunchedEffect(SetupTabs.openSection) {
if (SetupTabs.openSection != null && (railSelection != "setup" || s.pageKey != null)) showRailPage("setup", true)
}
LaunchedEffect(DevPreview.openSteam) {
if (!DevPreview.openSteam) return@LaunchedEffect
DevPreview.openSteam = false
showRailPage("steam", true)
}
LaunchedEffect(DevPreview.openLibrary) {
if (!DevPreview.openLibrary) return@LaunchedEffect
DevPreview.openLibrary = false
@@ -7,7 +7,6 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Display
import android.os.Build
import android.view.View
import android.view.Window
import android.view.WindowManager
@@ -481,15 +480,6 @@ private class SurfaceEditorPresentation(private val host: ComponentActivity, dis
internal fun Window.prepareInputEditor() {
addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_FULLSCREEN)
setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
extendIntoCutout()
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
}
internal fun Window.extendIntoCutout() {
if (Build.VERSION.SDK_INT < 28) return
attributes = attributes.apply {
layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= 30) WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
@@ -113,8 +113,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
val owned = remember(ownedAll, concealed) { ownedAll.filter { it.first.toLong() !in concealed } }
val featured = remember(featuredAll, concealed) { featuredAll.filter { it.appId.toLong() !in concealed } }
val previewing = DevPreview.steamHome
val games = remember(s.steamGames, previewing, LibraryHidden.keys, LibraryHidden.steam) { (if (previewing == SteamHomePreview.OFF) s.steamGames else sampleSteamHomeGames(previewing.games)).filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val games = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) { s.steamGames.filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val narrow = LocalNarrowPane.current
var words by remember { mutableStateOf<Rect?>(null) }
val mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
@@ -164,12 +163,12 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
games.isEmpty() -> EmptyLibrary(
avoid = words,
wall = if (owned.isEmpty() && featured.isEmpty()) null else { { CapsuleWall(emptyList(), owned = owned, featured = featured) } },
) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade(bottomWhenTall = true) } }
) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade() } }
games.size < WALL_MIN_GAMES -> CapsuleFan(games)
else -> CapsuleWall(games, owned = owned, featured = featured)
}
},
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade(bottomWhenTall = true) },
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
words = {
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
@@ -233,35 +232,19 @@ internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier
}
@Composable
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang(), bottomWhenTall: Boolean = false) {
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang()) {
val colors = MaterialTheme.colorScheme
BoxWithConstraints(modifier) {
if (bottomWhenTall && maxHeight > maxWidth) {
// The words sit at the bottom of a tall page, so the art stays clear above them and darkens only behind them.
Box(
Modifier.fillMaxSize().background(
Brush.verticalGradient(
0f to colors.background.copy(alpha = 0.12f),
0.5f to colors.background.copy(alpha = 0.18f),
0.72f to colors.background.copy(alpha = 0.72f),
1f to colors.background.copy(alpha = 0.94f),
),
),
)
} else {
Box(
Modifier.fillMaxSize().background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.86f),
0.34f to colors.background.copy(alpha = 0.6f),
0.68f to colors.background.copy(alpha = 0.14f),
1f to colors.background.copy(alpha = 0.04f),
),
),
)
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
}
}
Box(
modifier.background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.86f),
0.34f to colors.background.copy(alpha = 0.6f),
0.68f to colors.background.copy(alpha = 0.14f),
1f to colors.background.copy(alpha = 0.04f),
),
),
)
Box(modifier.background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
}
@Composable
@@ -404,45 +387,31 @@ private fun CapsuleFan(games: List<Library.SteamGame>) {
transition.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "float")
}
val still = Motion.scale == 0f
val landscape = listOf(
val slots = listOf(
FanSlot(0.54f, 0.14f, 0.62f, -9f),
FanSlot(0.70f, 0.24f, 0.56f, 5f),
FanSlot(0.40f, 0.30f, 0.50f, -17f),
)
// A tall page sizes the cards from its width, so they fit any aspect; heights are fractions of the width.
val portrait = listOf(
FanSlot(0.27f, 0.11f, 0.70f, -9f),
FanSlot(0.55f, 0.19f, 0.64f, 5f),
FanSlot(0.04f, 0.26f, 0.56f, -17f),
)
BoxWithConstraints(
Modifier.fillMaxSize().drawBehind {
drawRect(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.14f), Color.Transparent),
center = if (size.height > size.width) Offset(size.width * 0.55f, size.height * 0.28f) else Offset(size.width * 0.68f, size.height * 0.45f),
radius = if (size.height > size.width) size.width * 0.9f else size.height * 0.6f,
center = Offset(size.width * 0.68f, size.height * 0.45f), radius = size.height * 0.6f,
),
)
},
) {
val radius = with(density) { 14.dp.toPx() }
val tall = maxHeight > maxWidth
val slots = if (tall) portrait else landscape
for (i in games.indices.reversed()) {
val slot = slots[i]
val h = if (tall) maxWidth * slot.height else maxHeight * slot.height
val x = if (tall) {
// The lean and the float swing the corners out by about h/2 * sin(angle).
val swing = h * kotlin.math.sin(Math.toRadians(kotlin.math.abs(slot.lean) + 2.0)).toFloat() / 2f
(maxWidth * slot.x).coerceIn(swing, (maxWidth - h * 2f / 3f - swing).coerceAtLeast(swing))
} else maxWidth * slot.x
val h = maxHeight * slot.height
val v: State<Float> = floats[i]
val look = WallCapsule(artBrush(hueOf(games[i].name)), games[i].art)
val art = look.art?.let { rememberCapsuleArt(it, with(density) { Size((h * 2f / 3f).toPx(), h.toPx()) }, radius) }
Spacer(
Modifier
.offset(x = x, y = maxHeight * slot.y)
.offset(x = maxWidth * slot.x, y = maxHeight * slot.y)
.size(h * 2f / 3f, h)
.graphicsLayer {
val t = if (still) 0f else v.value
-4
View File
@@ -4376,10 +4376,6 @@
<string name="dev_ui_zoo_open">Open</string>
<string name="dev_ui_zoo_show">Show</string>
<string name="dev_ui_zoo_note">Previews change nothing real: nothing is installed, removed or signed out, and the menu\'s switches save nothing. A Library preview stays until you end it from its pill or restart.</string>
<string name="dev_preview_steam_home">Steam home</string>
<string name="dev_preview_steam_none">No games installed</string>
<string name="dev_preview_steam_few">3 games installed</string>
<string name="dev_preview_steam_many">12 games installed</string>
<string name="dev_preview_library">Library</string>
<string name="dev_preview_library_nothing_installed">Nothing installed</string>
<string name="dev_preview_library_signed_out">Signed out of every store</string>
@@ -1,50 +0,0 @@
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))
}
}
@@ -188,57 +188,4 @@ 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 })
}
}
@@ -5,7 +5,6 @@ import android.view.InputDevice
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputSurfaceElement
@@ -23,7 +22,6 @@ import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Robolectric
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@@ -92,22 +90,6 @@ class InputSurfaceEditorViewTest {
private fun InputSurfaceEditorView.centre(id: String) = rendered().first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height }
private fun editorCutoutMode(): Int {
val activity = Robolectric.buildActivity(android.app.Activity::class.java).setup().get()
val dialog = android.app.Dialog(activity)
dialog.window!!.prepareInputEditor()
return dialog.window!!.attributes.layoutInDisplayCutoutMode
}
@Test fun theEditorLaysOutIntoTheCutoutLikeTheSession() {
assertEquals(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS, editorCutoutMode())
}
@Config(sdk = [29])
@Test fun theEditorLaysOutIntoShortEdgeCutoutsOnOlderAndroid() {
assertEquals(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES, editorCutoutMode())
}
@Test fun editingStartsInTheDisplayedFrame() {
val view = view()
var started: Pair<List<InputSurfaceElement>, Float>? = null
-10
View File
@@ -474,13 +474,3 @@ 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.
@@ -1,106 +0,0 @@
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 )
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-f3a45b31
GAMESCOPE_SHA256=3908af87b2ee8a328e9780fc805c6a7bddd11d7405b9992d717b94e16c019313
GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d
GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02
@@ -2,9 +2,6 @@
#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>
@@ -155,43 +152,5 @@ 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,7 +1,6 @@
#!/usr/bin/python3
import base64
import ctypes
import json
import math
import re
@@ -20,7 +19,6 @@ 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
@@ -1240,17 +1238,7 @@ 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"))
@@ -565,7 +565,22 @@ def online_cores():
cores = parse_cores(f.read().strip())
except OSError:
cores = None
return cores or os.sched_getaffinity(0) | set(range(os.cpu_count() or 0))
return cores or allowed_cores() | set(range(os.cpu_count() or 0))
def allowed_cores(status="/proc/self/status"):
try:
with open(status) as f:
for line in f:
key, _, value = line.partition(":")
if key == "Cpus_allowed_list":
cores = parse_cores(value.strip())
if cores:
return cores
break
except OSError:
pass
return os.sched_getaffinity(0)
def game_cores(env):
@@ -634,11 +649,11 @@ def cpu_topology(env, command=()):
fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None
if not (picked or fastest):
return
online = online_cores()
try:
cores = sorted(os.sched_getaffinity(0))
cores = sorted(allowed_cores() & online)
except OSError:
return
online = online_cores()
if not cores or cores[-1] >= len(online):
return
picked = picked and not set(cores) >= online
@@ -14,16 +14,7 @@ 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
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; }
running() { pgrep -x vrserver >/dev/null 2>&1; }
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
quest_settings() {
backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json
@@ -49,19 +40,6 @@ 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"
@@ -72,7 +50,7 @@ unregister() {
}
idle() {
[ ! -f "$state/active" ] && ! running && ! alive vrstartup &&
[ ! -f "$state/active" ] && ! running && ! pgrep -x vrstartup >/dev/null 2>&1 &&
( flock -n 9 ) 9>"$state/start.lock"
}
@@ -83,7 +61,7 @@ stop() {
done
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
attempts=0
while alive 'vrserver|vrcompositor'; do
while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do
attempts=$((attempts + 1))
if [ "$attempts" = 10 ]; then
for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done
@@ -91,12 +69,8 @@ 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
@@ -107,11 +81,6 @@ 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)
@@ -153,7 +122,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 || alive vrstartup; }; then
if [ -f "$state/active" ] && { running || pgrep -x vrstartup >/dev/null 2>&1; }; then
echo "DroidDeck SteamVR is already running"
exit 0
fi
@@ -246,9 +215,8 @@ 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; steam_ui_priority 0 || :; }' EXIT
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
if [ -f "$cvp" ]; then
disabled=$cvp.droiddeck-disabled
@@ -4,14 +4,7 @@ import os
from pathlib import Path
import sys
# 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)]
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}
def read(path):
@@ -40,8 +33,6 @@ 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)
@@ -54,16 +45,12 @@ 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():
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)
saved_preferences(backup_path)
else:
section = settings.get('steamvr', {})
write(backup_path, {'section': 'steamvr' in settings,
'values': {key: saved_entry(section, key) for key in OVERRIDES}})
'values': {key: [key in section, section.get(key)] for key in OVERRIDES}})
settings.setdefault('steamvr', {}).update(OVERRIDES)
write(settings_path, settings)
elif operation == 'restore':
@@ -72,8 +59,6 @@ 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
+42
View File
@@ -1872,6 +1872,7 @@ class GameEnvironmentTest(unittest.TestCase):
for env, affinity, expected, proton in cases:
env["DROIDDECK_FASTEST_CORES"] = "0"
with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \
mock.patch.object(MODULE["allowed_cores"], "__defaults__", ("/missing/status",)), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
MODULE["cpu_topology"](env)
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
@@ -1986,6 +1987,7 @@ class GameEnvironmentTest(unittest.TestCase):
env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/3608888694")
with mock.patch.dict(MODULE["cpu_topology"].__globals__, {"online_cores": lambda: every}), \
mock.patch.dict(MODULE["fastest_first"].__globals__, {"core_speeds": lambda cores, speeds=speeds: speeds}), \
mock.patch.object(MODULE["allowed_cores"], "__defaults__", ("/missing/status",)), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
MODULE["cpu_topology"](env, command)
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
@@ -1995,6 +1997,46 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "1038250"}), "P")
self.assertEqual(MODULE["proton_cpu_limit"](command, {"SteamGameId": "618970"}), 4)
def test_windows_sees_the_same_cores_while_android_pauses_some(self):
os_mod = MODULE["os"]
kalama = {0: 411, 1: 411, 2: 411, 3: 869, 4: 869, 5: 869, 6: 869, 7: 1024}
every = set(range(8))
cases = [
({}, "0-7", {3, 4, 5, 6}, "8:7,3,4,5,6,0,1,2"),
({}, "0-7", {0, 1, 2, 3, 4, 5, 7}, "8:7,3,4,5,6,0,1,2"),
({}, "0-7", every, "8:7,3,4,5,6,0,1,2"),
({"DD_GAME_CPUS": "6,7"}, "6-7", {6}, "2:7,6"),
({"DROIDDECK_GAME_CORES": "3-7"}, "3-7", {3, 4, 5}, "5:7,3,4,5,6"),
({}, "0-9", {3, 4}, "8:7,3,4,5,6,0,1,2"),
({"DROIDDECK_FASTEST_CORES": "0"}, "0-7", {3, 4, 5, 6}, None),
({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}, "0-7", {3, 4, 5, 6}, None),
]
with tempfile.TemporaryDirectory() as tmp:
status = Path(tmp) / "status"
for env, allowed, active, expected in cases:
env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/1687950")
status.write_text("Name:\tpython3\nCpus_allowed:\tff\nCpus_allowed_list:\t%s\n" % allowed)
with mock.patch.dict(MODULE["cpu_topology"].__globals__, {"online_cores": lambda: every}), \
mock.patch.dict(MODULE["fastest_first"].__globals__, {"core_speeds": lambda cores: kalama}), \
mock.patch.object(MODULE["allowed_cores"], "__defaults__", (str(status),)), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=active, create=True):
MODULE["cpu_topology"](env, ["/missing/proton", "waitforexitandrun", "/game/P5R.exe"])
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, (env, allowed, active))
self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), expected, (env, allowed, active))
def test_allowed_cores_read_the_tasks_mask_before_the_active_one(self):
os_mod = MODULE["os"]
allowed = MODULE["allowed_cores"]
with tempfile.TemporaryDirectory() as tmp:
status = Path(tmp) / "status"
with mock.patch.object(os_mod, "sched_getaffinity", return_value={3, 4}, create=True):
status.write_text("Cpus_allowed_list:\t0-2,4,6-7\n")
self.assertEqual(allowed(str(status)), {0, 1, 2, 4, 6, 7})
for text in ("Name:\tpython3\n", "Cpus_allowed_list:\t\n", "Cpus_allowed_list:\tjunk\n"):
status.write_text(text)
self.assertEqual(allowed(str(status)), {3, 4}, text)
self.assertEqual(allowed(str(Path(tmp) / "missing")), {3, 4})
def test_core_speeds_read_capacity_then_top_clock(self):
with tempfile.TemporaryDirectory() as tmp:
for core, capacity, clock in ((0, "379", "2265600"), (1, None, "3302400")):
+1 -27
View File
@@ -108,8 +108,7 @@ 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,
'framesToThrottle': 0, 'powersaveFramesToThrottle': 0})
self.assertEqual(settings['steamvr'], {'enableLinuxVulkanAsync': True, 'motionSmoothing': False})
self.assertFalse(cvp.exists())
self.assertEqual(Path(str(cvp) + '.droiddeck-disabled').read_bytes(), b'frame-only backend')
@@ -173,31 +172,6 @@ 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'
@@ -1,141 +0,0 @@
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()
+23 -60
View File
@@ -530,9 +530,6 @@ 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) {}
@@ -1044,8 +1041,7 @@ 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, TrackingSystemName(xrMode_));
VRProperties()->SetStringProperty(c, Prop_ActualTrackingSystemName_String, "droiddeck");
VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_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"));
@@ -1382,8 +1378,7 @@ 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, TrackingSystemName(xrMode_));
VRProperties()->SetStringProperty(c, Prop_ActualTrackingSystemName_String, "droiddeck");
VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_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));
@@ -1452,22 +1447,6 @@ 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 = {};
@@ -1476,7 +1455,17 @@ public:
p.qRotation.w = 1;
DroidDeckXrTracking xr;
bool freshXr = xr_.Read(&xr) && XrTrackingFile::Fresh(xr);
if (freshXr || xrMode_) return XrHeadPose(xr, freshXr);
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;
}
p.vecPosition[1] = 1.6;
droiddeck_headpose hp;
bool ok = pose_.Read(&hp);
@@ -1591,44 +1580,19 @@ 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_) {
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());
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);
}
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));
VRDriverInput()->UpdateBooleanComponent(proximity_, fresh, 0);
std::this_thread::sleep_for(std::chrono::milliseconds(2));
continue;
}
droiddeck_headpose hp;
@@ -1771,7 +1735,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_SerialNumber_String).rfind("droiddeck-", 0) != 0) return true;
if (VRProperties()->GetStringProperty(c, Prop_TrackingSystemName_String) != "droiddeck") return true;
}
return false;
}
@@ -1806,7 +1770,6 @@ 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,11 +1,8 @@
#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>
@@ -22,38 +19,6 @@ 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; }
+2 -120
View File
@@ -294,12 +294,9 @@ 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
@@ -588,28 +585,9 @@ 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)
@@ -1405,100 +1383,6 @@ 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)
@@ -1561,8 +1445,7 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVr_GetInstanceProcAddr(
if (f) return f;
}
if (in) {
PFN_vkVoidFunction f = warp_hook(name);
if (!f) f = semaphore_hook(name);
PFN_vkVoidFunction f = semaphore_hook(name);
if (f && in->gipa(instance, name)) return f;
}
return in ? in->gipa(instance, name) : NULL;
@@ -1578,8 +1461,7 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVr_GetDeviceProcAddr(Vk
if (f) return f;
}
if (d) {
PFN_vkVoidFunction mine = warp_hook(name);
if (!mine) mine = semaphore_hook(name);
PFN_vkVoidFunction mine = semaphore_hook(name);
if (mine && d->gdpa(device, name)) return mine;
}
return d ? d->gdpa(device, name) : NULL;
+8 -69
View File
@@ -41,7 +41,6 @@ struct CaptureSlot {
bool rgbaInitialized{};
void *mapping{};
VkFence fence{};
uint64_t uses{};
bool busy{}, queued{};
DroidDeckXrFrameHeader header{};
~CaptureSlot() { Clear(); }
@@ -135,13 +134,9 @@ 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{};
@@ -163,47 +158,17 @@ 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);
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;
sendReady.wait(lock, [this] {
return stopping || std::any_of(slots.begin(), slots.end(), [](const auto &item) { return item.queued; });
});
slot = nullptr;
for (auto &item : slots) if (item.queued && (!slot || item.header.frame_id < slot->header.frame_id)) slot = &item;
if (!slot) continue;
if (!slot) return;
slot->queued = false;
}
auto &d = *device;
@@ -217,16 +182,10 @@ 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.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;
}
if (!gpuSender.Send(header, static_cast<uint32_t>(slot - slots.data()), flags)) result = VK_ERROR_DEVICE_LOST;
} 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",
@@ -236,7 +195,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;
}
if (!posted) slot->busy = false;
slot->busy = false;
}
}
bool Initialize(VkSwapchainKHR chain, VkQueue queue) {
@@ -252,7 +211,6 @@ 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;
@@ -278,11 +236,8 @@ struct Swapchain {
return result;
}
bool Header(DroidDeckXrFrameHeader &header) {
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);
DroidDeckXrTracking packet{};
if (!tracking.Read(&packet) || !XrTrackingFile::Fresh(packet)) return false;
header = {};
header.magic = DROIDDECK_XR_FRAME_MAGIC; header.version = DROIDDECK_XR_FRAME_VERSION;
header.width = extent.width; header.height = extent.height;
@@ -305,15 +260,6 @@ 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;
@@ -383,8 +329,6 @@ 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];
@@ -435,11 +379,6 @@ 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,7 +10,6 @@ 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,21 +111,6 @@ 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;
+1 -43
View File
@@ -2,7 +2,6 @@
#include "xr_tracking.h"
#include <cstring>
#include <cmath>
#include <dlfcn.h>
#include <mutex>
#include <string>
#include <fcntl.h>
@@ -39,16 +38,8 @@ 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() {
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);
timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now);
return (int64_t)now.tv_sec * 1000000000LL + now.tv_nsec;
}
static double PoseTimeOffset(int64_t predicted, int64_t now) {
@@ -75,36 +66,3 @@ 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;
};