Merge upstream PC input and dual-screen updates

This commit is contained in:
Delete228 committed 2026-11-05 00:00:34 +03:00
commit 68b0396dfe
819 files changed
+43953 -6186

No files matched your search

+53
View File
@@ -3,12 +3,21 @@
xmlns:tools="http://schemas.android.com/tools">
<queries>
<package android:name="cn.nubia.gamelauncher" />
<intent>
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
</intent>
<intent>
<action android:name="android.content.pm.action.CONFIRM_PERMISSIONS" />
</intent>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
</intent>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SECONDARY_HOME" />
</intent>
</queries>
<uses-permission android:name="android.permission.REORDER_TASKS" />
@@ -60,6 +69,19 @@
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
android:process=":rgb_diagnostic" />
<service android:name=".wallpaper.SteamWallService"
android:label="@string/steam_wall_label"
android:permission="android.permission.BIND_WALLPAPER"
android:exported="true">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data android:name="android.service.wallpaper" android:resource="@xml/steam_wall_wallpaper" />
</service>
<activity android:name=".wallpaper.WallpaperSettingsActivity"
android:label="@string/steam_wall_label"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:exported="true" />
<service android:name=".input.HomeButtonService"
android:label="@string/integration_shortcuts_service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
@@ -69,6 +91,20 @@
</intent-filter>
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
</service>
<service android:name=".session.BottomNotificationListener"
android:label="@string/bottom_notifications_listener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
android:process=":shortcuts_sync">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
android:permission="android.permission.DUMP"
@@ -99,6 +135,7 @@
android:exported="true"
android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
<layout android:defaultWidth="1024dp" android:defaultHeight="640dp" />
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
@@ -179,6 +216,13 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".sync.SyncthingWebActivity"
android:exported="false"
android:screenOrientation="sensorLandscape"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity
android:name=".files.FileManagerActivity"
android:exported="false"
@@ -278,6 +322,11 @@
android:name=".session.SessionService"
android:exported="false"
android:stopWithTask="false" />
<!-- The compositor's native state is one per process, so the bottom-screen desktop's compositor runs in its own. -->
<service
android:name=".wayland.BottomDesktopCompositorService"
android:process=":bottom_desktop"
android:exported="false" />
<service
android:name=".runtime.RuntimeInstallService"
android:exported="false" />
@@ -288,6 +337,10 @@
android:name=".stores.download.StoreDownloadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<service
android:name=".sync.SyncthingService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.logs"
+2 -2
View File
@@ -8,7 +8,6 @@ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,max-page-size=16384
add_subdirectory(adrenotools)
# DXVK's DXBC->SPIR-V translator is zlib licensed (vendored under thirdparty/dxbc).
add_subdirectory(thirdparty/dxbc)
set(DDFG_UPSTREAM "v0.3.0")
@@ -37,13 +36,14 @@ target_link_libraries(sdnative log)
add_library(deviceinfo SHARED deviceinfo/vkinfo.c)
target_link_libraries(deviceinfo dl)
add_library(gpuclock SHARED gpuclock/kgsl_clock.c gpuclock/kgsl_busy.c)
add_library(termux SHARED termux/termux.c)
add_library(ddvenc SHARED venc/venc_server.cpp)
target_compile_features(ddvenc PRIVATE cxx_std_17)
target_link_libraries(ddvenc mediandk log)
# The optional proprietary SDK is supplied locally; its headers/libraries are not vendored.
if(DROIDDECK_VITURE_SDK_DIR)
add_library(droiddeck_viture SHARED viture/sdk_bridge.cpp)
target_compile_features(droiddeck_viture PRIVATE cxx_std_17)
+2
View File
@@ -62,6 +62,7 @@ Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz
LINE("driver_version=%u.%u.%u\n", p.driverVersion >> 22, (p.driverVersion >> 12) & 0x3ff, p.driverVersion & 0xfff);
LINE("vendor_id=0x%04x\ndevice_id=0x%08x\n", p.vendorID, p.deviceID);
LINE("max_image_2d=%u\n", p.limits.maxImageDimension2D);
LINE("max_push_constants=%u\n", p.limits.maxPushConstantsSize);
uint32_t extCount = 0;
if (vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, NULL);
@@ -91,6 +92,7 @@ Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz
vkGetPhysicalDeviceFeatures(device, &f);
LINE("geometry_shader=%s\ntessellation_shader=%s\ntexture_bc=%s\n",
f.geometryShader ? "yes" : "no", f.tessellationShader ? "yes" : "no", f.textureCompressionBC ? "yes" : "no");
LINE("shader_int64=%s\n", f.shaderInt64 ? "yes" : "no");
}
if (vkGetPhysicalDeviceMemoryProperties) {
VkPhysicalDeviceMemoryProperties m;
-7
View File
@@ -78,7 +78,6 @@ static constexpr uint8_t GAMEPAD_AXIS_COUNT = 8;
static constexpr uint8_t GAMEPAD_BUTTON_COUNT = 11;
static constexpr uint32_t FAKE_INPUT_RING_MAGIC = 0x46494252;
static constexpr uint32_t FAKE_INPUT_RING_VERSION = 2;
// Rings hold the 64-bit input_event layout that the arm64 writers use; 32-bit guests convert on read.
struct RingEvent {
int64_t sec;
int64_t usec;
@@ -391,7 +390,6 @@ send_vibration(int strong, int weak, uint16_t duration_ms, uint16_t slot) {
syscall(SYS_close, sock);
}
// Must match RumbleComponent.HOLD_MS: play until the slot's next effect or stop.
static constexpr uint16_t RUMBLE_HOLD_MS = 0xffff;
__attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff_effect &effect, uint16_t slot) {
@@ -1243,7 +1241,6 @@ static constexpr int TRITON_REPORT_ID_BYTES = 1;
static constexpr int TRITON_STATE_BYTES = 45;
static constexpr int TRITON_REPORT_INTERVAL_US = 4000;
static constexpr int TRITON_FEATURE_TIMEOUT_MS = 500;
// The app clears output_length once it has taken a report; a writer waits this long for that before overwriting.
static constexpr int TRITON_OUTPUT_TIMEOUT_MS = 50;
static constexpr const char *TRITON_NAME = "Steam Controller";
static constexpr const char *TRITON_SERIAL = "DROIDDECKSC01";
@@ -2673,9 +2670,6 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
static constexpr uint32_t TRITON_HWID = 72;
static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3;
// Steam compares the controller's firmware with TRITON_FW_TS in its bundled hardwareupdater.cfg (and blocks
// with a required update below MUST_UPDATE_TRITON_FW_TS), so the emulated pad reports at least the build
// Steam ships.
static uint32_t triton_fw_timestamp() {
static const uint32_t timestamp = [] {
std::vector<std::string> roots;
@@ -3683,7 +3677,6 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
Logger::log("Hooking ioctl EVIOCGRAB for event %s\n", event);
return 0;
} else if (type == 0x6A && !strncmp(event, "event", 5)) {
// Older SDL2 builds treat any JSIOCGNAME answer as a joydev node and skip EVIOCGID, then drop the pad as 0000:0000.
Logger::log("Rejecting joydev ioctl %d for event %s\n", number, event);
guard.unlock();
errno = EINVAL;
@@ -267,8 +267,6 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_);
}
// Every generation of one real frame is recorded into the same command buffer, so the flow
// between prev and curr is computed once and each generation gets its own synth UBO and set.
if (reuseFlow && !g_scratch.flowReady) return;
if (!reuseFlow) {
bool gmEngaged = updateGlobalMotion(gmSlot, extent_);
+1 -2
View File
@@ -1,5 +1,4 @@
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS).
// Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS). Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
#include "lsfg_dll.h"
#include "lsfg_dxbc.h"
+1 -2
View File
@@ -1,5 +1,4 @@
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS).
// Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS). Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
#pragma once
@@ -1,5 +1,4 @@
#pragma once
// DXVK's dxbc subset is zlib licensed; vendored under cpp/thirdparty/dxbc.
#include <cstdint>
#include <vector>
+154
View File
@@ -0,0 +1,154 @@
// Whole-GPU busy share without root on Adreno (KGSL) devices whose kgsl sysfs is blocked for apps: a thread
// samples the memstore timestamps (kgsl_busy.h) once a millisecond while running. Ringbuffer entries are used where
// the kernel writes them; on hardware-scheduled kernels, which leave them at 0, the contexts' own entries are used.
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
#include "../adrenotools/src/hook/kgsl.h"
#include "kgsl_busy.h"
#define SAMPLE_NS 1000000L
// Context mode: how many samples between scans of the context entries.
#define SCAN_EVERY 200
enum { MODE_RINGBUFFER = 1, MODE_CONTEXTS = 2 };
struct reader {
int fd;
void *map;
size_t bytes;
int first;
int mode;
uint32_t last[KGSL_BUSY_SLOTS];
uint32_t *seen, *ctx_last;
int live[KGSL_BUSY_MAX_LIVE];
int live_count;
pthread_mutex_t lock;
pthread_t thread;
int thread_on;
atomic_int run;
atomic_uint_fast64_t busy, samples, moves;
};
static void *sample_loop(void *arg) {
struct reader *r = arg;
const struct timespec gap = {0, SAMPLE_NS};
int until_scan = 0;
while (atomic_load(&r->run)) {
int moved = 0, busy;
if (r->mode == MODE_CONTEXTS) {
if (until_scan-- <= 0) {
r->live_count = kgsl_busy_scan_contexts(r->map, r->first, r->seen, r->live, KGSL_BUSY_MAX_LIVE);
until_scan = SCAN_EVERY;
}
busy = kgsl_busy_sample_contexts(r->map, r->live, r->live_count, r->ctx_last, &moved);
} else {
busy = kgsl_busy_sample(r->map, r->first, r->last, &moved);
}
if (busy) atomic_fetch_add(&r->busy, 1);
if (moved) atomic_fetch_add(&r->moves, 1);
atomic_fetch_add(&r->samples, 1);
nanosleep(&gap, NULL);
}
return NULL;
}
static void reader_run(struct reader *r, int on) {
pthread_mutex_lock(&r->lock);
if (on && !r->thread_on) {
atomic_store(&r->run, 1);
if (pthread_create(&r->thread, NULL, sample_loop, r) == 0) r->thread_on = 1;
else atomic_store(&r->run, 0);
} else if (!on && r->thread_on) {
atomic_store(&r->run, 0);
pthread_join(r->thread, NULL);
r->thread_on = 0;
}
pthread_mutex_unlock(&r->lock);
}
static void reader_close(struct reader *r) {
if (!r) return;
reader_run(r, 0);
if (r->map && r->map != MAP_FAILED) munmap(r->map, r->bytes);
if (r->fd >= 0) close(r->fd);
free(r->seen);
free(r->ctx_last);
pthread_mutex_destroy(&r->lock);
free(r);
}
// Returns 0 or a negative errno; *out is set on success.
static int reader_open(struct reader **out) {
struct reader *r = calloc(1, sizeof(*r));
if (!r) return -ENOMEM;
pthread_mutex_init(&r->lock, NULL);
r->fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
if (r->fd < 0) { int e = -errno; reader_close(r); return e; }
struct kgsl_shadowprop shadow;
memset(&shadow, 0, sizeof(shadow));
struct kgsl_device_getproperty prop = {.type = KGSL_PROP_DEVICE_SHADOW, .value = &shadow, .sizebytes = sizeof(shadow)};
if (ioctl(r->fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &prop)) { int e = -errno; reader_close(r); return e; }
r->bytes = shadow.size;
r->first = kgsl_busy_first_slot(shadow.size);
if (r->first < 0) { reader_close(r); return -ERANGE; }
r->map = mmap(NULL, r->bytes, PROT_READ, MAP_SHARED, r->fd, (off_t)shadow.gpuaddr);
if (r->map == MAP_FAILED) { int e = -errno; reader_close(r); return e; }
int moved = 0, started = 0;
kgsl_busy_sample(r->map, r->first, r->last, &moved);
for (int i = 0; i < KGSL_BUSY_SLOTS; i++) started |= r->last[i] != 0;
if (started) {
r->mode = MODE_RINGBUFFER;
} else {
r->seen = calloc((size_t)r->first, sizeof(uint32_t));
r->ctx_last = calloc((size_t)r->first, sizeof(uint32_t));
if (!r->seen || !r->ctx_last) { reader_close(r); return -ENOMEM; }
r->live_count = kgsl_busy_scan_contexts(r->map, r->first, r->seen, r->live, KGSL_BUSY_MAX_LIVE);
kgsl_busy_sample_contexts(r->map, r->live, r->live_count, r->ctx_last, &moved);
r->mode = MODE_CONTEXTS;
}
*out = r;
return 0;
}
#ifndef KGSL_BUSY_NO_JNI
#include <jni.h>
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeOpen(JNIEnv *env, jclass cls, jintArray error) {
struct reader *r = NULL;
int e = reader_open(&r);
if (e && error && (*env)->GetArrayLength(env, error) > 0) {
jint v = e;
(*env)->SetIntArrayRegion(env, error, 0, 1, &v);
}
return e ? 0 : (jlong)(intptr_t)r;
}
JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeMode(JNIEnv *env, jclass cls, jlong handle) {
return handle ? ((struct reader *)(intptr_t)handle)->mode : 0;
}
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeRun(JNIEnv *env, jclass cls, jlong handle, jboolean on) {
if (handle) reader_run((struct reader *)(intptr_t)handle, on ? 1 : 0);
}
JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeRead(JNIEnv *env, jclass cls, jlong handle, jlongArray out) {
if (!handle || !out || (*env)->GetArrayLength(env, out) < 3) return JNI_FALSE;
struct reader *r = (struct reader *)(intptr_t)handle;
jlong v[3] = {(jlong)atomic_load(&r->busy), (jlong)atomic_load(&r->samples), (jlong)atomic_load(&r->moves)};
(*env)->SetLongArrayRegion(env, out, 0, 3, v);
return JNI_TRUE;
}
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeClose(JNIEnv *env, jclass cls, jlong handle) {
reader_close((struct reader *)(intptr_t)handle);
}
#endif
+77
View File
@@ -0,0 +1,77 @@
#ifndef DROIDDECK_KGSL_BUSY_H
#define DROIDDECK_KGSL_BUSY_H
// kgsl lets any client map its memstore read-only (KGSL_PROP_DEVICE_SHADOW). The CP writes a ringbuffer's
// start-of-pipe timestamp there before each submission's command buffers and its end-of-pipe timestamp after them
// (adreno_gen7_ringbuffer.c gen7_ringbuffer_addcmds), so start != end means that ringbuffer has work on the GPU.
// Ringbuffer entries start at KGSL_MEMSTORE_MAX: entries - 2 - 4 levels, or entries - 1 - 4 on kernels without the
// LPAC slot. Entries - 6 .. entries - 2 cover both; a context entry in that range follows the same start/end rule.
#include <stddef.h>
#include <stdint.h>
#define KGSL_BUSY_ENTRY_WORDS 10
#define KGSL_BUSY_SOP 0
#define KGSL_BUSY_EOP 2
#define KGSL_BUSY_SLOTS 5
static inline int kgsl_busy_first_slot(size_t bytes) {
size_t entries = bytes / (KGSL_BUSY_ENTRY_WORDS * sizeof(uint32_t));
return entries < 8 ? -1 : (int)(entries - 6);
}
// 1 when a watched slot has a submission between its start and end timestamps. *moved is set when a start
// timestamp differs from last[], which then holds the new ones.
static inline int kgsl_busy_sample(const volatile uint32_t *memstore, int first, uint32_t last[KGSL_BUSY_SLOTS], int *moved) {
int busy = 0;
for (int i = 0; i < KGSL_BUSY_SLOTS; i++) {
const volatile uint32_t *entry = memstore + (size_t)(first + i) * KGSL_BUSY_ENTRY_WORDS;
uint32_t sop = entry[KGSL_BUSY_SOP], eop = entry[KGSL_BUSY_EOP];
if (sop != eop) busy = 1;
if (sop != last[i]) {
*moved = 1;
last[i] = sop;
}
}
return busy;
}
// Hardware-scheduled kernels (every gen8 GPU and some gen7 ones: .gpudev = *_hwsched_gpudev in adreno-gpulist.h)
// leave the ringbuffer entries at 0. The GMU firmware writes each context's own entry instead
// (gen8_hwsched_hfi.c send_context_pointers). Context ids run from 1 below the ringbuffer entries, lowest free first,
// and kgsl zeroes an entry when its context is created or destroyed.
#define KGSL_BUSY_MAX_LIVE 64
// Collects the contexts to sample: every entry below first with a non-zero start stamp (kgsl zeroes an entry when its
// context is created or destroyed). Entries whose start stamp changed since the previous scan (seen[]) or that are
// busy now come first, so the max_live cap only drops idle ones. Returns how many ids went into live[].
static inline int kgsl_busy_scan_contexts(const volatile uint32_t *memstore, int first, uint32_t *seen, int *live, int max_live) {
int n = 0, idle = 0;
int idle_ids[KGSL_BUSY_MAX_LIVE];
for (int id = 1; id < first; id++) {
const volatile uint32_t *entry = memstore + (size_t)id * KGSL_BUSY_ENTRY_WORDS;
uint32_t sop = entry[KGSL_BUSY_SOP], eop = entry[KGSL_BUSY_EOP];
int changed = sop != seen[id];
seen[id] = sop;
if ((changed || sop != eop) && n < max_live) live[n++] = id;
else if (sop != 0 && idle < KGSL_BUSY_MAX_LIVE) idle_ids[idle++] = id;
}
for (int i = 0; i < idle && n < max_live; i++) live[n++] = idle_ids[i];
return n;
}
// 1 when a live context has a submission between its start and end timestamps. *moved is set when a start
// timestamp differs from last[] (indexed by context id), which then holds the new ones.
static inline int kgsl_busy_sample_contexts(const volatile uint32_t *memstore, const int *live, int count, uint32_t *last, int *moved) {
int busy = 0;
for (int i = 0; i < count; i++) {
const volatile uint32_t *entry = memstore + (size_t)live[i] * KGSL_BUSY_ENTRY_WORDS;
uint32_t sop = entry[KGSL_BUSY_SOP], eop = entry[KGSL_BUSY_EOP];
if (sop != eop) busy = 1;
if (sop != last[live[i]]) {
*moved = 1;
last[live[i]] = sop;
}
}
return busy;
}
#endif
+159
View File
@@ -0,0 +1,159 @@
// GPU clock without root on Adreno (KGSL) devices whose kgsl sysfs is blocked for apps.
//
// kgsl lets any app reserve a performance counter (IOCTL_KGSL_PERFCOUNTER_GET) but refuses to read it back while
// /sys/class/kgsl/kgsl-3d0/perfcounter is 0, and clears the counters whenever the GPU switches to another process.
// So the counter is read by the GPU itself: a small command buffer copies CP_ALWAYS_ON_COUNTER (19.2 MHz) and the
// RBBM ALWAYS_COUNT counter (GPU core cycles) to memory, runs a block of NOP packets, and copies both again.
// clock = cycles / always-on ticks * 19.2 MHz. Both reads sit in one command buffer, so a counter clear between
// them only happens if the buffer is preempted; such samples fail the range checks and are dropped.
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include "../adrenotools/src/hook/kgsl.h"
#include "kgsl_layout.h"
#define CP_TYPE7_PKT 0x70000000u
#define CP_NOP 0x10u
#define CP_REG_TO_MEM 0x3eu
#define XO_HZ 19200000.0
#define NOP_DWORDS 0x3fffu
#define NOP_BLOCKS 4
struct sampler {
int fd;
const struct kgsl_layout *layout;
unsigned context;
unsigned counter_reg;
struct kgsl_gpumem_alloc_id ib, out;
uint32_t *ib_map;
volatile uint64_t *out_map;
size_t ib_bytes;
};
static unsigned odd_parity(unsigned v) {
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
v &= 0xf;
return (~0x6996u >> v) & 1u;
}
static uint32_t pkt7(unsigned op, unsigned count) {
return CP_TYPE7_PKT | count | odd_parity(count) << 15 | (op & 0x7f) << 16 | odd_parity(op) << 23;
}
static void sampler_close(struct sampler *s) {
if (!s) return;
if (s->fd >= 0) {
if (s->ib_map && s->ib_map != MAP_FAILED) munmap(s->ib_map, s->ib.mmapsize);
if (s->out_map && s->out_map != MAP_FAILED) munmap((void *)s->out_map, s->out.mmapsize);
if (s->ib.id) { struct kgsl_gpumem_free_id f = {.id = s->ib.id}; ioctl(s->fd, IOCTL_KGSL_GPUMEM_FREE_ID, &f); }
if (s->out.id) { struct kgsl_gpumem_free_id f = {.id = s->out.id}; ioctl(s->fd, IOCTL_KGSL_GPUMEM_FREE_ID, &f); }
if (s->context) { struct kgsl_drawctxt_destroy d = {.drawctxt_id = s->context}; ioctl(s->fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &d); }
if (s->counter_reg) {
struct kgsl_perfcounter_put p = {.groupid = KGSL_PERFCOUNTER_GROUP_RBBM, .countable = s->layout->cycles};
ioctl(s->fd, IOCTL_KGSL_PERFCOUNTER_PUT, &p);
}
close(s->fd);
}
free(s);
}
static void emit_reads(struct sampler *s, size_t *n, unsigned pass) {
const unsigned regs[2] = {s->layout->always_on, s->counter_reg};
for (unsigned k = 0; k < 2; k++) {
uint64_t dst = s->out.gpuaddr + (uint64_t)(pass * 2 + k) * sizeof(uint64_t);
s->ib_map[(*n)++] = pkt7(CP_REG_TO_MEM, 3);
s->ib_map[(*n)++] = regs[k] | (2u << 18) | (1u << 30); // two dwords, 64-bit read
s->ib_map[(*n)++] = (uint32_t)dst;
s->ib_map[(*n)++] = (uint32_t)(dst >> 32);
}
}
// Returns 0 or a negative errno; *out is set on success.
static int sampler_open(struct sampler **out) {
struct sampler *s = calloc(1, sizeof(*s));
if (!s) return -ENOMEM;
s->fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
if (s->fd < 0) { int e = -errno; s->fd = -1; sampler_close(s); return e; }
struct kgsl_devinfo info;
memset(&info, 0, sizeof(info));
struct kgsl_device_getproperty prop = {.type = KGSL_PROP_DEVICE_INFO, .value = &info, .sizebytes = sizeof(info)};
if (ioctl(s->fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &prop)) { int e = -errno; sampler_close(s); return e; }
s->layout = kgsl_layout_for(info.chip_id);
if (!s->layout) { sampler_close(s); return -ENOTSUP; }
struct kgsl_perfcounter_get get = {.groupid = KGSL_PERFCOUNTER_GROUP_RBBM, .countable = s->layout->cycles};
if (ioctl(s->fd, IOCTL_KGSL_PERFCOUNTER_GET, &get)) { int e = -errno; sampler_close(s); return e; }
s->counter_reg = get.offset;
if (!get.offset || get.offset > s->layout->readable_last) { sampler_close(s); return -ERANGE; }
struct kgsl_drawctxt_create ctx = {.flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE};
if (ioctl(s->fd, IOCTL_KGSL_DRAWCTXT_CREATE, &ctx)) { int e = -errno; sampler_close(s); return e; }
s->context = ctx.drawctxt_id;
s->ib_bytes = (16 + NOP_BLOCKS * (NOP_DWORDS + 1)) * sizeof(uint32_t);
s->ib.size = (s->ib_bytes + 4095) & ~(size_t)4095;
s->out.size = 4096;
if (ioctl(s->fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &s->ib)) { int e = -errno; s->ib.id = 0; sampler_close(s); return e; }
if (ioctl(s->fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &s->out)) { int e = -errno; s->out.id = 0; sampler_close(s); return e; }
s->ib_map = mmap(NULL, s->ib.mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, (off_t)s->ib.id << 12);
s->out_map = mmap(NULL, s->out.mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, (off_t)s->out.id << 12);
if (s->ib_map == MAP_FAILED || s->out_map == MAP_FAILED) { int e = -errno; sampler_close(s); return e; }
size_t n = 0;
emit_reads(s, &n, 0);
for (unsigned b = 0; b < NOP_BLOCKS; b++) {
s->ib_map[n++] = pkt7(CP_NOP, NOP_DWORDS);
memset(&s->ib_map[n], 0, NOP_DWORDS * sizeof(uint32_t));
n += NOP_DWORDS;
}
emit_reads(s, &n, 1);
s->ib_bytes = n * sizeof(uint32_t);
*out = s;
return 0;
}
// MHz, or a negative value: -errno from kgsl, or -1000 for a sample that failed the range checks.
static int sampler_mhz(struct sampler *s) {
for (int i = 0; i < 4; i++) s->out_map[i] = 0;
struct kgsl_command_object cmd = {.gpuaddr = s->ib.gpuaddr, .size = s->ib_bytes, .flags = KGSL_CMDLIST_IB};
struct kgsl_gpu_command submit = {
.cmdlist = (uint64_t)(uintptr_t)&cmd, .cmdsize = sizeof(cmd), .numcmds = 1, .context_id = s->context,
};
if (ioctl(s->fd, IOCTL_KGSL_GPU_COMMAND, &submit)) return -errno;
struct kgsl_device_waittimestamp_ctxtid wait = {.context_id = s->context, .timestamp = submit.timestamp, .timeout = 250};
if (ioctl(s->fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait)) return -errno;
uint64_t xo0 = s->out_map[0], cyc0 = s->out_map[1], xo1 = s->out_map[2], cyc1 = s->out_map[3];
if (xo1 <= xo0 || cyc1 <= cyc0) return -1000;
uint64_t xo = xo1 - xo0, cycles = cyc1 - cyc0;
// 5 us .. 50 ms of always-on time, and a clock between 50 MHz and 2 GHz.
if (xo < 96 || xo > 960000) return -1000;
double mhz = (double)cycles / (double)xo * XO_HZ / 1e6;
if (mhz < 50 || mhz > 2000) return -1000;
return (int)(mhz + 0.5);
}
#ifndef KGSL_CLOCK_NO_JNI
#include <jni.h>
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeOpen(JNIEnv *env, jclass cls, jintArray error) {
struct sampler *s = NULL;
int r = sampler_open(&s);
if (r && error && (*env)->GetArrayLength(env, error) > 0) {
jint e = r;
(*env)->SetIntArrayRegion(env, error, 0, 1, &e);
}
return r ? 0 : (jlong)(intptr_t)s;
}
JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeSample(JNIEnv *env, jclass cls, jlong handle) {
return handle ? sampler_mhz((struct sampler *)(intptr_t)handle) : -EBADF;
}
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeClose(JNIEnv *env, jclass cls, jlong handle) {
sampler_close((struct sampler *)(intptr_t)handle);
}
#endif
+27
View File
@@ -0,0 +1,27 @@
#ifndef DROIDDECK_KGSL_LAYOUT_H
#define DROIDDECK_KGSL_LAYOUT_H
#include <stddef.h>
// Register layout per GPU generation. A counter kgsl places outside the range the kernel's CP protection lets
// command buffers read (adreno-gpulist.h *_protected_regs) is not read.
struct kgsl_layout {
unsigned always_on; // CP_ALWAYS_ON_COUNTER
unsigned cycles; // RBBM countable that counts GPU cycles
unsigned readable_last; // last register of the readable range starting at 0
};
// A6xx/A7xx: CP_ALWAYS_ON_COUNTER 0x980, RBBM countable 0 = ALWAYS_COUNT, 0x000-0x4ff readable (gen7 list).
static const struct kgsl_layout KGSL_LAYOUT_A7XX = {0x980u, 0u, 0x4ffu};
// A8xx: CP_ALWAYS_ON_COUNTER 0x8e7 (gen8_reg.h), RBBM countable 1 = US_ALWAYS_COUNT (0 is NEVER_COUNT, Mesa
// a8xx_perfcntrs.xml), 0x000-0x3a3 readable (gen8_0_0_protected_regs).
static const struct kgsl_layout KGSL_LAYOUT_A8XX = {0x8e7u, 1u, 0x3a3u};
// The KGSL chip id's top byte: 0x44 on every A8xx (Adreno 810/829/830/840, Mesa freedreno_devices.py),
// 0x43 or the generation number on A6xx/A7xx. Later generations are not known, so nothing is read there.
static inline const struct kgsl_layout *kgsl_layout_for(unsigned chip_id) {
unsigned core = chip_id >> 24;
if (core == 0x44u) return &KGSL_LAYOUT_A8XX;
if (core > 0x44u) return NULL;
return &KGSL_LAYOUT_A7XX;
}
#endif
-2
View File
@@ -76,7 +76,6 @@ public:
}
lastFrame_ = frame.header.frame_id;
if (state == XrGpuFrameState::Stale) {
// No GPU read was submitted, so the producer can safely reclaim a dropped frame.
dropped_++;
if (!xr_gpu_send(peer_, &frame.header.frame_id, sizeof(frame.header.frame_id))) Disconnect();
return false;
@@ -88,7 +87,6 @@ public:
glBindImageTexture(0, raw_, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);
glDispatchCompute((width_ + 7) / 8, (height_ + 7) / 8, 1);
glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
// The producer may overwrite this slot only after the native GPU has finished reading it.
glFinish();
if (glGetError() != GL_NO_ERROR) { rejected_++; Disconnect(); return false; }
if (!xr_gpu_send(peer_, &frame.header.frame_id, sizeof(frame.header.frame_id))) Disconnect();
-5
View File
@@ -3,10 +3,6 @@
#include <stdint.h>
/* SOCK_SEQPACKET between the guest's Remote Play hooks and the app: the emulated /dev/video-enc0 and
* MediaCodec encoder, and remote touches. A config carries the buffer memfds (inputs first) as SCM_RIGHTS;
* every frame gets one reply, touches get none. */
#define VENC_MAX_BUFFERS 16
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 };
@@ -45,7 +41,6 @@ struct venc_bitrate {
uint32_t bitrate;
};
/* Remote Play's touch-as-mouse turned back into a touch; x and y are fractions of the screen in 1/65535. */
struct venc_touch {
uint32_t type;
uint32_t action;
+3 -3
View File
@@ -33,8 +33,8 @@ struct Mapping {
constexpr int32_t kColorFormatYuv420SemiPlanar = 21;
constexpr uint32_t kBufferFlagKeyFrame = 1;
constexpr uint32_t kBufferFlagCodecConfig = 2;
constexpr int kTouchWidth = 1920, kTouchHeight = 1080; // InputSpace.kt
constexpr int kRemoteTouchId = 31; // the compositor's last touch slot (MAX_TOUCH_POINTS 32)
constexpr int kTouchWidth = 1920, kTouchHeight = 1080;
constexpr int kRemoteTouchId = 31;
int32_t avc_profile(int32_t v4l2) {
switch (v4l2) {
@@ -549,7 +549,7 @@ void serve(int listener) {
}
}
} // namespace
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_session_VideoEncodeBridge_nativeStart(JNIEnv *env, jobject, jstring jpath) {
+11 -13
View File
@@ -1,20 +1,18 @@
#pragma once
// Our controller uses the standard display-mode vocabulary, even for Beast.
// Native mode reuses some numbers with different meanings; never pass them through.
namespace droiddeck::viture {
constexpr int to_native_mode(int standard) {
switch (standard) {
case 0x31: return 0x31; // 1080p 60
case 0x33: return 0x32; // 1080p 90
case 0x34: return 0x33; // 1080p 120
case 0x32: return 0x37; // 1080p SBS 60
case 0x35: return 0x38; // 1080p SBS 90
case 0x41: return 0x34; // 1200p 60
case 0x43: return 0x35; // 1200p 90
case 0x44: return 0x36; // 1200p 120
case 0x42: return 0x3a; // 1200p SBS 60
case 0x45: return 0x3b; // 1200p SBS 90
case 0x31: return 0x31;
case 0x33: return 0x32;
case 0x34: return 0x33;
case 0x32: return 0x37;
case 0x35: return 0x38;
case 0x41: return 0x34;
case 0x43: return 0x35;
case 0x44: return 0x36;
case 0x42: return 0x3a;
case 0x45: return 0x3b;
default: return -4;
}
}
@@ -30,7 +28,7 @@ constexpr int from_native_mode(int native) {
case 0x36: return 0x44;
case 0x3a: return 0x42;
case 0x3b: return 0x45;
default: return -4; // Ultrawide is not stereo.
default: return -4;
}
}
}
-1
View File
@@ -5,7 +5,6 @@
inline std::size_t mjpeg_payload_size(const uint8_t* bytes, std::size_t size) {
if (!bytes || size < 4 || size > 4*1024*1024 || bytes[0] != 0xff || bytes[1] != 0xd8) return 0;
std::size_t end = size;
// Luma Ultra UVC frames can pad the JPEG to an eight-byte boundary with zeros.
while (end > 4 && size-end < 7 && bytes[end-1] == 0) --end;
return bytes[end-2] == 0xff && bytes[end-1] == 0xd9 ? end : 0;
}
-4
View File
@@ -30,7 +30,6 @@
#include "stereo_frame_gate.h"
namespace {
// SDK callbacks have no user-data parameter. Only one provider may exist at a time.
std::mutex api_mutex;
std::mutex pose_mutex;
std::array<float, 4> latest_pose{};
@@ -64,7 +63,6 @@ void on_pose(float* data, uint64_t) {
std::lock_guard<std::mutex> lock(pose_mutex);
if (!accepting_pose) return;
std::copy_n(data + 3, 4, latest_pose.begin());
// SDK device ticks are not Android's elapsed-realtime clock.
latest_time = now_ns();
}
@@ -234,8 +232,6 @@ int set_display(Session& s, int standard) {
if (mode == 0) {
int rc = xr_device_provider_set_display_mode(s.device, standard);
if (rc != VITURE_GLASSES_ERROR_NOT_SUPPORTED) return rc;
// Older Beast firmware exposes fewer bypass modes. Fall back to its
// separate native table only when the SDK explicitly rejects the mode.
}
const int native = droiddeck::viture::to_native_mode(standard);
if (native < 0) return native;
@@ -18,6 +18,7 @@ add_library(droiddeckwayland SHARED
src/wl_color_mgmt.c
src/hdr_compose.c
src/blend_pass.c
src/gpu_busy.c
generated/color-management-v1-protocol.c
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
@@ -43,6 +44,7 @@ target_include_directories(droiddeckwayland PRIVATE
prebuilt/include
src
${CMAKE_CURRENT_SOURCE_DIR}/../shaders
${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/gpuload/src
)
set(DROIDDECK_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg)
+7 -1
View File
@@ -34,7 +34,6 @@ void cardboard_clamp(struct cardboard_params *p) {
p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f);
p->k1 = clampf(p->k1, -1.0f, 2.0f);
p->k2 = clampf(p->k2, -1.0f, 2.0f);
// Optical vertical FOV on supported glasses can be as low as ~22 degrees.
p->fov_deg = clampf(p->fov_deg, 20.0f, 140.0f);
p->lens_inset = clampf(p->lens_inset, -0.25f, 0.25f);
p->chroma = clampf(p->chroma, 0.0f, 0.05f);
@@ -186,6 +185,13 @@ int vkp_cardboard_active(void) {
return on;
}
int vkp_cardboard_source(void) {
pthread_mutex_lock(&g_lock);
const int source = g_set.enabled ? g_set.source : CARDBOARD_SOURCE_SCREEN;
pthread_mutex_unlock(&g_lock);
return source;
}
int vkp_cardboard_pose_changed(void) {
if (!g_changed) return 0;
g_changed = 0;
@@ -27,6 +27,7 @@ void vkp_cardboard_set_render_height(int height);
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
int vkp_cardboard_active(void);
int vkp_cardboard_source(void);
int vkp_cardboard_pose_changed(void);
void vkp_cardboard_begin_frame(void);
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h);
@@ -1,4 +1,3 @@
// 1115.1.0
#pragma once
const uint32_t cardboard_frag_code[] = {
0x07230203,0x00010000,0x0008000b,0x000001ba,0x00000000,0x00020011,0x00000001,0x0006000b,
+173 -37
View File
@@ -289,7 +289,6 @@ static struct wl_event_source *g_fallback_timer;
static int g_fallback_armed;
volatile int g_fps_limit;
/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */
volatile int g_release_unpaced;
volatile int g_hide_shell;
@@ -446,6 +445,12 @@ static int g_cursor_w, g_cursor_h;
static int g_cursor_hidden = 1;
static int g_cursor_serial;
#define CURSOR_MAX_DRAWS 2
static struct vkp_image *g_cursor_img;
static int g_cursor_img_w, g_cursor_img_h, g_cursor_img_serial = -1;
static atomic_int g_cursor_composite;
static atomic_int g_cursor_composite_want;
static void cursor_publish_shown(void) {
pthread_mutex_lock(&g_cursor_lock);
if (g_cursor_w > 0) { g_cursor_hidden = 0; g_cursor_serial++; }
@@ -1736,6 +1741,8 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
struct draw_list { struct vkp_draw *d; int n, cap; };
static int add_cursor(struct draw_list *dl, int scene_w);
static struct vkp_image *surface_image(struct surface *s) {
if (!s->has_content) return NULL;
if (s->shm_img) return s->shm_img;
@@ -1909,7 +1916,7 @@ static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int fra
}
if (un && g_zero_copy) { hs->color = droiddeck_color_of(un->resource); hs->who = un; return 3; }
hs->hf.tonemap = !droiddeck_color_output();
if (dl->n <= 0 || !(hs->is_hdr = calloc((size_t)dl->n, 1))) return 0;
if (dl->n <= 0 || !(hs->is_hdr = calloc((size_t)dl->n + CURSOR_MAX_DRAWS, 1))) return 0;
for (int i = 0; i < dl->n; i++) {
struct surface *s = surface_for_image(dl->d[i].img);
if (!is_hdr_surface(s)) continue;
@@ -2011,12 +2018,6 @@ static void hdr_count_copied(const struct draw_list *dl, const char *reason) {
}
}
/*
* Stream mode (the Xbox Cloud Gaming native player, in its own process): no Wayland clients, the scene is one
* picture handed over as AHardwareBuffers (ImageReader images of the decoded video). Each buffer is imported once
* and kept while the reader cycles through its few buffers; the newest frame is the scene, so the screen effects
* and frame generation apply to it as to a game.
*/
#define STREAM_SLOTS 6
static pthread_mutex_t g_stream_lock = PTHREAD_MUTEX_INITIALIZER;
static atomic_int g_stream_on;
@@ -2036,7 +2037,6 @@ static void stream_forget_all(void) {
g_stream_img = NULL;
}
/* Compositor thread: the newest handed-over buffer becomes the scene picture. */
static void stream_take(void) {
pthread_mutex_lock(&g_stream_lock);
AHardwareBuffer *ahb = g_stream_pending;
@@ -2050,7 +2050,7 @@ static void stream_take(void) {
if (g_stream_slots[i].used < g_stream_slots[oldest].used) oldest = i;
}
if (slot >= 0) {
AHardwareBuffer_release(ahb); /* the slot keeps its own reference */
AHardwareBuffer_release(ahb);
} else {
struct vkp_image *img = vkp_image_from_ahb(ahb);
if (!img) {
@@ -2062,7 +2062,7 @@ static void stream_take(void) {
droiddeck_log("stream", "decoded frame buffer imported (%dx%d)", vkp_image_width(img), vkp_image_height(img));
slot = oldest;
if (g_stream_slots[slot].img) {
vkp_wait_idle(); /* the GPU may still read the picture being replaced */
vkp_wait_idle();
if (g_stream_img == g_stream_slots[slot].img) g_stream_img = NULL;
vkp_image_destroy(g_stream_slots[slot].img);
}
@@ -2108,7 +2108,6 @@ void droiddeck_stream_set(int on) {
(void)n;
}
/* Any thread: hands over one decoded frame (acquires its own reference). */
void droiddeck_stream_frame(AHardwareBuffer *ahb) {
if (!ahb || !atomic_load(&g_stream_on) || g_input_pipe[1] < 0) return;
AHardwareBuffer_acquire(ahb);
@@ -2116,7 +2115,7 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
AHardwareBuffer *dropped = g_stream_pending;
g_stream_pending = ahb;
pthread_mutex_unlock(&g_stream_lock);
if (dropped) { AHardwareBuffer_release(dropped); return; } /* a wake-up is already queued */
if (dropped) { AHardwareBuffer_release(dropped); return; }
struct input_msg m = { 20, 0, 0, 0, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
@@ -2124,7 +2123,21 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
static int64_t g_scene_due_ns;
static int scene_held_for_limit(int64_t now, int64_t due, int limit, int unpaced) {
if (limit <= 0 || unpaced || due <= 0) return 0;
return now < due - 1000000LL;
}
static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
if (limit <= 0) return 0;
const int64_t interval = 1000000000LL / limit;
return due > 0 && now - due < interval ? due + interval : now + interval;
}
static void render_scene(void) {
g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
struct draw_list dl = {0};
struct surface *s;
@@ -2171,6 +2184,28 @@ static void render_scene(void) {
hdr_note_precedence(hdr_route == 3 ? hs.who : NULL, fx_on, framegen);
}
if (hdr_route == 3) { fx_on = 0; framegen = 0; }
struct surface *ahb_only = ahb_layer_only_candidate(w, h);
struct surface *layer_only = ahb_only ? ahb_only : hdr_unimported_fullscreen(&dl, w, h);
const int cursor_on = hdr_route == 3 || layer_only ? 0 : add_cursor(&dl, w);
static int cursor_layer_said;
if (layer_only && atomic_load(&g_cursor_composite) && !cursor_layer_said) {
cursor_layer_said = 1;
droiddeck_log("cursor", "the pointer stays out of the picture: the game's frames cannot be imported, "
"so the game is shown on its own display layer");
} else if (!layer_only) {
cursor_layer_said = 0;
}
static int cursor_hdr_said;
if (cursor_on && hdr_route == 0 && hs.n_hdr > 0 && !cardboard) {
hdr_route = 2;
if (!cursor_hdr_said) {
cursor_hdr_said = 1;
droiddeck_log("cursor", "the pointer needs a composed scene: the HDR picture goes through the screen "
"swapchain instead of the game's own display layer");
}
} else {
cursor_hdr_said = 0;
}
if (hdr_route == 1) {
static int fell_back;
vkp_apply_window_request();
@@ -2196,21 +2231,19 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard &&
!ahb_layer_only_candidate(w, h)) {
/* The complete SDR scene stays on one display layer. Do not hide/re-show GAME
* on each desktop frame just because it is not a single fullscreen window. */
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
int li = (g_zero_copy && !framegen && !cardboard) ? layer_candidate(&dl, w, h) : -1;
int li = (g_zero_copy && !framegen && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; }
const int ov_blocks = (li >= 0 && over > 0 && !fx_blocks && !sc_layer_overlay_affordable());
if (ov_blocks) { li = -1; over = 0; }
const int blocked = framegen ? 1 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0));
if (g_zero_copy && blocked != g_zero_copy_paused) {
if (g_zero_copy && !cursor_on && blocked != g_zero_copy_paused) {
g_zero_copy_paused = blocked;
if (blocked == 1)
droiddeck_log("framegen", "zero-copy paused: frame generation needs the compositor pass");
@@ -2223,9 +2256,9 @@ static void render_scene(void) {
droiddeck_log("effects", "zero-copy resumed: the game is back on its own display layer");
}
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
if (li < 0) ls = ahb_layer_only_candidate(w, h);
if (li < 0 && !ls) ls = hdr_unimported_fullscreen(&dl, w, h);
if (li < 0) ls = layer_only;
if (cardboard) ls = NULL;
if (cursor_on) ls = NULL;
if (ls && pass_on && li < 0 && !g_zero_copy_fx_skip_said) {
g_zero_copy_fx_skip_said = 1;
droiddeck_log(framegen ? "framegen" : "effects",
@@ -2302,12 +2335,12 @@ static void render_scene(void) {
static int on_fallback_timer(void *data) {
g_fallback_armed = 0;
if (g_dirty) render_scene();
if (!g_dirty) return 0;
if (scene_held_for_limit(now_ns(), g_scene_due_ns, g_fps_limit, g_release_unpaced)) schedule_render();
else render_scene();
return 0;
}
/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh,
while frames go straight back to the game (no compositor limit), without streaming or frame generation. */
static int commit_renders_on(void) {
return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active();
}
@@ -2366,10 +2399,6 @@ static void on_vsync(int64_t frame_time_ns) {
if (vkp_effects_sync()) tick_change = 1;
if (vkp_cardboard_pose_changed()) tick_change = 1;
if (tick_change) g_dirty = 1;
/* A frame that arrived after this refresh was already drawn is left for the next arrival to draw;
drawing it here would block that arrival too and keep every frame waiting for the tick. A client
that draws again only after its frame callback sends no such arrival: once a held frame is still
waiting at the next tick, the tick draws every frame for a second before holding one again. */
if (g_tick_held && g_dirty) g_hold_missed_ns = now;
g_tick_held = 0;
if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns &&
@@ -2377,6 +2406,7 @@ static void on_vsync(int64_t frame_time_ns) {
g_tick_held = 1;
return;
}
if (g_dirty && scene_held_for_limit(now, g_scene_due_ns, g_fps_limit, g_release_unpaced)) return;
if (g_dirty && !scene_waits_for_game(now)) render_scene();
}
@@ -2392,6 +2422,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
if (g_cursor_surface) g_cursor_surface->role = ROLE_NONE;
g_cursor_surface = NULL;
cursor_publish_hidden();
if (atomic_load(&g_cursor_composite)) schedule_render();
return;
}
struct surface *s = wl_resource_get_user_data(surface);
@@ -2399,8 +2430,10 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
if (s->role != ROLE_NONE && s->role != ROLE_CURSOR) return;
s->role = ROLE_CURSOR;
g_cursor_surface = s;
pthread_mutex_lock(&g_cursor_lock);
g_cursor_hx = hx;
g_cursor_hy = hy;
pthread_mutex_unlock(&g_cursor_lock);
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) {
cursor_publish_buffer(s, buffer);
@@ -2411,6 +2444,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
cursor_publish_pixels((const uint8_t *)s->idle_px, s->idle_w, s->idle_h, (size_t)s->idle_w * 4, hx, hy);
g_cursor_shown = s;
}
if (atomic_load(&g_cursor_composite)) schedule_render();
}
static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static const struct wl_pointer_interface pointer_impl = {
@@ -2592,6 +2626,97 @@ static int g_ptr_known;
static double g_raw_x, g_raw_y;
static int g_raw_valid;
static int pointer_locked_for_cursor(void) {
return g_active_constraint && g_active_constraint->is_lock;
}
static int cursor_scene_positions(int scene_w, int source, int ptr_x, int hx, int out[2]) {
out[0] = ptr_x - hx; out[1] = -1;
if (source != CARDBOARD_SOURCE_SBS || scene_w <= 1) return 1;
const int half = scene_w / 2;
out[1] = (ptr_x < half ? ptr_x + half : ptr_x - half) - hx;
return 2;
}
static int cursor_clip_to_eye(int scene_w, int eye, int x0, int w, int *dx, int *sx, int *dw) {
int left = x0, right = x0 + w;
if (eye >= 0 && scene_w > 1) {
const int half = scene_w / 2;
const int band = eye ? half : 0;
if (left < band) left = band;
if (right > band + half) right = band + half;
}
if (right <= left) return 0;
*dx = left;
*sx = left - x0;
*dw = right - left;
return 1;
}
static int add_cursor(struct draw_list *dl, int scene_w) {
if (!atomic_load(&g_cursor_composite) || !g_ptr_known || pointer_locked_for_cursor()) return 0;
int hidden, w, h, hx, hy, serial;
uint32_t *copy = NULL;
pthread_mutex_lock(&g_cursor_lock);
hidden = g_cursor_hidden;
w = g_cursor_w; h = g_cursor_h;
hx = g_cursor_hx; hy = g_cursor_hy;
serial = g_cursor_serial;
if (!hidden && w > 0 && h > 0 && serial != g_cursor_img_serial) {
copy = malloc((size_t)w * (size_t)h * 4);
if (copy) memcpy(copy, g_cursor_px, (size_t)w * (size_t)h * 4);
}
pthread_mutex_unlock(&g_cursor_lock);
if (hidden || w <= 0 || h <= 0) return 0;
if (copy) {
if (g_cursor_img && (g_cursor_img_w != w || g_cursor_img_h != h)) {
vkp_wait_idle();
vkp_image_destroy(g_cursor_img);
g_cursor_img = NULL;
}
if (!g_cursor_img) g_cursor_img = vkp_image_create_shm(w, h);
if (g_cursor_img) {
g_cursor_img_w = w; g_cursor_img_h = h;
vkp_image_upload_shm(g_cursor_img, copy, w * 4);
g_cursor_img_serial = serial;
}
free(copy);
}
if (!g_cursor_img || g_cursor_img_serial != serial) return 0;
int xs[CURSOR_MAX_DRAWS];
const int source = vkp_cardboard_source();
const int ptr_x = (int)(g_ptr_x + 0.5);
const int count = cursor_scene_positions(scene_w, source, ptr_x, hx, xs);
static int said_w = -1, said_source = -1, said_count = -1;
if (scene_w != said_w || source != said_source || count != said_count) {
said_w = scene_w; said_source = source; said_count = count;
droiddeck_log("cursor", "pointer drawn %d time(s) in a %d wide scene (%s picture)", count, scene_w,
source == CARDBOARD_SOURCE_SBS ? "side-by-side" : "single");
}
if (dl->n + count > dl->cap) {
int cap = dl->cap ? dl->cap : 32;
while (cap < dl->n + count) cap *= 2;
struct vkp_draw *d = realloc(dl->d, (size_t)cap * sizeof(*d));
if (!d) return 0;
dl->d = d; dl->cap = cap;
}
const int sbs = source == CARDBOARD_SOURCE_SBS && scene_w > 1;
const int pointer_eye = ptr_x < scene_w / 2 ? 0 : 1;
int appended = 0;
for (int i = 0; i < count; i++) {
int dx, sx, cw;
const int eye = sbs ? (i ? 1 - pointer_eye : pointer_eye) : -1;
if (!cursor_clip_to_eye(scene_w, eye, xs[i], w, &dx, &sx, &cw)) continue;
dl->d[dl->n++] = (struct vkp_draw){g_cursor_img, (float)sx, 0, (float)cw, (float)h,
dx, (int)(g_ptr_y + 0.5) - hy, cw, h, 1};
appended++;
}
return appended ? 1 : 0;
}
extern void droiddeck_on_pointer_lock(int locked, int x, int y);
static void sync_lock_notify(void) {
@@ -2600,6 +2725,7 @@ static void sync_lock_notify(void) {
if (locked == last) return;
last = locked;
droiddeck_on_pointer_lock(locked, (int)g_ptr_x, (int)g_ptr_y);
if (atomic_load(&g_cursor_composite)) schedule_render();
}
static void constraint_describe(const struct constraint *k, char *out, size_t size) {
@@ -2679,7 +2805,10 @@ static void constraint_activate(struct constraint *k) {
constraint_end(g_active_constraint, 1, "replaced by a newer request");
k->active = 1;
g_active_constraint = k;
const double was_x = g_ptr_x, was_y = g_ptr_y;
if (!k->is_lock) confine_clamp(k, &g_ptr_x, &g_ptr_y);
if ((g_ptr_x != was_x || g_ptr_y != was_y) && atomic_load(&g_cursor_composite))
schedule_render();
constraint_origin(k, &ox, &oy);
pointer_focus(k->surface->resource, wl_fixed_from_double(g_ptr_x - ox), wl_fixed_from_double(g_ptr_y - oy));
int focused = 0;
@@ -2738,6 +2867,7 @@ static void constraints_pointer_gone(struct wl_resource *pointer) {
static void constraints_surface_commit(struct surface *s) {
struct constraint *k;
const double was_x = g_ptr_x, was_y = g_ptr_y;
wl_list_for_each(k, &g_constraints, link) {
if (k->surface != s) continue;
if (k->pending_hint_set) {
@@ -2761,6 +2891,8 @@ static void constraints_surface_commit(struct surface *s) {
if (k->active && !k->is_lock) confine_clamp(k, &g_ptr_x, &g_ptr_y);
}
}
if ((g_ptr_x != was_x || g_ptr_y != was_y) && atomic_load(&g_cursor_composite))
schedule_render();
}
static void constraint_resource_destroy(struct wl_resource *r) {
@@ -2946,6 +3078,7 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int
if (k) confine_clamp(k, &x, &y);
g_ptr_x = x; g_ptr_y = y;
g_ptr_known = 1;
if (atomic_load(&g_cursor_composite)) schedule_render();
if (k) {
target = k->surface;
} else if (g_desktop) {
@@ -2968,10 +3101,6 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int
uint32_t t = now_ms();
pointer_focus(target->resource, fx, fy);
// A button-only input must not replay a cached absolute position. A game
// may have warped its cursor since the last motion (before taking lock,
// or while releasing it), so that replay can become an unintended pan.
// Absolute touch events still carry their position, including on clicks.
int rel_consumed = send_relative_motion(client, dx, dy);
if (!(k && k->is_lock) && !(relative && rel_consumed) && (!relative || dx != 0 || dy != 0))
for_each_pointer_of(client, sp) wl_pointer_send_motion(sp->ptr, t, fx, fy);
@@ -3003,9 +3132,6 @@ static void pointer_button(uint32_t button, int pressed) {
pointer_input(0, 0, 1, button, pressed);
return;
}
// Releases also clean up interrupted gestures. Deliver them to the existing
// pointer focus without motion or hit-testing: native touch has independent
// coordinates, so replaying g_ptr_x/y here can warp the game cursor.
uint32_t t = now_ms();
for (int i = 0; i < g_nptrs; i++) {
struct seat_pointer *sp = &g_ptrs[i];
@@ -3425,6 +3551,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
case 12: axis_event(m.p1, m.p2, 1); break;
case 20: stream_take(); break;
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
case 22: schedule_render(); break;
default: deliver_pointer(&m); break;
}
}
@@ -3499,6 +3626,17 @@ void droiddeck_wayland_send_scene_input(int type, int a, int b) {
(void)n;
}
void droiddeck_wayland_set_cursor_composite(int on) {
const int want = on ? 1 : 0;
if (atomic_exchange(&g_cursor_composite_want, want) == want) return;
atomic_store(&g_cursor_composite, want);
droiddeck_log("cursor", "compositing the pointer into the output: %s", on ? "on" : "off");
if (g_input_pipe[1] < 0) return;
struct input_msg m = { 22, on ? 1 : 0, 0, 0, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
}
const char *droiddeck_client_name(struct wl_client *client) { return client_name(client); }
struct wl_display *droiddeck_get_display(void) { return g_display; }
@@ -3678,8 +3816,6 @@ int droiddeck_wayland_run(void) {
open_session_log();
if (vkp_ready() != 0) WLOGE("renderer unavailable; clients will connect but nothing is drawn");
/* Presentation compatibility is not HDR capability. Set the initial layer mode before
* clients bind, including when Desktop is the first session in this app process. */
if (vkp_quest_layer_presentation() && sc_layer_available()) g_zero_copy = 1;
struct wl_display *display = wl_display_create();
@@ -374,16 +374,11 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
mark_failed(kind);
return 0;
}
/* The ring and the engine's images are new on this frame. Dispatching into them now
* null-dereferenced Turnip (vkp_framegen_run, first Steam frame, 2560x1440 to the panel).
* Show this frame as it is; generation starts once the size has settled. */
if (size_changed || ring == 2) {
FGLOG("frame generation catches up at %dx%d; this frame is shown as it is", w, h);
return 0;
}
/* The pacer's source rate must be the game's, not this loop's: a loop slowed by its own
* generations would otherwise read as a slower game and justify even more generations. */
++g_source_frames;
const uint64_t game_frames = droiddeck_game_frames();
uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate);
@@ -0,0 +1,89 @@
#include "gpu_busy.h"
#include <jni.h>
#include <pthread.h>
#include <stdatomic.h>
#include "gpuload_ring.h"
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct gpuload_vk g_v;
static struct gpuload_ring g_ring;
static uint32_t g_family, g_bits;
static PFN_vkQueueSubmit g_submit;
static int g_was_on;
static _Atomic int g_on, g_lost, g_timing;
static _Atomic uint64_t g_busy_ns;
static VkResult VKAPI_CALL timed_submit(VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence) {
if (!count || !atomic_load(&g_on) || atomic_load(&g_lost)) return g_submit(queue, count, infos, fence);
pthread_mutex_lock(&g_lock);
if (!atomic_load(&g_on) || atomic_load(&g_lost)) {
pthread_mutex_unlock(&g_lock);
return g_submit(queue, count, infos, fence);
}
if (g_ring.state == 0 && gpuload_ring_setup(&g_ring, &g_v, g_family, g_bits)) atomic_store(&g_timing, 1);
VkSubmitInfo *mine = NULL;
uint32_t used = 0;
if (g_ring.state == 1) {
uint64_t ns = gpuload_ring_harvest(&g_ring, &g_v);
if (g_was_on) atomic_fetch_add(&g_busy_ns, ns); // the first harvest after a pause holds work timed before it
g_was_on = 1;
mine = gpuload_ring_wrap(&g_ring, count, infos, &used);
}
VkResult r = g_submit(queue, count, mine ? mine : infos, fence);
if (mine && r != VK_SUCCESS) gpuload_ring_unwind(&g_ring, used);
pthread_mutex_unlock(&g_lock);
free(mine);
return r;
}
void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family) {
pthread_mutex_lock(&g_lock);
memset(&g_ring, 0, sizeof(g_ring));
g_was_on = 0;
atomic_store(&g_timing, 0);
atomic_store(&g_lost, 0);
PFN_vkGetDeviceProcAddr gdpa = g_vk.GetDeviceProcAddr;
g_v = (struct gpuload_vk){
.device = dev,
.create_pool = g_vk.CreateCommandPool,
.destroy_pool = (PFN_vkDestroyCommandPool)gdpa(dev, "vkDestroyCommandPool"),
.alloc_cmds = g_vk.AllocateCommandBuffers,
.begin = g_vk.BeginCommandBuffer,
.end = g_vk.EndCommandBuffer,
.cmd_reset = (PFN_vkCmdResetQueryPool)gdpa(dev, "vkCmdResetQueryPool"),
.cmd_timestamp = (PFN_vkCmdWriteTimestamp)gdpa(dev, "vkCmdWriteTimestamp"),
.create_queries = (PFN_vkCreateQueryPool)gdpa(dev, "vkCreateQueryPool"),
.destroy_queries = (PFN_vkDestroyQueryPool)gdpa(dev, "vkDestroyQueryPool"),
.results = (PFN_vkGetQueryPoolResults)gdpa(dev, "vkGetQueryPoolResults"),
};
VkPhysicalDeviceProperties props;
g_vk.GetPhysicalDeviceProperties(pd, &props);
gpuload_vk_period(&g_v, props.limits.timestampPeriod);
VkQueueFamilyProperties families[16];
uint32_t n = 16;
g_vk.GetPhysicalDeviceQueueFamilyProperties(pd, &n, families);
g_family = family;
g_bits = family < n ? families[family].timestampValidBits : 0;
// vk_loader_load_device has just put the driver's function back.
if (g_vk.QueueSubmit != timed_submit) g_submit = g_vk.QueueSubmit;
if (g_submit) g_vk.QueueSubmit = timed_submit;
pthread_mutex_unlock(&g_lock);
}
void vkp_gpu_busy_device_lost(void) {
atomic_store(&g_lost, 1);
atomic_store(&g_timing, 0);
}
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGpuBusyNs(JNIEnv *env, jclass cls) {
return atomic_load(&g_timing) ? (jlong)atomic_load(&g_busy_ns) : -1;
}
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTiming(JNIEnv *env, jclass cls, jboolean on) {
pthread_mutex_lock(&g_lock);
if (!on) g_was_on = 0;
atomic_store(&g_on, on ? 1 : 0);
pthread_mutex_unlock(&g_lock);
}
@@ -0,0 +1,9 @@
#ifndef GPU_BUSY_H
#define GPU_BUSY_H
#include "vk_loader.h"
// Times the compositor's own GPU work for the HUD (tools/gpuload/src/gpuload_ring.h); call after the device and its
// functions are loaded. Off until WaylandCompositor.nativeSetGpuTiming(true).
void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family);
void vkp_gpu_busy_device_lost(void);
#endif
@@ -103,7 +103,6 @@ static bool prepare_pin(void) {
(off_t)pin.memory << 12);
if (commands == MAP_FAILED) return false;
pin.commands = commands;
// A3xx/A4xx use type-3 CP_NOP; newer cores use type-7 with zero odd-parity bits.
uint32_t *words = commands;
words[0] = pin.nop;
words[1] = 0;
@@ -124,7 +123,6 @@ static void *hold_pin(void *unused) {
if (errno == EINTR || errno == ETIMEDOUT) continue;
break;
}
// Constraints expire after idle_timer (normally 80 ms); renew with a NOP, keeping devfreq alive.
usleep(25000);
if (atomic_load(&running) && !submit_pin()) break;
}
@@ -24,7 +24,6 @@ struct droiddeck_headpose {
float eye_aspect;
uint32_t eye_w, eye_h;
float display_hz;
// Uses a formerly reserved word; older publishers leave this zero.
uint32_t render_height;
uint32_t reserved[10];
};
@@ -8,7 +8,6 @@
#include "hudframes.h"
/* Layout written by gamescope patch 0125 (tools/gamescope/patches). */
#define HUD_FRAMES_MAGIC 0x46484444u
#define HUD_FRAMES_HEADER 128u
#define HUD_FRAMES_ENTRY 16u
@@ -69,7 +68,6 @@ int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, i
memcpy(&frametimes[n], e, 8);
memcpy(&times[n], e + 8, 8);
}
/* The writer may have lapped the ring while we copied: drop what it overwrote. */
uint64_t after = load64(h->map + 16);
uint64_t valid = after > cap ? after - cap : 0;
if (from < valid) {
@@ -8,9 +8,7 @@ struct hud_frames;
struct hud_frames *hud_frames_open(const char *path);
void hud_frames_close(struct hud_frames *h);
/* New frames since the last poll, oldest first; -1 while the file holds no valid ring. */
int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max);
/* info: pid, output width, output height, refresh mHz, Steam focused. */
int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len);
#endif
@@ -3,7 +3,6 @@
#include <string.h>
#include <strings.h>
/* Presentation only; this does not select a GPU driver or expand driver support. */
static inline int quest_device_matches(const char *model, const char *device, const char *maker) {
return !strcasecmp(model, "Quest 2") || !strcasecmp(model, "Quest 3") ||
!strcasecmp(model, "Quest 3S") ||
+74 -21
View File
@@ -291,7 +291,7 @@ int sc_layer_base_black(int width, int height) {
ARect src = {0, 0, 16, 16}, dst = {0, 0, width, height};
api.setBuffer(tx, g_base_sc, black, -1);
api.setBufferTransparency(tx, g_base_sc, ASC_TRANSPARENCY_OPAQUE);
api.setZOrder(tx, g_base_sc, 0); /* GAME = 1, OVERLAY = 2 */
api.setZOrder(tx, g_base_sc, 0);
api.setGeometry(tx, g_base_sc, &src, &dst, 0);
api.setVisibility(tx, g_base_sc, ASC_VISIBILITY_SHOW);
api.txApply(tx); api.txDelete(tx);
@@ -381,6 +381,26 @@ static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod
return 1;
}
#define SC_MOD_GRALLOC (~0ULL - 1)
static const char *pool_kind(uint64_t mod) {
return mod == MOD_QCOM_COMPRESSED ? "UBWC" : mod == SC_MOD_GRALLOC ? "gralloc-laid-out" : "linear";
}
static void describe_handle(const struct droiddeck_native_handle *h, char *out, size_t n) {
size_t o = 0;
out[0] = 0;
if (!h) { snprintf(out, n, "no handle"); return; }
for (int i = 0; i < h->numFds && i < 4 && o < n; i++) {
off_t sz = lseek(h->data[i], 0, SEEK_END);
if (sz >= 0) lseek(h->data[i], 0, SEEK_SET);
o += (size_t)snprintf(out + o, n - o, "%sfd%d %lld bytes", i ? ", " : "", i, (long long)sz);
}
if (o < n) o += (size_t)snprintf(out + o, n - o, "; ints");
for (int i = 0; i < h->numInts && i < 8 && o < n; i++)
o += (size_t)snprintf(out + o, n - o, " %#x", (unsigned)h->data[h->numFds + i]);
}
static int g_alloc_failed;
enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR };
@@ -416,22 +436,54 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
AHardwareBuffer_Desc got; AHardwareBuffer_describe(ahb, &got);
const struct droiddeck_native_handle *nh = api.getNativeHandle(ahb);
uint64_t mod = MOD_LINEAR;
if (!sniff_modifier(nh, &mod)) {
if (tier < TIER_LINEAR) {
struct vkp_image *img = NULL;
const char *path;
char info[160] = "";
if (sniff_modifier(nh, &mod)) {
img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h,
got.stride * 4, 0, 1);
path = "dma-buf (QTI handle)";
} else {
if (tier == TIER_UBWC) {
char hd[256];
describe_handle(nh, hd, sizeof(hd));
droiddeck_log("layer", "%s: gralloc handle is not a QTI one (%d fds, %d ints: %s): no UBWC request; "
"pool buffers are imported %s", l->name, nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd,
vkp_can_import_ahb() ? "as AHardwareBuffers (the driver takes gralloc's own layout)"
: "as linear dma-bufs (this driver has no AHardwareBuffer import)");
AHardwareBuffer_release(ahb);
l->alloc_tier = TIER_LINEAR;
droiddeck_log("layer", "%s: gralloc handle layout unknown (%d fds, %d ints): using linear pool buffers",
l->name, nh ? nh->numFds : -1, nh ? nh->numInts : -1);
l->alloc_tier = vkp_can_import_ahb() ? TIER_PLAIN : TIER_LINEAR;
continue;
}
mod = MOD_LINEAR;
mod = SC_MOD_GRALLOC;
path = "AHardwareBuffer";
img = vkp_image_import_ahb(ahb, info, sizeof(info));
if (!img && tier == TIER_LINEAR) {
const off_t need = (off_t)got.stride * 4 * h;
int fd = -1, which = -1;
for (int i = 0; nh && i < nh->numFds; i++) {
off_t sz = lseek(nh->data[i], 0, SEEK_END);
if (sz >= 0) lseek(nh->data[i], 0, SEEK_SET);
if (sz >= need) { fd = nh->data[i]; which = i; break; }
}
if (fd < 0 && nh && nh->numFds > 0) { fd = nh->data[0]; which = 0; }
mod = MOD_LINEAR;
path = "linear dma-buf";
img = fd >= 0 ? vkp_image_import_dmabuf(fd, fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod,
w, h, got.stride * 4, 0, 1) : NULL;
snprintf(info, sizeof(info), "handle fd %d of %d", which, nh ? nh->numFds : 0);
if (vkp_can_import_ahb())
droiddeck_log("layer", "%s: AHardwareBuffer import failed: the linear dma-buf in the handle's fd %d "
"(of %d) -> %s", l->name, which, nh ? nh->numFds : 0, img ? "imported" : "failed too");
}
}
int fd = (nh && nh->numFds > 0) ? nh->data[0] : -1;
struct vkp_image *img = fd >= 0 ? vkp_image_import_dmabuf(fd, fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888,
mod, w, h, got.stride * 4, 0, 1) : NULL;
if (!img) {
droiddeck_log("layer", "%s: import of a %s %dx%d pool buffer (stride %u px) into the compositor's Turnip failed",
l->name, mod == MOD_QCOM_COMPRESSED ? "UBWC" : "linear", w, h, got.stride);
char hd[256];
describe_handle(nh, hd, sizeof(hd));
droiddeck_log("layer", "%s: import of a %s %dx%d pool buffer (stride %u px, %s, usage %#llx) into the "
"compositor's Turnip failed via %s; gralloc handle %d fds / %d ints: %s", l->name,
pool_kind(mod), w, h, got.stride, tier_name(tier), (unsigned long long)got.usage, path,
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
AHardwareBuffer_release(ahb);
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
g_alloc_failed = 1;
@@ -442,10 +494,11 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
if (l->logged_w != w || l->logged_h != h || l->logged_fmt != fmt || l->logged_mod != mod ||
l->logged_tier != tier) {
l->logged_w = w; l->logged_h = h; l->logged_fmt = fmt; l->logged_mod = mod; l->logged_tier = tier;
droiddeck_log("layer", "%s: pool buffers %dx%d%s: %s (%s), stride %u px, up to %d buffers (gralloc handle %d fds / %d ints)",
l->name, w, h, fmt == AHB_RGB10A2 ? " 10-bit RGBA1010102" : "",
mod == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" : "linear", tier_name(tier),
got.stride, l->pool_n, nh ? nh->numFds : -1, nh ? nh->numInts : -1);
droiddeck_log("layer", "%s: pool buffers %dx%d%s: %s (%s), stride %u px, up to %d buffers (gralloc handle %d fds / "
"%d ints), imported as %s%s%s%s", l->name, w, h, fmt == AHB_RGB10A2 ? " 10-bit RGBA1010102" : "",
mod == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" : pool_kind(mod), tier_name(tier),
got.stride, l->pool_n, nh ? nh->numFds : -1, nh ? nh->numInts : -1, path,
info[0] ? " (" : "", info, info[0] ? ")" : "");
}
return 0;
}
@@ -814,7 +867,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
l->first_logged = 1;
droiddeck_log("layer", "presenting %dx%d game frames on their own SurfaceControl layer (%s pool, %d buffers); "
"HUD and pointer stay Android views above it", sw, sh,
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear", l->pool_n);
pool_kind(l->pool_modifier), l->pool_n);
}
vkp_signal_first_frame();
return 0;
@@ -836,7 +889,7 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
l->first_logged = 1;
droiddeck_log("layer", "presenting %dx%d frames on their own SurfaceControl layer (%s pool, %d buffers); "
"HUD and pointer stay Android views above it", rw, rh,
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear", l->pool_n);
pool_kind(l->pool_modifier), l->pool_n);
}
vkp_signal_first_frame();
return 0;
@@ -874,12 +927,12 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
if (tm)
droiddeck_log("color", "tone-mapped picture on the game's display layer: %dx%d, %s 8-bit buffers, untagged "
"(sRGB) - HDR output is switched off", rw, rh,
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear");
pool_kind(l->pool_modifier));
else {
char cov[96];
coverage_text(l, cov, sizeof(cov));
droiddeck_log("color", "HDR picture on its own display layer: %dx%d, %s %s buffers, tagged %s%s%s", rw, rh,
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear",
pool_kind(l->pool_modifier),
g_hdr_pool_fmt == AHB_RGB10A2 ? "10-bit" : "8-bit",
color && color->dataspace == DROIDDECK_ADATASPACE_BT2020_PQ ? "BT2020_PQ" : "HDR",
cov[0] ? ", " : "", cov);
@@ -973,7 +1026,7 @@ void sc_layer_hide_overlay(void) {
}
void sc_layer_window_gone(void) {
base_hide(1); /* the backdrop belongs to the old window, just like GAME and OVERLAY */
base_hide(1);
if (api.state != 1) return;
layers_init();
for (int i = SC_LAYER_COUNT - 1; i >= 0; i--) retire_sc(&g_layers[i]);
+105 -17
View File
@@ -7,6 +7,7 @@
#include "framegen_bridge.h"
#include "hdr_compose.h"
#include "blend_pass.h"
#include "gpu_busy.h"
#include "droiddeck_color.h"
#include "quest_device.h"
#include <stdio.h>
@@ -70,8 +71,6 @@ static int g_first_frame_done;
static int g_base_black;
int vkp_quest_layer_presentation(void) {
/* Compositor thread only; this is a process-wide device property, not a session setting.
* Quest 2 still needs its separate A6xx driver: this gate only chooses presentation. */
static int enabled = -1;
if (enabled < 0) {
char model[PROP_VALUE_MAX] = {0}, device[PROP_VALUE_MAX] = {0}, maker[PROP_VALUE_MAX] = {0};
@@ -94,6 +93,9 @@ static int g_black_state;
static PFN_vkImportSemaphoreFdKHR g_import_sem_fd;
static VkSemaphore g_wait_sem;
#define VKP_VENDOR_QUALCOMM 0x5143
static uint32_t g_vendor_id;
static struct vkp_perf g_perf;
static int64_t perf_now(void) {
struct timespec ts;
@@ -461,6 +463,7 @@ static int dev_init(void) {
{
VkPhysicalDeviceProperties props;
g_vk.GetPhysicalDeviceProperties(g_pd, &props);
g_vendor_id = props.vendorID;
snprintf(g_gpu_name, sizeof(g_gpu_name), "%s", props.deviceName);
droiddeck_log("gpu", "compositor renders on %s with %s", props.deviceName,
g_library_name ? g_library_name : "the system Vulkan driver");
@@ -476,7 +479,6 @@ static int dev_init(void) {
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player never needs. */
for (unsigned i = 0; i < 4; i++) {
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
@@ -488,7 +490,6 @@ static int dev_init(void) {
}
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
/* The cloud player's decoded frames arrive as AHardwareBuffers (vkp_image_from_ahb). */
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
if (g_ahb_import) {
@@ -517,6 +518,7 @@ static int dev_init(void) {
}
vk_loader_load_device(g_dev);
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
vkp_gpu_busy_device(g_pd, g_dev, g_qfam);
if (want_sem_fd) {
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
@@ -991,8 +993,9 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
.allocationSize = req.size, .memoryTypeIndex = (uint32_t)idx};
VkResult mr = g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
if (mr != VK_SUCCESS) {
LOGE("%s: importing the %s dma-buf (%dx%d, %llu bytes) -> %s", as_blit_dst ? "layer" : "dmabuf",
vkp_modifier_name(modifier), w, h, (unsigned long long)req.size, vk_result_name(mr));
LOGE("%s: importing the %s dma-buf (%dx%d, pitch %u, offset %u, %llu bytes, memory type %d of image types "
"%#x & fd types %#x) -> %s", as_blit_dst ? "layer" : "dmabuf", vkp_modifier_name(modifier), w, h,
stride, offset, (unsigned long long)req.size, idx, req.memoryTypeBits, allowed, vk_result_name(mr));
g_vk.DestroyImage(g_dev, img->image, NULL); close(dupfd); free(img); return NULL;
}
VkResult br = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
@@ -1059,6 +1062,101 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
return img;
}
int vkp_can_import_ahb(void) {
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import &&
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
}
struct vkp_image *vkp_image_import_ahb(struct AHardwareBuffer *ahb, char *info, size_t info_n) {
if (info && info_n) info[0] = 0;
if (!ahb || !vkp_can_import_ahb()) return NULL;
AHardwareBuffer_Desc d;
AHardwareBuffer_describe(ahb, &d);
VkAndroidHardwareBufferFormatPropertiesANDROID fp = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID hp = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &fp};
VkResult pr = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, ahb, &hp);
if (pr != VK_SUCCESS) {
LOGE("layer: vkGetAndroidHardwareBufferPropertiesANDROID(%ux%u, AHB format %#x, usage %#llx) -> %s", d.width,
d.height, d.format, (unsigned long long)d.usage, vk_result_name(pr));
return NULL;
}
if (fp.format == VK_FORMAT_UNDEFINED) {
LOGE("layer: the driver reports the %ux%u AHB (format %#x) as external format %#llx only: no blit target",
d.width, d.height, d.format, (unsigned long long)fp.externalFormat);
return NULL;
}
const VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
if (g_vk.GetPhysicalDeviceImageFormatProperties2) {
VkPhysicalDeviceExternalImageFormatInfo ext = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkPhysicalDeviceImageFormatInfo2 qi = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, .pNext = &ext, .format = fp.format,
.type = VK_IMAGE_TYPE_2D, .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = usage};
VkExternalImageFormatProperties extp = {.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES};
VkImageFormatProperties2 ip = {.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, .pNext = &extp};
VkResult qr = g_vk.GetPhysicalDeviceImageFormatProperties2(g_pd, &qi, &ip);
if (qr != VK_SUCCESS ||
!(extp.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)) {
LOGE("layer: VkFormat %d as an imported AHB blit target is not supported (%s, external features %#x)",
(int)fp.format, vk_result_name(qr), extp.externalMemoryProperties.externalMemoryFeatures);
return NULL;
}
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)d.width; img->h = (int)d.height;
img->dmabuf = 1; img->blit_dst = 1;
img->fmt = fp.format;
VkExternalMemoryImageCreateInfo extImg = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo ici = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &extImg,
.imageType = VK_IMAGE_TYPE_2D, .format = fp.format, .extent = {d.width, d.height, 1},
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
if (cr != VK_SUCCESS) {
LOGE("layer: vkCreateImage(AHB %ux%u, VkFormat %d) -> %s", d.width, d.height, (int)fp.format,
vk_result_name(cr));
free(img); return NULL;
}
int idx = -1;
for (int i = 0; i < 32; i++) if (hp.memoryTypeBits & (1u << i)) { idx = i; break; }
if (idx < 0) {
LOGE("layer: no memory type can import the %ux%u AHB (memoryTypeBits 0)", d.width, d.height);
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
}
VkImportAndroidHardwareBufferInfoANDROID imp = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = ahb};
VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &imp, .image = img->image};
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
.allocationSize = hp.allocationSize, .memoryTypeIndex = (uint32_t)idx};
VkResult mr = g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
if (mr != VK_SUCCESS) {
LOGE("layer: importing the %ux%u AHB (VkFormat %d, %llu bytes, memory type %d of memoryTypeBits %#x) -> %s",
d.width, d.height, (int)fp.format, (unsigned long long)hp.allocationSize, idx, hp.memoryTypeBits,
vk_result_name(mr));
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
}
VkResult br = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
if (br != VK_SUCCESS) {
LOGE("layer: vkBindImageMemory(AHB) -> %s", vk_result_name(br));
g_vk.FreeMemory(g_dev, img->mem, NULL); g_vk.DestroyImage(g_dev, img->image, NULL);
free(img); return NULL;
}
if (info && info_n)
snprintf(info, info_n, "VkFormat %d, %llu bytes, memory type %d of memoryTypeBits %#x", (int)fp.format,
(unsigned long long)hp.allocationSize, idx, hp.memoryTypeBits);
return img;
}
static int shm_sampled(void) {
static int known;
if (!known) {
@@ -1311,6 +1409,7 @@ static void device_lost(const char *where) {
g_dev_state = -2;
g_base_black = 0;
vkp_framegen_device_lost();
vkp_gpu_busy_device_lost();
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
"restart the session", where);
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
@@ -1698,9 +1797,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if (fx) {
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
/* Frame generation samples every output pixel. Upscaling first made it interpolate
* the whole panel (3200x1440 on a 1440p phone) and rebuild on Steam's first frame.
* Grade at the game's size instead; the screen blit still scales to the panel. */
if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt);
result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, &rw, &rh);
@@ -1800,9 +1896,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
if (vkp_quest_layer_presentation() && !vkp_framegen_active() && !vkp_cardboard_active()) {
/* The desktop (multiple windows), overlays and an empty scene must also avoid WSI.
* Merely enabling zero-copy handles only a single fullscreen window and leaves both
* the letterbox and every fallback frame going through the corrupted swapchain. */
vkp_apply_window_request();
sc_layer_hide_overlay();
if (n > 0) {
@@ -1814,9 +1907,6 @@ int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
} else {
sc_layer_hide();
}
/* sc_layer_present_pass signals only after submitting client content.
* A backdrop alone, or a successful no-op while a layer slot is unavailable,
* must not dismiss the app's loading UI or mark Steam's window as shown. */
return vkp_base_black(scene_w, scene_h);
}
return render_impl(scene_w, scene_h, draws, n, NULL, NULL);
@@ -1853,8 +1943,6 @@ void vkp_signal_first_frame(void) {
int vkp_update_map(int scene_w, int scene_h) {
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
if (vkp_quest_layer_presentation()) {
/* Layer geometry needs the window size, not a Vulkan swapchain. In particular, do
* not create/present a swapchain just to paint black under an otherwise clean layer. */
int w = ANativeWindow_getWidth(g_window), h = ANativeWindow_getHeight(g_window);
if (w <= 0 || h <= 0) return -1;
g_extent = (VkExtent2D){(uint32_t)w, (uint32_t)h};
@@ -1,6 +1,7 @@
#ifndef VK_PRESENT_H
#define VK_PRESENT_H
#include <stdint.h>
#include <stddef.h>
#include <android/native_window.h>
void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir);
@@ -33,6 +34,9 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
int w, int h, uint32_t stride, uint32_t offset,
int as_blit_dst);
int vkp_image_is_dmabuf(const struct vkp_image *img);
struct AHardwareBuffer;
int vkp_can_import_ahb(void);
struct vkp_image *vkp_image_import_ahb(struct AHardwareBuffer *ahb, char *info, size_t info_n);
struct vkp_image *vkp_image_create_shm(int w, int h);
struct AHardwareBuffer;
@@ -30,6 +30,7 @@ extern void droiddeck_wayland_send_key(int evdev, int state);
extern int droiddeck_focus_takes_touch(void);
extern int droiddeck_cursor_input_pos(int *x, int *y);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
extern void droiddeck_wayland_set_cursor_composite(int on);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
extern void droiddeck_stream_set(int on);
extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
@@ -292,6 +293,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv
return droiddeck_cursor_serial();
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCursorComposite(
JNIEnv *env, jclass clazz, jboolean on) {
(void)env; (void)clazz;
droiddeck_wayland_set_cursor_composite(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
JNIEnv *env, jclass clazz, jint evdev, jint state) {
@@ -690,7 +698,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *
jclass error = (*env)->FindClass(env, "java/lang/IllegalStateException");
if (error) (*env)->ThrowNew(env, error, strerror(saved_errno));
}
// Clear a legacy global pin when recovering its marker after an app upgrade or crash.
if (on != JNI_TRUE) adrenotools_set_turbo(false);
}
@@ -717,7 +724,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialP
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
}
/* The Xbox Cloud Gaming native player: its decoded frames are the whole scene (no Wayland clients). */
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamMode(JNIEnv *env, jclass clazz, jboolean on) {
droiddeck_stream_set(on ? 1 : 0);
@@ -17,7 +17,8 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
// Helper processes must not initialize the main USB provider or guest graphics context.
com.droiddeck.launcher.ui.BuildWatermark.install(this)
HomeApp.trackRecents(this)
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
@@ -30,12 +31,13 @@ class App : Application() {
return
}
if (process == "$packageName:xcloudnative") {
// The native cloud player: the stores log and nothing that touches the Linux session.
com.droiddeck.launcher.stores.StoresState.init(this)
return
}
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
CrashHandler.install(this)
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
@@ -53,11 +55,12 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gamejolt.GameJoltBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.sync.Syncthing.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
}
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
private fun prefetchAddonPacks() {
val app = this
Thread({
@@ -65,7 +65,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
fun state() = GpuDriversState(
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
@@ -264,7 +264,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
return
}
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase())
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
}
releaseChecking = true
@@ -78,6 +78,7 @@ import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
@@ -161,6 +162,10 @@ class FrontEndActivity : ComponentActivity() {
private var gameCores by mutableStateOf<Set<Int>>(emptySet())
private var tuSysmem by mutableStateOf(false)
private var zinkLazy by mutableStateOf(false)
private var vkBridge by mutableStateOf(false)
private var vkBridgeSafe by mutableStateOf(true)
private var bridgeProtonDxvk by mutableStateOf(false)
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
private var noXalia by mutableStateOf(true)
private var fastSync by mutableStateOf(false)
private var syncFallback by mutableStateOf(true)
@@ -194,7 +199,7 @@ class FrontEndActivity : ComponentActivity() {
private var navRequest by mutableStateOf<String?>(null)
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.STORES_VIEWS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
private var mic by mutableStateOf(false)
private var wifiDiscovery by mutableStateOf(false)
private var wifiDiscoveryPermission by mutableStateOf(false)
@@ -315,15 +320,11 @@ class FrontEndActivity : ComponentActivity() {
refreshWifiDiscovery()
}
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
HomeApp.setHomeScreenEnabled(this, true)
refreshHomeAppState()
manageHomeApp()
}
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
SteamIntegration.Feature.SHORTCUTS -> {
if (!integrationState.shortcuts) shortcutsTried = true
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
SteamIntegration.setShortcutsListed(this, true)
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
}
}
}
@@ -456,7 +457,7 @@ class FrontEndActivity : ComponentActivity() {
private var fexPreset by mutableStateOf("")
private var forceSsbs by mutableStateOf(false)
private var steamClientArch by mutableStateOf("arm64")
private var runSteamAtStartup by mutableStateOf(false)
private var startupSession by mutableStateOf(SessionPrefs.STARTUP_OFF)
private var bootMovie by mutableStateOf(com.droiddeck.launcher.session.BootMovie.DROIDDECK_30)
private var bootMovieSound by mutableStateOf(true)
private var bootMovieCustomName by mutableStateOf<String?>(null)
@@ -472,6 +473,7 @@ class FrontEndActivity : ComponentActivity() {
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var backHold by mutableStateOf(true)
private var backActionsInverted by mutableStateOf(false)
private var gameStorage by mutableStateOf("")
private var slowUsb by mutableStateOf<com.droiddeck.launcher.session.UsbLink.SlowDrive?>(null)
@@ -489,6 +491,40 @@ class FrontEndActivity : ComponentActivity() {
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
}
private var steamLibraries by mutableStateOf<List<SteamLibraries.Entry>>(emptyList())
private var foundSteamLibraries by mutableStateOf<List<SteamLibraries.Found>>(emptyList())
private var allFilesAccessMissing by mutableStateOf(false)
private var steamLibraryScan = 0
private val pickSteamLibrary = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val path = if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data) else null
if (path != null) addSteamLibrary(path)
}
private fun addSteamLibrary(path: String) {
Thread({
val result = SteamLibraries.add(this, path)
ui.post {
steamLibraries = SteamLibraries.list(this)
refreshFoundSteamLibraries()
refresh()
when {
result is SteamLibraries.AddResult.Refused ->
android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, result.reason), android.widget.Toast.LENGTH_LONG).show()
result is SteamLibraries.AddResult.Added && result.entry.path != path ->
android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show()
}
}
}, "steam-library-add").start()
}
private fun refreshFoundSteamLibraries() {
allFilesAccessMissing = com.droiddeck.launcher.files.AllFilesAccess.missing()
val scan = ++steamLibraryScan
Thread({
val found = SteamLibraries.found(this)
ui.post { if (scan == steamLibraryScan) foundSteamLibraries = found }
}, "steam-library-scan").start()
}
private var romsDir by mutableStateOf<String?>(null)
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
private var steamGamesX64 by mutableStateOf(false)
@@ -529,7 +565,7 @@ class FrontEndActivity : ComponentActivity() {
private var dualDisplayId by mutableStateOf(-1)
private var dualScreenDevice by mutableStateOf(false)
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
private var dualScreenLauncher by mutableStateOf(true)
private var dualScreenSessions by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
private var dualScreenControls by mutableStateOf(true)
private var launcherStarted = false
private lateinit var displayManager: DisplayManager
@@ -538,10 +574,25 @@ class FrontEndActivity : ComponentActivity() {
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
}
private val bottomScreenListener: () -> Unit = { refreshSecondScreenDisplays() }
private val secondScreenTouchListener = object : android.hardware.input.InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) = refreshSecondScreenDisplays()
override fun onInputDeviceRemoved(deviceId: Int) = refreshSecondScreenDisplays()
override fun onInputDeviceChanged(deviceId: Int) = refreshSecondScreenDisplays()
}
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
homeChoiceOpen = false
HomeApp.releaseUnusedHomeEntry(this)
refreshHomeAppState()
}
private val gameSpaceAdd = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
homeChoiceOpen = false
if (HomeApp.inGameSpace(this)) enableHomeScreen()
else refreshHomeAppState()
}
private var homeChoiceOpen = false
private var gameSpaceOffered = false
override fun startActivity(intent: Intent?) {
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
@@ -707,7 +758,6 @@ class FrontEndActivity : ComponentActivity() {
LauncherIcon.set(this, style)
launcherIcon = LauncherIcon.current(this)
if (launcherIcon == before) return false
// Android finishes activities started through the alias that was just disabled.
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(LauncherIcon.activity(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
@@ -739,7 +789,10 @@ class FrontEndActivity : ComponentActivity() {
if (id == null) {
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else refresh()
} else {
handleGameLink(steamGames, scanned = false)
refresh()
}
}
}
}, "game-launch-file").start()
@@ -942,9 +995,10 @@ class FrontEndActivity : ComponentActivity() {
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
}
private fun handleGameLink(games: List<Library.SteamGame>) {
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
if (!scanned && games.none { it.gameIdString == id }) return
gameLinkTried = true
ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
@@ -972,6 +1026,8 @@ class FrontEndActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
readGameIntent(intent)
gameSyncFolder = GameFileSync.folder(this)
@@ -1027,6 +1083,7 @@ class FrontEndActivity : ComponentActivity() {
FrontEndScreen(
FrontEndState(
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
vkBridge = vkBridge, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
shortcutPicker = shortcutPicker,
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
@@ -1054,7 +1111,7 @@ class FrontEndActivity : ComponentActivity() {
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
dualScreenDevice = dualScreenDevice,
dualScreenMode = dualScreenMode,
dualScreenLauncher = dualScreenLauncher,
dualScreenSessions = dualScreenSessions,
dualScreenControls = dualScreenControls,
packages = packageRows,
packageCatalogLoading = catalogLoading,
@@ -1175,6 +1232,15 @@ class FrontEndActivity : ComponentActivity() {
onInstallPackage = { id -> installPackage(id) },
onRemovePackage = { id -> removePackage(id) },
onRuntime = { onRuntimeButton() },
onVkBridge = { on ->
SessionPrefs.setVkBridge(this, on); vkBridge = on
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
onBridgeProtonDxvk = { on ->
SessionPrefs.setBridgeProtonDxvk(this, on); bridgeProtonDxvk = on
if (on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onFrameGenPick = { mode ->
FrameGen.set(this, mode)
frameGenLabel = FrameGen.label(this)
@@ -1288,8 +1354,8 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setDualScreenMode(this, mode)
refreshSecondScreenDisplays()
},
onDualScreenLauncher = { on ->
SessionPrefs.setDualScreenLauncher(this, on)
onDualScreenSessions = { mode ->
SessionPrefs.setDualScreenSessionMode(this, mode)
refreshSecondScreenDisplays()
},
onDualScreenControls = { on ->
@@ -1327,8 +1393,11 @@ class FrontEndActivity : ComponentActivity() {
integrationState = readIntegration()
},
onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on)
refreshHomeAppState()
if (on && HomeApp.hasGameSpace(this)) offerHomeScreen()
else {
HomeApp.setHomeScreenEnabled(this, on)
refreshHomeAppState()
}
},
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
onBackActionsInverted = { inverted ->
@@ -1493,7 +1562,7 @@ class FrontEndActivity : ComponentActivity() {
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
else {
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
@@ -1536,9 +1605,14 @@ class FrontEndActivity : ComponentActivity() {
startSteamAtStartupIfEnabled()
}
private fun startSteamAtStartupIfEnabled() {
if (intent.action != Intent.ACTION_MAIN) return
if (SessionPrefs.runSteamAtStartup(this) && !isFinishing && !isDestroyed) startSteamSession()
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
if (isFinishing || isDestroyed) return
when (SessionPrefs.startupSession(this)) {
SessionPrefs.STARTUP_STEAM -> startSteamSession()
SessionPrefs.STARTUP_DESKTOP -> startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP))
}
}
private fun playSteam() {
@@ -1560,9 +1634,28 @@ class FrontEndActivity : ComponentActivity() {
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
val outside = com.droiddeck.launcher.ui.DualScreenPanel.shownOn >= 0 &&
com.droiddeck.launcher.ui.DualScreenPanel.opensOutside(packageName, intent.component?.packageName ?: intent.`package` ?: intent.resolveActivity(packageManager)?.packageName)
if (outside) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
window.decorView.postDelayed({ if (hasWindowFocus()) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) }, 1500)
}
try {
super.startActivityForResult(intent, requestCode, options)
} catch (e: RuntimeException) {
if (outside) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
throw e
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) applyLauncherFullscreen()
if (hasFocus) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
applyLauncherFullscreen()
}
}
private fun applyLauncherFullscreen() {
@@ -1621,16 +1714,24 @@ class FrontEndActivity : ComponentActivity() {
override fun onPause() {
compatLaunchVisible = false
if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, true)
super.onPause()
}
override fun onResume() {
super.onResume()
if (!homeChoiceOpen) {
HomeApp.releaseUnusedHomeEntry(this)
refreshHomeAppState()
}
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
compatLaunchVisible = true
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
SteamIntegration.syncShortcutsListing(this)
refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
@@ -1682,6 +1783,8 @@ class FrontEndActivity : ComponentActivity() {
addDataScheme("file")
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
com.droiddeck.launcher.input.DualScreen.watchTaken(bottomScreenListener)
getSystemService(android.hardware.input.InputManager::class.java)?.registerInputDeviceListener(secondScreenTouchListener, ui)
launcherStarted = true
refreshSecondScreenDisplays()
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
@@ -1697,6 +1800,8 @@ class FrontEndActivity : ComponentActivity() {
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
@@ -1716,7 +1821,13 @@ class FrontEndActivity : ComponentActivity() {
super.onDestroy()
}
override fun onRestart() {
super.onRestart()
homeChoiceOpen = false
}
override fun onStop() {
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
@@ -1725,6 +1836,8 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
launcherStarted = false
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
flood = null
@@ -1758,15 +1871,14 @@ class FrontEndActivity : ComponentActivity() {
private fun refreshSecondScreenDisplays() {
if (!::displayManager.isInitialized) return
// The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen".
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
dualScreenMode = SessionPrefs.dualScreenMode(this)
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
dualScreenLauncher = SessionPrefs.dualScreenLauncher(this)
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, ownDisplayId)
dualDisplayId = if (dualScreenLauncher) target?.displayId ?: -1 else -1
dualDisplayId = target?.displayId ?: -1
syncDualPanel()
}
@@ -1795,12 +1907,32 @@ class FrontEndActivity : ComponentActivity() {
}
}
private fun offerHomeScreen() {
if (!gameSpaceOffered && HomeApp.hasGameSpace(this) && !HomeApp.inGameSpace(this)) {
gameSpaceOffered = true
val opened = runCatching { gameSpaceAdd.launch(HomeApp.gameSpaceAddIntent()) }.isSuccess
if (opened) {
homeChoiceOpen = true
android.widget.Toast.makeText(this, R.string.setup_home_game_space_first, android.widget.Toast.LENGTH_LONG).show()
return
}
}
enableHomeScreen()
}
private fun enableHomeScreen() {
HomeApp.setHomeScreenEnabled(this, true)
refreshHomeAppState()
manageHomeApp()
}
private fun manageHomeApp() {
homeChoiceOpen = true
val request = HomeApp.roleRequestIntent(this)
if (request != null) {
homeRoleRequest.launch(request)
} else {
HomeApp.openSystemHomeSettings(this)
} else if (runCatching { homeRoleRequest.launch(HomeApp.settingsIntent()) }.isFailure) {
homeChoiceOpen = false
}
}
@@ -2066,6 +2198,7 @@ class FrontEndActivity : ComponentActivity() {
unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
unfoldedControlsWithController = unfoldedControlsWithController,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
backHold = backHold,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
@@ -2073,6 +2206,9 @@ class FrontEndActivity : ComponentActivity() {
mic = if (mode == SessionService.MODE_STEAM) mic else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
storageOptions = storageOptions,
steamLibraries = steamLibraries,
foundSteamLibraries = foundSteamLibraries,
allFilesAccessMissing = allFilesAccessMissing,
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
forceSsbs = forceSsbs,
@@ -2083,7 +2219,7 @@ class FrontEndActivity : ComponentActivity() {
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
startupSession = startupSession,
bootMovie = if (mode == SessionService.MODE_STEAM) bootMovie else null,
bootMovieSound = bootMovieSound,
bootMovieCustomName = bootMovieCustomName,
@@ -2118,6 +2254,7 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on
},
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onBackHold = { on -> SessionPrefs.setBackHold(this, on); backHold = on },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
backActionsInverted = inverted
@@ -2136,6 +2273,22 @@ class FrontEndActivity : ComponentActivity() {
onPickGameStorageFolder = {
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null }))
},
onAddSteamLibrary = {
pickSteamLibrary.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.libraries_pick), null))
},
onAddFoundSteamLibrary = { path -> addSteamLibrary(path) },
onAllowAllFilesAccess = { com.droiddeck.launcher.files.AllFilesAccess.open(this) },
onRenameSteamLibrary = { id, label ->
SteamLibraries.rename(this, id, label)
steamLibraries = SteamLibraries.list(this)
refresh()
},
onRemoveSteamLibrary = { id ->
SteamLibraries.remove(this, id)
steamLibraries = SteamLibraries.list(this)
refresh()
refreshFoundSteamLibraries()
},
onStorageDiagnostics = { on ->
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
storageDiagnostics = on
@@ -2159,9 +2312,9 @@ class FrontEndActivity : ComponentActivity() {
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on
onStartupSession = { id ->
SessionPrefs.setStartupSession(this, id)
startupSession = id
},
onBootMovie = { id -> com.droiddeck.launcher.session.BootMovie.select(this, id); loadBootMovie() },
onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on },
@@ -2352,7 +2505,7 @@ class FrontEndActivity : ComponentActivity() {
returnAfterGame = SessionPrefs.returnAfterGame(this)
loadShaderPrecache(mode)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
startupSession = SessionPrefs.startupSession(this)
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
upscaler = SessionPrefs.upscaler(this)
@@ -2362,6 +2515,7 @@ class FrontEndActivity : ComponentActivity() {
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
backHold = SessionPrefs.backHold(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
picturePosition = SessionPrefs.picturePosition(this)
@@ -2369,6 +2523,8 @@ class FrontEndActivity : ComponentActivity() {
mic = SessionPrefs.micEnabled(this)
refreshWifiDiscovery()
gameStorage = SessionPrefs.gameStorage(this)
steamLibraries = SteamLibraries.list(this)
if (mode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
Thread({
@@ -2399,6 +2555,7 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setGameStorage(this, path, label)
gameStorage = path
checkUsbLink()
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
}
private fun checkUsbLink() {
@@ -2422,6 +2579,9 @@ class FrontEndActivity : ComponentActivity() {
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
tuSysmem = SessionPrefs.tuSysmem(this)
zinkLazy = SessionPrefs.zinkLazy(this)
vkBridge = SessionPrefs.vkBridge(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
noXalia = SessionPrefs.noXalia(this)
fastSync = SessionPrefs.fastSync(this)
syncFallback = SessionPrefs.syncFallback(this)
@@ -2443,7 +2603,6 @@ class FrontEndActivity : ComponentActivity() {
!SessionPaths.currentSessionLogsRetained(this)
private fun refresh() {
// Until the scan finishes, the other client's games would launch in this one.
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
steamGamesX64 = listX64
@@ -2459,6 +2618,9 @@ class FrontEndActivity : ComponentActivity() {
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
vkBridge = SessionPrefs.vkBridge(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
frameGenLabel = FrameGen.label(this)
@@ -2503,7 +2665,7 @@ class FrontEndActivity : ComponentActivity() {
}
val scannedArch = SessionPrefs.activeSteamClientArch(this)
val scannedX64 = scannedArch == "x86_64"
val games = if (ready) Library.launchableGames(this, arch = scannedArch) else emptyList()
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
@@ -2563,7 +2725,7 @@ class FrontEndActivity : ComponentActivity() {
Thread({ checkCatalog() }, "catalog").start()
return
}
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)) { showNonAdreno = release; return }
install(release)
}
@@ -2582,7 +2744,7 @@ class FrontEndActivity : ComponentActivity() {
showPhantomGate = true
return false
}
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)
if (warn && available != null) { showNonAdreno = available; return false }
startActivity(intent)
return true
@@ -2704,6 +2866,8 @@ class FrontEndActivity : ComponentActivity() {
}
companion object {
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
private const val COMPONENT_RESTORE_MS = 60_000L
@@ -24,6 +24,9 @@ import kotlin.math.roundToInt
object HomeApp {
private const val ICON_DP = 72
private const val GAME_SPACE = "cn.nubia.gamelauncher"
private const val GAME_SPACE_ADD = "cn.nubia.gamelauncher.action.GAME_MANAGER"
private val GAME_SPACE_GAMES = Uri.parse("content://cn.nubia.gamelauncher.db.AppAddProvider/appadd")
data class LaunchableApp(
val label: String,
@@ -54,6 +57,24 @@ object HomeApp {
)
}
fun hasGameSpace(context: Context): Boolean =
runCatching { context.packageManager.getPackageInfo(GAME_SPACE, 0) }.isSuccess
fun inGameSpace(context: Context): Boolean =
runCatching {
context.contentResolver.query(GAME_SPACE_GAMES, arrayOf("component"), null, null, null)?.use { rows ->
val prefix = context.packageName + ","
generateSequence { if (rows.moveToNext()) rows.getString(0) else null }.any { it.startsWith(prefix) }
}
}.getOrNull() ?: true
fun gameSpaceAddIntent(): Intent = Intent(GAME_SPACE_ADD).setPackage(GAME_SPACE)
fun releaseUnusedHomeEntry(context: Context) {
if (isHomeScreenEnabled(context) && !isDefault(context) && hasGameSpace(context))
setHomeScreenEnabled(context, false)
}
fun isDefault(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val roles = context.getSystemService(RoleManager::class.java)
@@ -147,8 +168,62 @@ object HomeApp {
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
}.getOrNull()
fun trackRecents(app: android.app.Application) {
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
override fun onActivityStarted(activity: android.app.Activity) = Unit
override fun onActivityResumed(activity: android.app.Activity) = syncRecents(activity)
override fun onActivityPaused(activity: android.app.Activity) { if (activity is FrontEndActivity) syncRecents(activity) }
override fun onActivityStopped(activity: android.app.Activity) = Unit
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
})
}
private fun syncRecents(activity: android.app.Activity) =
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
internal fun recentsStep(hidden: Boolean, owned: Boolean, excluded: Boolean): RecentsStep = when {
hidden && !excluded -> RecentsStep.HIDE
!hidden && owned && excluded -> RecentsStep.SHOW
!hidden && owned -> RecentsStep.FORGET
else -> RecentsStep.NONE
}
fun keepOutOfRecents(activity: android.app.Activity, hidden: Boolean) {
val prefs = activity.getSharedPreferences("home-recents", Context.MODE_PRIVATE)
val owned = prefs.getStringSet("tasks", null).orEmpty()
val id = activity.taskId.toString()
if (!hidden && id !in owned) return
runCatching {
@Suppress("DEPRECATION")
fun idOf(task: android.app.ActivityManager.AppTask) =
if (Build.VERSION.SDK_INT >= 29) task.taskInfo.taskId else task.taskInfo.persistentId
val tasks = activity.getSystemService(android.app.ActivityManager::class.java).appTasks
val task = tasks.firstOrNull { idOf(it) == activity.taskId } ?: return
val excluded = task.taskInfo.baseIntent.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS != 0
val step = recentsStep(hidden, id in owned, excluded)
if (step == RecentsStep.NONE) return
if (step != RecentsStep.FORGET) task.setExcludeFromRecents(step == RecentsStep.HIDE)
val live = tasks.map { idOf(it).toString() }.toSet()
val next = owned.filter { it in live && it != id }.toMutableSet()
if (step == RecentsStep.HIDE) next += id
prefs.edit().putStringSet("tasks", next).apply()
}
}
fun startShortcut(context: Context, info: ShortcutInfo) {
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
val task = generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }
.filterIsInstance<android.app.Activity>().firstOrNull()?.taskId
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, true) }
try {
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
} catch (e: Exception) {
task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, false) }
throw e
}
}
fun openAppInfo(context: Context, app: LaunchableApp) {
@@ -12,7 +12,6 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */
object HomePins {
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
@@ -197,7 +197,6 @@ object HomeWidgets {
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
}
/** Places a widget another app asked for; its own app has already configured it. */
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
val info = request.getAppWidgetProviderInfo(activity) ?: return false
@@ -20,7 +20,6 @@ internal class ProtonMenu(
private val ui: Handler,
private val idle: () -> Boolean = { true },
) {
// Install workers and their results outlive the activity that starts them.
private object Operation {
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
val busyId = mutableStateOf<String?>(null)
@@ -71,7 +71,6 @@ class QuestXrActivity : NativeActivity() {
}
} finally {
synchronized(steamVrLock) {
// A retiring activity must not stop a replacement's SteamVR session.
if (steamVrOwner === this) {
if (sessionAlive()) SteamVr.run(this, "stop")
steamVrOwner = null
File diff suppressed because it is too large. Load diff
@@ -18,7 +18,6 @@ object AgentEnv {
private const val TAG = "AgentEnv"
private const val FILE = "agent-env.json"
private const val GUEST_BIN = "/opt/droiddeck-agent/bin"
private const val BASE_PATH = "/usr/local/bin:/usr/bin:/bin"
private val NAME = Regex("[A-Za-z0-9._-]{1,64}")
private val KEY = Regex("[A-Za-z_][A-Za-z0-9_]*")
private val lock = Any()
@@ -160,7 +159,7 @@ object AgentEnv {
}
private fun pathOf(lines: List<String>) =
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: BASE_PATH
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH
private fun bin(context: Context): File {
val root = LinuxRuntime.rootDir(context).canonicalFile.toPath()
@@ -118,7 +118,6 @@ public class DirectAudioRelayComponent extends SessionPart {
}
}
// Android keeps the input stream's wake lock while a frozen helper still has it started.
public boolean awaitMicReleased(long timeoutMs) {
long deadline = System.currentTimeMillis() + timeoutMs;
synchronized (micLock) {
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.audio
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import android.util.Log
object DirectAudioTiming {
private const val TAG = "DirectAudioTiming"
const val PERIOD_ENV = "AUDIO_DIRECT_PERIOD_MS"
const val BUFFER_ENV = "AUDIO_DIRECT_MS"
const val SLOW_OUTPUT_PERIOD_MS = 20
const val SLOW_OUTPUT_BUFFER_MS = 60
fun environment(lowLatencyOutput: Boolean): List<String> =
if (lowLatencyOutput) emptyList()
else listOf("$PERIOD_ENV=$SLOW_OUTPUT_PERIOD_MS", "$BUFFER_ENV=$SLOW_OUTPUT_BUFFER_MS")
fun lowLatencyOutput(): Boolean = try {
val track = AudioTrack.Builder()
.setAudioAttributes(AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build())
.setAudioFormat(AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
.setSampleRate(48000)
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
.build())
.setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY)
.setTransferMode(AudioTrack.MODE_STREAM)
.build()
try {
track.performanceMode == AudioTrack.PERFORMANCE_MODE_LOW_LATENCY
} finally {
track.release()
}
} catch (e: Exception) {
Log.w(TAG, "audio: could not check for low-latency output; DirectAudio keeps its defaults", e)
true
}
}
@@ -13,15 +13,10 @@ import kotlinx.coroutines.launch
import java.io.File
import java.io.FileInputStream
/**
* A pack built by CI alongside this APK (tools/packs). Main and release builds publish it to
* DroidDeck-Components under a content-addressed tag; a PR test build attaches packs that are not there
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
* was made with install, whichever host serves them.
*/
internal class AddonPack(
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
) {
sealed interface State {
data object Missing : State
@@ -42,13 +37,11 @@ internal class AddonPack(
)
private fun root(context: Context) = File(context.filesDir, "addons/$name")
/** App-private and written only after the archive matched the pinned digest. */
fun dir(context: Context) = File(root(context), version(context))
fun file(context: Context, relative: String) = File(dir(context), relative)
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
// A build made outside CI pins no packs, so it runs the newest one a CI build already verified and installed.
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
@@ -65,7 +58,6 @@ internal class AddonPack(
.also { mutableState.value = it }
}
/** Starts the download in the background unless the pack is already present or on its way. */
fun ensure(context: Context, onReady: (Context) -> Unit = {}) {
val app = context.applicationContext
synchronized(lock) {
@@ -80,7 +72,6 @@ internal class AddonPack(
}
}
/** Blocks a worker thread until the pack is installed, starting the download if needed. */
@JvmOverloads
fun await(context: Context, running: () -> Boolean = { true }, onState: (State) -> Unit = {}): Boolean {
if (installed(context)) return true
@@ -104,7 +95,7 @@ internal class AddonPack(
}
val root = root(context).apply { mkdirs() }
val archive = File(root, "$sha256.tar.zst")
val downloaded = urls.any { url ->
val downloaded = bundled(context, archive) || urls.any { url ->
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
.also { if (!it) archive.delete() }
}
@@ -126,6 +117,16 @@ internal class AddonPack(
return true
}
internal fun bundled(context: Context, archive: File): Boolean {
val copied = runCatching {
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
}.isSuccess
if (copied && Hashes.sha256(archive).equals(sha256, ignoreCase = true)) return true
if (copied) Log.w(TAG, "$name: the bundled pack does not match the pinned digest")
archive.delete()
return false
}
companion object {
private const val TAG = "AddonPack"
private const val REPO = "Droid-Deck/DroidDeck-Components"
@@ -42,7 +42,6 @@ object DeviceReport {
}
}
/** Name of an ApplicationExitInfo reason code, so a report says "LOW_MEMORY" instead of "3". */
internal fun exitReasonName(reason: Int): String = when (reason) {
0 -> "UNKNOWN"
1 -> "EXIT_SELF"
@@ -209,7 +208,7 @@ object DeviceReport {
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
if (gpu.model == 740) {
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
@@ -6,8 +6,20 @@ import com.droiddeck.launcher.R
import java.io.File
object DeviceSupport {
fun adreno(): Boolean =
private val adrenoGpu by lazy {
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
}
private val maliGpu by lazy { !adrenoGpu && File("/dev/mali0").exists() }
fun adreno(): Boolean = adrenoGpu
fun mali(): Boolean = maliGpu
fun vkBridge(context: Context): Boolean =
!adreno() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
fun canDraw(context: Context): Boolean = adreno() || vkBridge(context)
fun gpuName(context: Context): String {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
@@ -126,11 +126,9 @@ object DownloadSource {
fun isGithub(url: String): Boolean = GITHUB_HOSTS.any { url.startsWith("https://$it/") }
/** Catalogs carry the digests everything else is checked against, so a mirror must never supply one. */
fun isCatalog(url: String): Boolean = CATALOGS.any { url.startsWith(it) }
fun candidates(target: String): List<String> {
// GitHub API metadata carries executable URLs and digests; never proxy it.
if (isCatalog(target) || target.startsWith("https://api.github.com/")) return listOf(target)
val prefs = prefs() ?: return listOf(target)
if (!isGithub(target)) return listOf(target)
@@ -184,7 +182,6 @@ object DownloadSource {
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
}
/** An HTTP proxy every Downloader connection uses, or null when none is configured. */
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
internal fun proxyOf(value: String): Proxy? {
@@ -91,7 +91,6 @@ public final class Downloader {
if (isCancelled(cancelled)) return null;
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
Fetch fetch = fetch(sources.get(i), cancelled);
// A cancelled fetch says nothing about the source, so it must not count as a failure.
if (isCancelled(cancelled)) return null;
if (fetch.body != null) {
DownloadSource.INSTANCE.succeeded(sources.get(i));
@@ -103,7 +102,6 @@ public final class Downloader {
return null;
}
/** Fetches without the mirror list, for a URL whose body is a digest the payload is checked against. */
public static String downloadDirect(String url) {
return fetch(url).body;
}
@@ -113,13 +111,11 @@ public final class Downloader {
return downloadFile(url, destination, resume, null, progress);
}
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.Consumer<Float> progress) {
return downloadFile(url, destination, resume, expectedSha256, null, progress);
}
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
@@ -128,13 +124,11 @@ public final class Downloader {
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
}
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
static List<String> sources(String url, String expectedSha256) {
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
}
// Package-private for the local multi-source HTTP test.
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.Consumer<Float> progress) {
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
@@ -149,7 +143,6 @@ public final class Downloader {
if (isCancelled(cancelled)) return false;
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
if (outcome == Outcome.CANCELLED) return false;
if (outcome == Outcome.DONE) {
if (expectedSha256 != null) {
@@ -192,7 +185,6 @@ public final class Downloader {
return value != null && !value.isEmpty() && !value.startsWith("W/");
}
/** Only reuse saved bytes when we persisted a strong validator and their source. */
private static Identity loadIdentity(File dest, boolean resume, String expectedSha256) {
Identity identity = new Identity();
File marker = resumeFile(dest);
@@ -213,7 +205,6 @@ public final class Downloader {
return identity;
}
} catch (IOException e) {
// Legacy partials or interrupted metadata writes have no trustworthy identity.
}
if (!discardPartial(dest, identity)) Log.w(TAG, "could not discard unidentified partial " + dest);
return identity;
@@ -239,7 +230,7 @@ public final class Downloader {
try (FileOutputStream out = new FileOutputStream(marker)) {
p.store(out, "DroidDeck partial download validator");
} catch (IOException e) {
marker.delete(); // No valid metadata means no future resume.
marker.delete();
Log.w(TAG, "cannot persist download validator", e);
}
}
@@ -252,7 +243,6 @@ public final class Downloader {
long have = resume && destination.isFile() ? destination.length() : 0;
try {
if (have > 0 && (!url.equals(identity.source) || !strongETag(identity.etag))) {
// A new source or unvalidated bytes must restart from byte zero.
if (!discardPartial(destination, identity)) return Outcome.RETRY;
have = 0;
}
@@ -286,7 +276,6 @@ public final class Downloader {
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (!appending && have > 0) {
// If-Range may legitimately return full 200 when representation changed.
if (!discardPartial(destination, identity)) return Outcome.RETRY;
have = 0;
}
@@ -333,14 +322,12 @@ public final class Downloader {
}
}
/** True when a `Content-Range: bytes START-END/TOTAL` header starts exactly at {@code start}. */
static boolean rangeStartsAt(String contentRange, long start) {
if (contentRange == null) return false;
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+(\\d+)-\\d+/(?:\\d+|\\*)\\s*$").matcher(contentRange);
return m.matches() && Long.parseLong(m.group(1)) == start;
}
/** The complete length in a `Content-Range` header, or -1 when the header leaves it unknown. */
static long rangeTotal(String contentRange) {
if (contentRange == null) return -1;
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*bytes\\s+\\d+-\\d+/(\\d+)\\s*$").matcher(contentRange);
@@ -390,7 +377,6 @@ public final class Downloader {
}
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
// An explicit Proxy routes the connection through the app setting instead of the system-wide proxy.
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
HttpURLConnection connection = (HttpURLConnection) (proxy != null
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
@@ -34,6 +34,8 @@ object GameEnvironmentOptions {
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
Option("AUDIO_DIRECT_MS", "", 0, Type.NUMBER),
Option("AUDIO_DIRECT_PERIOD_MS", "", 0, Type.NUMBER),
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
@@ -5,7 +5,6 @@ import android.net.Uri
import android.provider.Settings
object GlobalSettings {
// Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly.
fun read(context: Context, name: String): String? {
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
@@ -19,6 +18,5 @@ object GlobalSettings {
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
// Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11.
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
}
@@ -11,7 +11,6 @@ object LogRedactor {
size > 32
}
// Android matchers own native state, so reuse them instead of creating one for every log line.
private val matchers = object : ThreadLocal<MatcherCache>() {
override fun initialValue(): MatcherCache = MatcherCache()
}
@@ -145,7 +144,6 @@ object LogRedactor {
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
}
// A file that could not be read keeps the names learned from it before.
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
}
@@ -228,7 +226,6 @@ object LogRedactor {
return out
}
/** The at-rest rewrite reads a file into memory twice; larger logs are only scrubbed on the way out. */
const val IN_MEMORY_SCRUB_MAX = 64L * 1024 * 1024
fun isBinary(file: java.io.File): Boolean = try {
@@ -241,8 +238,6 @@ object LogRedactor {
true
}
fun isText(file: java.io.File): Boolean = file.isFile && file.length() < IN_MEMORY_SCRUB_MAX && !isBinary(file)
const val RULES_VERSION = 3
private val LAN_IPV4 = Regex(
@@ -52,8 +52,6 @@ object SessionLogCapture {
if (t.parentFile?.absolutePath == dir.absolutePath) stop()
}
/** flush() only reaches the page cache, and a hard reset on f2fs lost the last minutes of every
* log. Every 2 s the session folder's files (ours and the native parts') are synced to storage. */
private fun startSyncing(dir: File): Thread = Thread({
while (true) {
try { Thread.sleep(2000) } catch (e: InterruptedException) { break }
@@ -0,0 +1,11 @@
package com.droiddeck.launcher.core
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class ShortcutsListingReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
}
}
@@ -4,6 +4,7 @@ import android.accessibilityservice.AccessibilityServiceInfo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.view.accessibility.AccessibilityManager
@@ -44,8 +45,6 @@ object SteamIntegration {
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
// Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info.
// MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here.
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
@@ -55,6 +54,33 @@ object SteamIntegration {
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
}
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
private fun shortcutsSelection(context: Context): Boolean? {
val target = shortcutsComponent(context)
val enabled = runCatching {
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
}.getOrElse { return null }.orEmpty()
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
}
fun setShortcutsListed(context: Context, listed: Boolean) {
val packages = context.packageManager
val component = shortcutsComponent(context)
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
runCatching {
if (packages.getComponentEnabledSetting(component) != state) {
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
}
}
}
fun syncShortcutsListing(context: Context) {
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
}
fun dismissSuggestion(context: Context) {
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
}
@@ -62,7 +88,6 @@ object SteamIntegration {
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:${context.packageName}"))
// ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list.
fun shortcutSettings(context: Context): Intent {
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
@@ -0,0 +1,21 @@
package com.droiddeck.launcher.files
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
object AllFilesAccess {
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
sdk >= Build.VERSION_CODES.R && !granted()
fun open(context: Context) {
val app = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + context.packageName))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { context.startActivity(app) }.recoverCatching {
context.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
@@ -311,87 +311,3 @@ fun CollapsibleRail(
}
}
@Composable
fun RailTopTabs(
items: List<RailItem>,
modifier: Modifier = Modifier,
links: List<RailLink> = emptyList(),
) {
Column(modifier = modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
items.forEach { item ->
TopTabCell(
icon = item.icon,
label = item.label,
selected = item.selected,
onClick = item.onClick,
modifier = Modifier.weight(1f),
)
}
if (links.isNotEmpty()) {
Box(
modifier = Modifier
.padding(horizontal = 2.dp)
.width(1.dp)
.height(30.dp)
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
)
links.forEach { link ->
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f))
}
}
}
HorizontalDivider()
}
}
@Composable
private fun TopTabCell(
icon: ImageVector,
label: String,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
isTab: Boolean = true,
) {
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
.clip(RoundedCornerShape(9.dp))
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
.focusGlide(RoundedCornerShape(9.dp))
.then(
if (isTab) {
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
} else {
Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
},
)
.padding(vertical = 6.dp, horizontal = 1.dp),
) {
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
Spacer(Modifier.height(3.dp))
Text(
label,
color = tint,
fontSize = 8.5.sp,
fontWeight = FontWeight.Bold,
letterSpacing = 0.2.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(2.dp))
Box(
modifier = Modifier
.height(2.dp)
.width(if (selected) 16.dp else 0.dp)
.clip(RoundedCornerShape(3.dp))
.background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent),
)
}
}
@@ -498,6 +498,25 @@ fun FileManagerScreen(
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
val drives = remember(storageTick) { StorageRoots.list(context) }
var accessDrive by remember { mutableStateOf<String?>(null) }
fun unreadable(drive: StorageRoot) {
if (AllFilesAccess.missing()) accessDrive = drive.label
else Toast.makeText(context, context.getString(R.string.fm_drive_not_readable, drive.label), Toast.LENGTH_SHORT).show()
}
accessDrive?.let { label ->
OutlinedAlertDialog(
onDismissRequest = { accessDrive = null },
title = { Text(stringResource(R.string.fm_drive_access_title, label)) },
text = { Text(stringResource(R.string.fm_drive_access_text)) },
confirmButton = {
TextButton(onClick = {
accessDrive = null
AllFilesAccess.open(context)
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) }
},
dismissButton = { TextButton(onClick = { accessDrive = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
val linuxRoot = remember(storageTick) {
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
}
@@ -747,11 +766,7 @@ fun FileManagerScreen(
if (drive.readable) {
openDrive(drive.dir)
} else {
Toast.makeText(
context,
context.getString(R.string.fm_drive_not_readable, drive.label),
Toast.LENGTH_SHORT,
).show()
unreadable(drive)
}
},
modifier = Modifier.focusGlide(),
@@ -1072,7 +1087,7 @@ fun FileManagerScreen(
add(locItem(stringResource(R.string.fm_drive_internal), Icons.Filled.Smartphone, File("/storage/emulated/0")))
drives.filter { it.removable }.forEach { d ->
add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) {
showFavorites = false; if (d.readable) openDrive(d.dir)
showFavorites = false; if (d.readable) openDrive(d.dir) else unreadable(d)
})
}
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
@@ -57,7 +57,6 @@ object FileOps {
return true
}
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
// Once the destination is committed, finish deleting the source.
return delete(src)
}
@@ -63,7 +63,6 @@ object StorageRoots {
}
return true
}
// vold-managed locations only hold removable volumes, whatever the fstype is.
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
}
@@ -92,8 +91,6 @@ object StorageRoots {
.forEachIndexed { index, volume ->
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
val dirName = volume.directory?.name?.takeIf { it.isNotBlank() }
// Unmounted volumes often report neither uuid nor directory; never drop the
// volume or a plugged-in drive stays invisible with no explanation.
val descSlug = volume.getDescription(context)?.trim()
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
@@ -108,8 +105,6 @@ object StorageRoots {
if (name != null) {
entry.candidates += File("/storage/$name")
entry.candidates += File("/mnt/media_rw/$name")
// Only strict uuid matches own an app directory; a loose match would
// attach another volume's folder to this entry.
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
.forEach { entry.seeds += it }
}
@@ -122,8 +117,6 @@ object StorageRoots {
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
if (child.isDirectory) volumeOf(child.name).candidates += child
}
// USB OTG drives do not always appear as storage volumes or under /storage for
// third-party apps, but their kernel mounts are still visible in /proc/mounts.
for (mount in externalMounts()) {
val entry = volumeOf(mount.name)
if (entry.label == null) entry.label = mount.name
@@ -243,6 +243,8 @@ object AddedGameArt {
val steam: (String, File, Set<Slot>) -> Boolean,
val sgdbGame: (String, Int?, String) -> Int?,
val sgdb: (String, Int, File, Set<Slot>) -> Boolean,
val sgdbExactGame: (String, Int?, String) -> Int? = { _, _, _ -> null },
val battleNetArt: (Context, BattleNet.Title) -> Boolean = { _, _ -> false },
)
private val network = Sources(
@@ -251,6 +253,8 @@ object AddedGameArt {
steam = ::download,
sgdbGame = SteamGridDb::gameId,
sgdb = SteamGridDb::download,
sgdbExactGame = SteamGridDb::exactGameId,
battleNetArt = { context, title -> BattleNet.fetchCovers(context, listOf(BattleNet.artTitle(title))) },
)
private val EXTRAS = setOf(Slot.LOGO, Slot.ICON)
@@ -287,14 +291,20 @@ object AddedGameArt {
var sgdbDown = false
var changed = false
for (game in games) {
if (forgetOtherAppsArt(context, game)) changed = true
if (forgetNameMatchedBattleNetArt(context, game)) changed = true
val battleNetTitle = game.storeId?.takeIf { game.source == Store.BATTLENET.id }?.let(BattleNet::title)
if (battleNetTitle != null && runCatching { sources.battleNetArt(context, battleNetTitle) }.getOrDefault(false)) changed = true
val cache = cacheDir(context, game)
val start = missing(context, game)
val again = refetch(cache) intersect start
if (again.isEmpty()) File(cache, REFETCH).delete()
val full = Slot.COVER in start
val allowed = if (full) Slot.values().toSet() else EXTRAS
val allowed = if (full) Slot.values().toSet() else EXTRAS + again
var need = start intersect allowed
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
val cache = cacheDir(context, game)
val tried = File(cache, EXTRAS_TRIED)
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
if (!full && again.isEmpty() && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
cache.mkdirs()
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
changed = true
@@ -315,7 +325,7 @@ object AddedGameArt {
if (need.isNotEmpty() && sgdbKey.isNotEmpty()) {
if (sgdbDown) asked = false else try {
val gridId = remembered(File(cache, "sgdb-id"), keyChangedAt) {
sources.sgdbGame(sgdbKey, match.appId, game.name)?.toString()
(if (battleNetTitle != null) sources.sgdbExactGame else sources.sgdbGame)(sgdbKey, match.appId, game.name)?.toString()
}?.toIntOrNull()
if (gridId != null && sources.sgdb(sgdbKey, gridId, cache, need)) changed = true
} catch (e: Exception) {
@@ -324,11 +334,57 @@ object AddedGameArt {
asked = false
}
}
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
val left = missing(context, game)
if (again.isNotEmpty()) keepRefetch(cache, again intersect left)
if ((left intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
}
return changed
}
internal const val REFETCH = "refetch"
private fun refetch(cache: File): Set<Slot> =
runCatching { File(cache, REFETCH).readText() }.getOrDefault("").split(',').mapNotNull { key -> Slot.values().firstOrNull { it.key == key } }.toSet()
private fun keepRefetch(cache: File, slots: Set<Slot>) {
if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key })
}
internal const val BATTLENET_ART_CHECKED = "battlenet-art-2"
internal fun forgetNameMatchedBattleNetArt(context: Context, game: AddedGames.Game): Boolean {
val title = game.storeId?.takeIf { game.source == Store.BATTLENET.id }?.let(BattleNet::title) ?: return false
val cache = cacheDir(context, game)
val checked = File(cache, BATTLENET_ART_CHECKED)
if (title.steam != null || checked.isFile) return false
val dropped = EXTRAS.filter { File(cache, SteamGridDb.cacheName(it)).delete() }
EXTRAS.forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
listOf("sgdb-id", EXTRAS_TRIED).forEach { File(cache, it).delete() }
cache.mkdirs()
checked.writeText("")
return dropped.isNotEmpty()
}
internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean {
val cache = cacheDir(context, game)
val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null }
val legacy = runCatching { File(cache, "steam-appid").readText().trim().toInt() }.getOrNull()?.takeIf { it > 0 }
val before = recorded?.appId ?: legacy ?: return false
val identity = runCatching { GameIdentifier.identify(game.exe) }.getOrNull()
val now = identity?.appId
val fromFiles = recorded?.certainty == SteamMatch.Certainty.FILES || before == GameIdentifier.SPACEWAR
if (now == before || (now == null && !fromFiles)) return false
SteamMatch.put(context, game.folder.path,
if (identity != null && now != null) SteamMatch.Match(now, SteamMatch.Certainty.FILES, identity.source.name.lowercase(), System.currentTimeMillis())
else SteamMatch.Match(null, SteamMatch.Certainty.NONE, "", 0))
val dropped = Slot.values().filter { File(cache, SteamGridDb.cacheName(it)).delete() }.toSet()
Slot.values().forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
listOf("sgdb-id", "steam-appid", EXTRAS_TRIED).forEach { File(cache, it).delete() }
keepRefetch(cache, refetch(cache) + dropped)
Log.i(TAG, "${game.name}: its files no longer name Steam app $before; its art is fetched again")
return dropped.isNotEmpty()
}
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
if (game.source == Store.BATTLENET.id) {
val id = game.storeId?.let(BattleNet::title)?.steam
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
@@ -69,6 +70,10 @@ object AddedGames {
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
}
StoreInstallRoot.externalGuestPath(context, host)?.let { return it }
for (lib in SteamLibraries.list(context)) {
if (path == lib.path) return lib.guest
if (path.startsWith("${lib.path}/")) return lib.guest + "/" + path.removePrefix("${lib.path}/")
}
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
}
@@ -83,6 +88,7 @@ object AddedGames {
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
SteamLibraries.list(context).map { it.host to it.guest } +
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
if (guest == root) return host
@@ -170,9 +176,9 @@ object AddedGames {
val files = folder.listFiles() ?: return null
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
if (declaredExes(folder).isNotEmpty()) return null
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") }.sortedBy { it.name.lowercase() }
if (dirs.size < 2 || dirs.any { it.name.lowercase() in GAME_PARTS }) return null
return dirs.takeIf { all -> all.all { rank(it).exes.isNotEmpty() } }
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") && !isSteamLibraryFolder(it.name) }.sortedBy { it.name.lowercase() }
if (dirs.any { it.name.lowercase() in GAME_PARTS || GameExePicker.auxiliaryDir(it) }) return null
return dirs.filter { rank(it).exes.isNotEmpty() }.takeIf { it.size >= 2 }
}
private fun expand(folder: File, entries: Set<String>): List<File> =
@@ -180,7 +186,9 @@ object AddedGames {
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
private fun libraryDepotInstalls(context: Context): List<File> =
SteamLibraries.list(context).flatMap { SteamLibraries.depotInstalls(File(it.path, "steamapps/common")) }
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
@@ -208,6 +216,7 @@ object AddedGames {
if (folder.path in removed || !folder.isDirectory) continue
scanGame(context, folder, out, single = entry)
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
@@ -254,6 +263,7 @@ object AddedGames {
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.filter { owns(it) && groupGames(it) == null }.maxByOrNull { canonical(it).length }?.let { return it }
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
libraryDepotInstalls(context).firstOrNull(::holds)?.let { return it }
val removed = SessionPrefs.removedAddedGames(context)
val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
@@ -315,7 +325,6 @@ object AddedGames {
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}, showHidden: Boolean = false): FolderResult {
val app = context.applicationContext
// Binds are mounted at session start, so a new one reaches the session from the next start.
if (guestPath(app, dir) == null) bindFolder(app, dir)
val removed = SessionPrefs.removedAddedGames(app).toSet()
val listed = listedFolders(app, removed)
@@ -372,6 +381,7 @@ object AddedGames {
}
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
StoreInstallRoot.gameFolders(context).forEach { out.add(canonical(it)) }
libraryDepotInstalls(context).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
return out
}
@@ -416,7 +426,14 @@ object AddedGames {
?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) }
val exe = adopted ?: found
val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest
val storeExe = sidecar?.exeFile(folder)
val launched = adopted ?: chosen ?: storeExe?.takeIf { it.isFile }
val storeOwnExe = launched != null && storeExe != null && canonical(launched) == canonical(storeExe)
val sidecarDir = sidecar?.workdir?.takeIf { storeOwnExe }?.let { dir ->
guestPath(context, if (dir.isEmpty()) folder else File(folder, dir))
}
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
?: sidecarDir
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
val steamId = config?.let { steamRoute(it, appId) }
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
@@ -111,10 +111,7 @@ object AutoComponents {
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
p.name.all(Char::isDigit) && runCatching { String(File(p, "cmdline").readBytes()).replace('\u0000', ' ') }.getOrNull()
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
} == true
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
fun queueInSession(context: Context, game: Library.SteamGame) {
if (appKey(game) == null) return
@@ -54,21 +54,6 @@ object DependencyDetector {
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
)
fun detectForExe(exeFile: File): List<Recommendation> {
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
var d: File? = start
var depth = 0
while (d != null && depth < 4) {
val hasRedistContainer = try {
d.listFiles()?.any { it.isDirectory && REDIST_DIR_RE.matches(it.name.lowercase(Locale.US)) } == true
} catch (_: Throwable) { false }
if (hasRedistContainer) return detect(d)
d = d.parentFile
depth++
}
return detect(start)
}
fun detect(gameDir: File): List<Recommendation> {
if (!gameDir.isDirectory) return emptyList()
val hits = LinkedHashMap<String, Recommendation>()
@@ -89,6 +89,8 @@ object GameExePicker {
return score
}
internal fun auxiliaryDir(dir: File): Boolean = skipDir(dir, dir.name)
private fun skipDir(dir: File, relative: String): Boolean {
val name = dir.name.lowercase().trim()
if (name in SKIP_DIRS || SKIP_DIR_PREFIX.any { name.startsWith(it) }) return true
@@ -5,6 +5,7 @@ import java.io.File
object GameIdentifier {
private const val MAX_PARENT_DEPTH = 6
internal const val SPACEWAR = 480
enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE }
enum class Confidence { HIGH, MEDIUM, LOW }
@@ -92,7 +93,7 @@ object GameIdentifier {
for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) {
val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim()
?.takeWhile { it.isDigit() }?.toIntOrNull()
if (id != null && id > 0) return id
if (id != null && id > 0 && id != SPACEWAR) return id
}
return null
}
@@ -111,7 +112,7 @@ object GameIdentifier {
for (f in candidates) {
val text = readSmallTextFile(f) ?: continue
val id = re.find(text)?.groupValues?.getOrNull(1)?.toIntOrNull()
if (id != null && id > 0) return id
if (id != null && id > 0 && id != SPACEWAR) return id
}
return null
}
@@ -133,7 +134,8 @@ object GameIdentifier {
val match = manifests.firstOrNull { m ->
val text = readSmallTextFile(m) ?: return@firstOrNull false
val installdir = vdfValue(text, "installdir")
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true)
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true) &&
vdfValue(text, "appid")?.toIntOrNull() != SPACEWAR
} ?: return null
val text = readSmallTextFile(match) ?: return null
@@ -24,15 +24,33 @@ object GamesFolderMigration {
for (root in roots) {
var n = 0
val steamInstalls = AddedGames.steamInstallDirs(root.host)
for (folder in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
if (AddedGames.isSteamLibraryFolder(folder.name) || folder.name.lowercase() in steamInstalls) continue
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
if (folder.path in entries) continue
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val exe = picked ?: AddedGames.rank(folder).exes.firstOrNull() ?: continue
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null))
entries.add(folder.path)
if (folder.path !in removed) n++
for (top in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
if (AddedGames.isSteamLibraryFolder(top.name) || top.name.lowercase() in steamInstalls) continue
if (top.absolutePath in storeRoots || StoreGameSidecar.read(top) != null) continue
if (top.path in entries) continue
val topPick = SessionPrefs.addedGameExe(context, top.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val groups = AddedGames.groupGames(top)
val played = topPick ?: groups?.let { AddedGames.rank(top).exes.firstOrNull() }
val owner = played?.let { exe -> top.listFiles { f -> f.isDirectory }?.firstOrNull { exe.path.startsWith(it.path + File.separator) } }
val folders = when {
groups == null -> listOf(top)
topPick == null || owner in groups -> groups
owner == null || owner.name.startsWith(".") || AddedGames.isSteamLibraryFolder(owner.name) -> listOf(top)
else -> (groups + owner).sortedBy { it.name.lowercase() }
}
for (folder in folders) {
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
if (folder.path in entries) continue
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: topPick?.takeIf { it.path.startsWith(folder.path + File.separator) }
val ranked = AddedGames.rank(folder).exes.firstOrNull()
val exe = picked ?: played?.takeIf { folder == owner } ?: ranked ?: continue
AddedExes.put(context, AddedExes.Entry(folder.path, exe.path, picked = picked != null || exe != ranked))
entries.add(folder.path)
if (folder != top && folder == owner) SessionPrefs.inheritAddedGame(context, top.path, folder.path)
if (folder != top && top.path in removed) SessionPrefs.setAddedGameRemoved(context, folder.path, true)
else if (folder.path !in removed) n++
}
}
Log.i(TAG, "games: migrated ${root.host} → $n games")
}
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.session.SecondaryLibrary
import java.io.File
@@ -87,13 +88,14 @@ object Library {
internal fun steamLibraries(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<Pair<File, String>> {
val root = SessionPrefs.steamRoot(context, arch)
// The session gives the x86-64 client only its card folder; the games folders stay the arm64 client's.
val card = GameStorage.effective(context)
if (arch == "x86_64") return listOfNotNull(root to "internal", card?.let { File(it.path, GameStorage.X64_CARD_DIR) to it.label })
val added = SteamLibraries.list(context).filter { it.host.isDirectory }
if (arch == "x86_64") return listOfNotNull(root to "internal", card?.let { File(it.path, GameStorage.X64_CARD_DIR) to it.label }) +
added.map { it.x64Host to it.label }
return listOfNotNull(
root to "internal",
card?.let { File(it.path) to it.label },
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
) + added.map { it.host to it.label } + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
}
fun protonPrefix(
@@ -101,15 +103,21 @@ object Library {
libraries: List<File> = steamLibraries(context).map { it.first },
): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
return prefixRoots(context, libraries, preferredLibrary).asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
fun compatdataDirs(context: Context, libraries: List<File> = steamLibraries(context).map { it.first }): List<File> =
prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory }
private fun prefixRoots(context: Context, libraries: List<File>, preferredLibrary: File? = null): List<File> {
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
else root
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
return (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
fun steamGames(
@@ -172,7 +180,6 @@ object Library {
}
}
/** Apps the user hid (the "hidden" collection) or marked private in Steam. */
internal fun concealedSteamApps(root: File): Set<Long> {
val config = AddedGames.accountConfig(root) ?: return emptySet()
val hidden = runCatching {
@@ -213,7 +220,6 @@ object Library {
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
}
/** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
internal fun shortcutsLastPlayed(root: File): Map<Long, Long> = runCatching {
val config = AddedGames.accountConfig(root) ?: return emptyMap()
val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
@@ -10,7 +10,6 @@ object LibraryCache {
private const val TAG = "LibraryCache"
private fun file(context: Context) = File(context.filesDir, "library-cache.json")
/** The cached games and whether they are the x86-64 client's; a cache written as a bare list is arm64's. */
@Synchronized
fun snapshot(context: Context): Pair<List<Library.SteamGame>, Boolean> = runCatching {
val f = file(context)
@@ -36,7 +35,6 @@ object LibraryCache {
fun listedX64(context: Context): Boolean = snapshot(context).second
/** Without [x64] the list keeps the client already recorded. */
@Synchronized
fun save(context: Context, games: List<Library.SteamGame>, x64: Boolean? = null) {
runCatching {
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.frontend
import org.json.JSONObject
/** Where Steam pins a game's logo on its hero image and how big it draws it; the same JSON Steam keeps in `<appid>.json`. */
object LogoPosition {
enum class Pin(val steam: String) {
UPPER_LEFT("UpperLeft"), UPPER_CENTER("UpperCenter"), CENTER("CenterCenter"), BOTTOM_LEFT("BottomLeft"), BOTTOM_CENTER("BottomCenter");
@@ -17,7 +16,6 @@ object LogoPosition {
const val MIN_PCT = 10
const val MAX_PCT = 100
/** What Steam draws when a game has no custom position. */
val DEFAULT = Value(Pin.BOTTOM_LEFT, 50, 50)
private const val VERSION = 1
@@ -25,7 +23,6 @@ object LogoPosition {
fun sized(pin: Pin, size: Int): Value = size.coerceIn(MIN_PCT, MAX_PCT).let { Value(pin, it, it) }
/** `{"nVersion":1,"logoPosition":{...}}`, with whatever else [into] already held kept as it was. */
fun toJson(value: Value, into: JSONObject = JSONObject()): JSONObject = into
.put("nVersion", VERSION)
.put(KEY, JSONObject().put("pinnedPosition", value.pin.steam).put("nWidthPct", value.widthPct).put("nHeightPct", value.heightPct))
@@ -39,7 +36,6 @@ object LogoPosition {
return Value(pin, inner.optInt("nWidthPct").coerceIn(MIN_PCT, MAX_PCT), inner.optInt("nHeightPct").coerceIn(MIN_PCT, MAX_PCT))
}
/** [existing] without the logo position; null when nothing but the version number would be left. */
fun without(existing: JSONObject): JSONObject? {
existing.remove(KEY)
val rest = existing.keys().asSequence().filter { it != "nVersion" }.toList()
@@ -7,11 +7,9 @@ import org.json.JSONObject
import java.io.File
import java.util.UUID
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
object SteamGrid {
private const val TAG = "SteamGrid"
/** Every change to a game's art, here or in a scan, takes this first so two of them never interleave. */
internal val lock = Any()
private const val MANIFEST = ".droiddeck-art.json"
private val SUFFIX = mapOf(AddedGameArt.Slot.COVER to "p", AddedGameArt.Slot.WIDE to "", AddedGameArt.Slot.BACKGROUND to "_hero", AddedGameArt.Slot.LOGO to "_logo")
@@ -36,7 +34,6 @@ object SteamGrid {
private fun signature(file: File?) = if (file == null) "" else "${file.length()}:${file.lastModified()}"
/** Each Steam client has its own grid folder, so what was last seen there is kept per client. */
private fun sigName(context: Context, key: String) =
if (SessionPrefs.activeSteamClientArch(context) == "x86_64") "grid-x86_64-$key" else "grid-$key"
@@ -45,10 +42,6 @@ object SteamGrid {
private const val GRID_ID = ".droiddeck-grid"
private const val UNKNOWN_GRID = "?"
/**
* A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the
* runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped.
*/
private fun gridId(grid: File): String = runCatching {
val f = File(grid, GRID_ID)
f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id ->
@@ -83,7 +76,6 @@ object SteamGrid {
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
}.getOrDefault(emptySet())
/** Puts a choice (or, with null, the lack of one) where Steam reads it, whether or not Steam is running. */
fun write(context: Context, target: Target, slot: AddedGameArt.Slot, file: File?): Boolean = synchronized(lock) { place(context, target, slot, file) }
private fun place(context: Context, target: Target, slot: AddedGameArt.Slot, file: File?): Boolean {
@@ -116,7 +108,6 @@ object SteamGrid {
private fun positionIn(file: File): LogoPosition.Value? = file.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() }?.let(LogoPosition::parse)
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
private fun positionRecorded(context: Context, grid: File, target: Target): String? =
@@ -132,12 +123,10 @@ object SteamGrid {
return runCatching { file.writeText(LogoPosition.toJson(value).toString()) }.isSuccess
}
/** Sets (or with null, clears) a game's logo position here and in the client's grid folder, whether or not Steam is running. */
fun writePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean = synchronized(lock) {
placePosition(context, target, value) && storePosition(target, value)
}
/** Steam keeps the position in `<id>.json`; anything else that file holds is left as it was. */
private fun placePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean {
val grid = dir(context) ?: return true
val file = positionFile(grid, target.id)
@@ -160,7 +149,6 @@ object SteamGrid {
return true
}
/** A `logoPosition` this version cannot read (a pin it does not know, say) is left alone rather than read as "removed". */
private fun hasUnknownPosition(file: File): Boolean {
val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return false
return json.has("logoPosition") && LogoPosition.parse(json) == null
@@ -176,7 +164,6 @@ object SteamGrid {
when {
before == null && own != null && theirs == null -> placePosition(context, target, own)
before == null || now != before -> {
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
if (theirs != null) {
if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now)
} else {
@@ -187,7 +174,6 @@ object SteamGrid {
}
}
/** Takes over what changed in Steam since the last look; returns true when a choice was added, replaced or dropped. */
fun sync(context: Context, targets: List<Target>): Boolean = synchronized(lock) { reconcile(context, targets) }
private fun reconcile(context: Context, targets: List<Target>): Boolean {
@@ -70,15 +70,22 @@ object SteamGridDb {
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
}
fun gameId(key: String, steamAppId: Int?, name: String): Int? {
fun gameId(key: String, steamAppId: Int?, name: String): Int? = gameId(key, steamAppId, name, ::match)
fun exactGameId(key: String, steamAppId: Int?, name: String): Int? = gameId(key, steamAppId, name, ::exactMatch)
private fun gameId(key: String, steamAppId: Int?, name: String, pick: (String, List<Pair<Int, String>>) -> Int?): Int? {
if (steamAppId != null) {
json(key, "$API/games/steam/$steamAppId")?.optJSONObject("data")?.optInt("id")?.takeIf { it > 0 }?.let { return it }
}
val term = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
val results = json(key, "$API/search/autocomplete/$term")?.optJSONArray("data") ?: return null
return match(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
return pick(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
}
internal fun exactMatch(name: String, results: List<Pair<Int, String>>): Int? =
results.firstOrNull { (id, got) -> id > 0 && AddedGameArt.nameMatch(name, got) == 3 }?.first
internal fun match(name: String, results: List<Pair<Int, String>>): Int? =
results.map { (id, got) -> id to AddedGameArt.nameMatch(name, got) }
.filter { it.second > 0 && it.first > 0 }
@@ -0,0 +1,162 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
object SteamLaunchOptions {
private const val TAG = "SteamLaunchOptions"
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
fun current(context: Context, appId: Int): String =
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId).orEmpty()
enum class Saved { YES, NO, DESKTOP }
fun set(context: Context, appId: Int, options: String, shown: String): Saved {
val value = options.trim()
if (SessionState.running && SessionState.mode == SessionService.MODE_DESKTOP) return Saved.DESKTOP
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) {
val live = SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: return Saved.NO
if (live.trim() != shown.trim()) return Saved.NO
return if (SteamLiveShortcuts.setLaunchOptions(context, appId.toLong(), value)) Saved.YES else Saved.NO
}
val home = SessionPrefs.activeSteamRoot(context)
if (steam(home, appId).orEmpty().trim() != shown.trim()) return Saved.NO
return if (write(home, appId, value)) Saved.YES else Saved.NO
}
internal fun steam(steamHome: File, appId: Int): String? {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
return launchOptions(text, appId)
}
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
val updated = withLaunchOptions(text, appId, options) ?: return false
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(updated)
if (config.readText() != text) {
staged.delete()
return false
}
Files.move(staged.toPath(), config.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write launch options to ${config.path}", e)
false
}
}
internal fun launchOptions(text: String, appId: Int): String? {
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
}
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
var updated = text
var path = STEAM
for (key in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
path = path + key
}
val app = section(updated, path) ?: return null
val value = "\"" + escape(options) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
return updated.replaceRange(it.valueStart, it.end + 1, value)
}
val lineStart = closingLine(updated, app) ?: return null
val indent = updated.substring(lineStart, app.end) + "\t"
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
}
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
private fun section(text: String, path: List<String>): Entry? {
var found: Entry? = null
for (key in path) {
found = entries(text, found?.valueStart ?: -1, found?.end ?: text.length)
.firstOrNull { it.section && it.key.equals(key, true) } ?: return null
}
return found
}
private fun entries(text: String, open: Int, close: Int): List<Entry> {
val found = ArrayList<Entry>()
var key: String? = null
var i = open + 1
while (i < close) {
when {
text[i] == '"' -> {
val end = stringEnd(text, i) ?: return found
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
i = end + 1
}
text[i] == '{' -> {
val end = sectionEnd(text, i) ?: return found
key?.let { found += Entry(it, i, end, true) }
key = null
i = end + 1
}
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
else -> i++
}
}
return found
}
private fun stringEnd(text: String, open: Int): Int? {
var i = open + 1
while (i < text.length) {
when (text[i]) {
'\\' -> i += 2
'"' -> return i
else -> i++
}
}
return null
}
private fun sectionEnd(text: String, open: Int): Int? {
var depth = 0
var i = open
while (i < text.length) {
when (text[i]) {
'"' -> i = stringEnd(text, i) ?: return null
'{' -> depth++
'}' -> if (--depth == 0) return i
}
i++
}
return null
}
private fun withSection(text: String, parent: Entry, key: String, newline: String): String? {
if (entries(text, parent.valueStart, parent.end).any { it.section && it.key.equals(key, true) }) return text
val lineStart = closingLine(text, parent) ?: return null
val indent = text.substring(lineStart, parent.end) + "\t"
return text.substring(0, lineStart) + "$indent\"$key\"$newline$indent{$newline$indent}$newline" + text.substring(lineStart)
}
private fun closingLine(text: String, section: Entry): Int? {
val lineStart = text.lastIndexOf('\n', section.end - 1) + 1
return lineStart.takeIf { lineStart > section.valueStart && text.substring(lineStart, section.end).all { it == '\t' || it == ' ' } }
}
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"")
private fun unescape(value: String) = value.replace(Regex("\\\\(.)"), "$1")
}
@@ -45,15 +45,15 @@ object SteamMatch {
identity?.appId?.let { id ->
return Match(id, Certainty.FILES, identity.source.name.lowercase(), now).also { put(context, key, it) }
}
val known = get(context, key)
val known = get(context, key)?.takeUnless { it.appId == GameIdentifier.SPACEWAR }
if (known != null && known.certainty == Certainty.NAME) return known
if (known != null && known.certainty == Certainty.NONE && now - known.checkedAt < RETRY_AFTER_MS) return known
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 }?.let { id ->
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 && it != GameIdentifier.SPACEWAR }?.let { id ->
return Match(id, Certainty.NAME, "store search", now).also { put(context, key, it) }
}
if (search == null) return known?.takeIf { it.certainty != Certainty.FILES } ?: Match(null, Certainty.NONE, "", 0)
val id = runCatching { search(name) }.getOrNull()
val match = if (id != null && id > 0) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
val match = if (id != null && id > 0 && id != GameIdentifier.SPACEWAR) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
put(context, key, match)
return match
}
@@ -15,7 +15,6 @@ object SteamRedists {
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
"228990" to ("d3dx9" to "DirectX (June 2010)"),
)
/** Redists a game's own install script runs on Windows that its shared depots don't name. */
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
@@ -28,7 +27,6 @@ object SteamRedists {
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
}
/** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */
fun installScript(gameDir: File?): List<Pair<String, String>> =
gameDir?.listFiles { f ->
f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") }
@@ -51,10 +51,8 @@ object WinCompSources {
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
private val XBOX_KNOWN = Regex("""<KnownDependency\s+Name="([A-Za-z0-9_.-]{1,40})"""")
// VC14 also registers the ARM64 runtime: launchers running as ARM64EC look for it and stop when it is missing.
private val XBOX_COMPONENTS = mapOf("VC14" to listOf("vcredist2022", WinComponents.VCREDIST_ARM64))
/** Microsoft installs a PC Game Pass game's declared runtimes with it; VC14 is wanted by nearly all and is always added. */
fun xbox(folder: File?): List<Pair<String, String>> {
val config = folder?.listFiles().orEmpty().firstOrNull { it.isFile && it.name.equals("MicrosoftGame.config", ignoreCase = true) && it.length() < 1L shl 20 }
val declared = config?.let { file -> runCatching { XBOX_KNOWN.findAll(file.readText()).map { it.groupValues[1] }.toList() }.getOrNull() }.orEmpty()
@@ -563,7 +563,6 @@ object Glasses {
val device = selected?.first
val m = selected?.second
val controllable = m?.let(::canOpenModel) == true
// XREAL uses Android's Ethernet sockets, without opening or claiming USB interfaces.
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
val identity = device?.let {
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
@@ -677,8 +676,6 @@ object Glasses {
internal fun selectGlassesDisplay(displays: List<Display>, usbPresent: Boolean): Display? {
val candidates = displays
.filter { it.displayId != Display.DEFAULT_DISPLAY && it.flags and Display.FLAG_PRESENTATION != 0 }
// Android can expose the glasses name on either the logical display or
// its product metadata. A generic label on one must not hide the other.
return candidates.firstOrNull { display ->
isGlassesDisplayName(display.name) ||
(Build.VERSION.SDK_INT >= 31 && display.deviceProductInfo?.let { product ->
@@ -728,7 +725,6 @@ object Glasses {
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) {
VitureV2Link.open(usb, device, v2Listener(generation))
} else if ((model as? VitureProtocol.Model)?.needsSdk == true) {
// Android can evict cacheDir while the SDK is running.
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial))
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
(model as? VitureProtocol.Model)?.family, spatial)
@@ -854,7 +850,6 @@ object Glasses {
if (generation != linkGeneration) return@post
closeLink()
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
// Let a reconnect or explicit Allow retry restart the SDK, not an endless failure loop.
}
}
@@ -974,7 +969,6 @@ object Glasses {
}
if (!s.usable || s.sbs || modeState.pendingStereo) return
val hz = _settings.value.refreshHz
// Native 30 Hz is selected by the Android presentation, without a vendor mode command.
if (hz == 30 && GlassesRendering.native30HzAvailable(_settings.value, s)) return
if (glassesMode == m.mode(hz, false, outputResolution())) return
if (!force) {
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.glasses
/** Hardware properties; display refresh is selected from Android's advertised modes. */
interface GlassesModel {
val name: String
val controllable: Boolean
@@ -18,9 +17,6 @@ interface GlassesModel {
fun modeForStep(step: Int): Int?
}
/** The command IDs here are the existing glasses controller's internal vocabulary.
* Each transport translates them to its own wire protocol; unsupported controls return false.
*/
internal interface GlassesLink {
val hasImu: Boolean
val badFrames: Long get() = 0L
@@ -63,7 +63,6 @@ class GlassesMenuSurface(
override fun onDetachedFromWindow() {
close()
super.onDetachedFromWindow()
// GLSurfaceView may exit its GL thread before queued cleanup is consumed.
releaseInput()
}
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.Cardboard
/** Share the actual picture mode with settings so controls match the rendered view. */
internal object GlassesRendering {
enum class Picture { FLAT, DUPLICATED, VIRTUAL_SCREEN, STEREO }
@@ -51,11 +50,7 @@ internal object GlassesRendering {
outputActive: Boolean,
steamVrRunning: Boolean,
): Cardboard {
// Mirror output still uses the glasses' picture and sensors during VR.
if (!usesGlasses(state, outputActive, steamVrRunning)) {
// SteamVR uses the renderer's enabled flag as headset proximity.
// A flat phone preview still needs an active HMD and one SBS eye;
// otherwise SteamVR enters standby and leaves a frozen frame.
return if (steamVrRunning && !base.enabled) base.copy(
enabled = true,
source = Cardboard.SOURCE_SBS,
@@ -36,7 +36,6 @@ class GlassesScreen(context: Context, display: Display, refreshHz: Int, private
fun prefer(hz: Int, resolution: GlassesResolution? = null) {
wantHz = hz
wantResolution = resolution
// A 2D/SBS transition can replace the active mode without changing Hz.
applyMode()
}
@@ -51,7 +51,6 @@ internal class HandImageBuffer {
pixels.clear()
pixels.put(rgb)
pixels.rewind()
// MediaPipe applies the model metadata's float normalization to these RGB bytes.
return ByteBufferImageBuilder(pixels, width, height, MPImage.IMAGE_FORMAT_RGB).build()
}
}
@@ -150,7 +150,6 @@ class LumaRgbCaptureService : Service() {
intent?.getIntExtra("durationMs",5000) ?: 5000) }
finally {
stopSelf()
// SDK 2.4.0 can crash while cancelling failed USB transfers; isolate each diagnostic.
android.os.Process.killProcess(android.os.Process.myPid())
}
}, "luma-rgb-diagnostic").start()
@@ -40,12 +40,9 @@ internal data class RayNeoCalibration(val gyroBiasDps: Vec3, val level: Quaterni
internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
companion object {
// GT and GT Max can share USB identity fields. Keep the non-Max mounting
// correction separate from existing Max profiles and their legacy keys.
fun profileKey(base: String, gtUsb: Boolean, boardId: Int): String =
if (gtUsb && boardId == RayNeoProtocol.BOARD_GT) "$base:gt-standard-v1" else base
}
// A serial isolates physical units. Devices without one share their model profile.
fun key(vid: Int, pid: Int, serial: String?, modelName: String = ""): String =
"rayneo-cal-v1:$vid:$pid:${serial?.takeIf { it.isNotBlank() } ?: "model:$modelName"}"
fun load(key: String): RayNeoCalibration? = RayNeoCalibration.decode(prefs.getString(key, null))
@@ -55,7 +52,6 @@ internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
}
}
/** One upside-down stationary pose estimates gyro bias and tilt, never yaw or accelerometer scale. */
internal class RayNeoCalibrationCollector(private val axes: RayNeoSensorAxes, private val beganMs: Long) {
var phase = CalibrationPhase.SETTLING; private set
var progress = 0; private set
@@ -6,7 +6,6 @@ import android.hardware.usb.UsbManager
import android.os.SystemClock
import android.util.Log
/** RayNeo command/response and IMU share one endpoint. Keep reads on a single worker. */
internal class RayNeoLink private constructor(
private val connection: UsbDeviceConnection,
private val endpoints: RayNeoEndpointSelection,
@@ -52,7 +51,6 @@ internal class RayNeoLink private constructor(
ready && (mode == RayNeoProtocol.CMD_SWITCH_TO_3D || mode == RayNeoProtocol.CMD_SWITCH_TO_2D) &&
command(mode)
}
// No VITURE brightness, volume, film, rate or raw command is sent to RayNeo.
else -> false
}
}
@@ -159,7 +157,6 @@ internal class RayNeoLink private constructor(
}
val wxyz = filter.update(packet.sample)
if (wantImu && collector == null && lastSensor >= warmupUntil) {
// Normalize basis and component order at the hardware boundary.
listener.onPose(raw, RayNeoOrientationFilter.glassesPose(wxyz),
SystemClock.elapsedRealtimeNanos())
}
@@ -176,7 +173,6 @@ internal class RayNeoLink private constructor(
override fun close() {
synchronized(writeLock) {
if (!running) return
// Best effort: stop the sensor before releasing the claimed interface.
if (ready) runCatching { command(RayNeoProtocol.CMD_CLOSE_IMU) }
running = false
}
@@ -8,8 +8,6 @@ object RayNeoModel {
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
if (!isVendor(vid)) return null
// GT's identity is confirmed by verncat's SDK; do not claim other products
// from that vendor just because their name resembles a supported model.
val gt = RayNeoProtocol.isGt(vid, pid)
if (vid == RayNeoProtocol.GT_VENDOR_ID && !gt) return null
if (!(vid == RayNeoProtocol.VENDOR_ID && pid == RayNeoProtocol.PRODUCT_ID) &&
@@ -23,8 +21,6 @@ object RayNeoModel {
name.contains("rayneo", ignoreCase = true) || name.contains("ray neo", ignoreCase = true) ||
modelName.containsMatchIn(name)
// Observed on GT Max: Android exposes an unbranded EDID monitor name.
// Match its product metadata, not every display called SmartGlasses/TCL.
fun isDisplayProduct(name: String?, manufacturer: String?, productId: String?): Boolean =
name?.trim().equals("SmartGlasses", ignoreCase = true) &&
manufacturer.equals("TCL", ignoreCase = true) && productId == "980"
@@ -33,7 +29,7 @@ object RayNeoModel {
override val controllable = true
override val brightnessMax = 0
override val volumeMax = 0
override val diagonalFovDeg = 46f // Conservative existing default, not a calibrated model profile.
override val diagonalFovDeg = 46f
override val sbs90 = false
override fun mode(hz: Int, sbs: Boolean) =
if (sbs) RayNeoProtocol.CMD_SWITCH_TO_3D else RayNeoProtocol.CMD_SWITCH_TO_2D
@@ -1,5 +1,4 @@
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0).
// See docs/third-party/rayneo/. Returns scaffold quaternions in (w, x, y, z) order.
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0); see docs/third-party/rayneo/ for license and attribution.
package com.droiddeck.launcher.glasses
import kotlin.math.cos
@@ -123,10 +122,6 @@ internal class RayNeoOrientationFilter(
private var lastRealtimeNs: Long = 0L
companion object {
/** Scaffold: right +X, up +Y, back +Z. VITURE: right -Y, up +Z, back -X.
* Conjugate by HeadPose.GLASSES_AXES before entering the unchanged VITURE pose path.
* This is a basis conversion, not a projection or seated-origin adjustment.
*/
fun glassesPose(wxyz: FloatArray): FloatArray =
floatArrayOf(-wxyz[3], -wxyz[1], wxyz[2], wxyz[0])
}
@@ -168,8 +163,6 @@ internal class RayNeoOrientationFilter(
if (accelNorm > 1e-3f) {
val measuredUp = accel.normalized()
if (!gravityInitialized) {
// Align gravity before publishing the first pose. Starting at
// identity and settling after recenter can rotate the horizon.
val axis = measuredUp.cross(worldUp)
q = if (measuredUp.y < -0.9999f) {
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.PI.toFloat())
@@ -179,7 +172,6 @@ internal class RayNeoOrientationFilter(
gravityInitialized = true
}
val predictedUp = q.conjugate().rotate(worldUp).normalized()
// q maps body to world: measured x predicted reduces gravity error.
val correction = measuredUp.cross(predictedUp)
gyro += correction * accelGain
}
@@ -40,14 +40,13 @@ data class RayNeoEndpointSelection(
object RayNeoProtocol {
const val VENDOR_ID = 0x1BBB
const val PRODUCT_ID = 0xAF50
// verncat/RayNeo-Air-3S-Pro-OpenVR PR #3 (MIT), tested on GT hardware.
const val GT_VENDOR_ID = 0x3941
private const val GT_CONTROL_INTERFACE = 5
fun isGt(vid: Int, pid: Int) = vid == GT_VENDOR_ID && pid == PRODUCT_ID
const val BOARD_AIR_4_PRO = 0x3A
const val BOARD_GT = 0x40 // Observed on the user's non-Max GT.
const val BOARD_GT = 0x40
const val PKT_MAGIC = 0x99
const val PKT_SENSOR = 0x65
@@ -131,7 +130,6 @@ object RayNeoProtocol {
endpoint.type != UsbConstants.USB_ENDPOINT_XFER_BULK) {
continue
}
// Exclude small button reports from GT's protocol transport.
if (gt && endpoint.maxPacketSize < 64) continue
if (endpoint.direction == UsbConstants.USB_DIR_IN && inEndpoint == null) {
@@ -159,8 +157,6 @@ object RayNeoProtocol {
}
}
// Interface numbers can change with firmware. Use a unique protocol-sized
// pair when interface 5 is absent, never an arbitrary composite interface.
return if (gt) gtCandidates.singleOrNull() else fallback
}
@@ -9,7 +9,6 @@ import android.hardware.usb.UsbManager
import android.os.SystemClock
import android.util.Log
/** Controls are vendor control transfers; the HID interrupt endpoint streams IMU reports unprompted. */
internal class RokidLink private constructor(
private val connection: UsbDeviceConnection,
private val usbInterface: UsbInterface,
@@ -44,7 +43,7 @@ internal class RokidLink private constructor(
?.let { listener.onValue(VitureProtocol.MSG_BRIGHTNESS, RokidModel.brightnessStep(it)) } != null
VitureProtocol.MSG_BRIGHTNESS -> value in 0..RokidModel.BRIGHTNESS_STEPS &&
control(RokidModel.REQUEST_SET_BRIGHTNESS, RokidModel.brightnessRaw(value), RokidModel.INDEX_BRIGHTNESS)
else -> false // Volume is the glasses' USB audio device; there is no film or IMU-rate control.
else -> false
}
}
@@ -54,7 +53,6 @@ internal class RokidLink private constructor(
if (!running) return null
val buffer = ByteArray(64)
val count = connection.controlTransfer(VENDOR_IN, request, 0, index, buffer, buffer.size, TIMEOUT_MS)
// Display mode is reported in the second byte, brightness in the first.
val offset = if (request == RokidModel.REQUEST_GET_DISPLAY) 1 else 0
if (count > offset) buffer[offset].toInt() and 0xff else null
}
@@ -90,7 +88,6 @@ internal class RokidLink private constructor(
if (enabled && !wasTracking) fusion = ImuFusion()
wasTracking = enabled
if (!enabled) continue
// Max captures: already right/up/back; level gravity +Y, turn left +gyroY, look up +gyroX, roll right -gyroZ.
fusion.update(sample.timeNs, sample.accel, sample.gyro)?.let {
if (running && tracking) listener.onPose(buffer.copyOf(count), it, SystemClock.elapsedRealtimeNanos())
}
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.glasses
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */
internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel {
override val controllable = true
override val brightnessMax = BRIGHTNESS_STEPS
@@ -36,7 +35,6 @@ internal class RokidModel private constructor(override val name: String, private
const val MAX2_PRODUCT_ID = 0x2002
const val BRIGHTNESS_STEPS = 10
// Vendor control requests, device recipient.
const val REQUEST_SET_DISPLAY = 0x01
const val REQUEST_GET_DISPLAY = 0x81
const val REQUEST_SET_BRIGHTNESS = 0x02
@@ -51,7 +49,6 @@ internal class RokidModel private constructor(override val name: String, private
const val MODE_SBS_1200_60 = 5
val MODES = setOf(MODE_2D_60, MODE_SBS_1080_60, MODE_2D_120, MODE_SBS_1200_90, MODE_SBS_1200_60)
// 0x04d2 is a shared vendor ID, so the Rokid product string is required too.
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null
val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null
@@ -60,7 +57,6 @@ internal class RokidModel private constructor(override val name: String, private
fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true)
/** Device brightness is 0..100; the shared slider uses ten steps. */
fun brightnessStep(raw: Int): Int = ((raw.coerceIn(0, 100) + 5) / 10).coerceIn(0, BRIGHTNESS_STEPS)
fun brightnessRaw(step: Int): Int = step.coerceIn(0, BRIGHTNESS_STEPS) * 10
}
@@ -74,7 +70,6 @@ internal object RokidProtocol {
private const val SENSOR_ACCEL = 1
private const val SENSOR_GYRO = 2
/** Max sends one combined report; Air sends accel and gyro reports that share a timestamp. */
class Parser {
private var accel: Vec3? = null
private var accelTime = -1L
@@ -87,7 +82,7 @@ internal object RokidProtocol {
return when (packet[0].toInt() and 0xff) {
COMBINED -> Sample(b.getLong(1), vec(b, 9), vec(b, 21), packet[59].toInt() and 0xff)
SEPARATE -> {
val time = b.getLong(9) * 1000 // Air reports microseconds; Max reports nanoseconds.
val time = b.getLong(9) * 1000
when (packet[1].toInt() and 0xff) {
SENSOR_ACCEL -> { accel = vec(b, 21); accelTime = time }
SENSOR_GYRO -> { gyro = vec(b, 21); gyroTime = time }
@@ -26,7 +26,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
val source get() = if (bundledBase && !verified) "luma-ultra-base" else "device"
private val p1 = Mat.zeros(3, 4, CvType.CV_64F)
private val p2 = Mat.zeros(3, 4, CvType.CV_64F)
private val undistortionMaps = Array(2) { arrayOf(Mat(),Mat()) }
init {
val a = Mat.eye(3, 4, CvType.CV_64F)
val b = Mat.zeros(3, 4, CvType.CV_64F)
@@ -35,18 +34,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
Core.gemm(k1, a, 1.0, empty, 0.0, p1); Core.gemm(k2, b, 1.0, empty, 0.0, p2)
a.release(); b.release(); empty.release()
}
fun undistort(src: Mat, dst: Mat, right: Boolean) {
val k = if (right) k2 else k1; val d = if (right) d2 else d1
val maps=undistortionMaps[if(right) 1 else 0]
if(maps[0].empty()) {
val identity=Mat.eye(3,3,CvType.CV_64F)
try {
if(fisheye) Calib3d.fisheye_initUndistortRectifyMap(k,d,identity,k,src.size(),CvType.CV_16SC2,maps[0],maps[1])
else Calib3d.initUndistortRectifyMap(k,d,identity,k,src.size(),CvType.CV_16SC2,maps[0],maps[1])
} finally { identity.release() }
}
Imgproc.remap(src,dst,maps[0],maps[1],Imgproc.INTER_LINEAR)
}
fun triangulateRaw(left: List<Point>, right: List<Point>): List<SpatialVector>? {
val points = triangulateLandmarksRaw(left,right) ?: return null
return if(points.any { it == null }) null else points.filterNotNull()
@@ -74,10 +61,6 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
return triangulatePoints(l.toList(),r.toList())
} finally { l.release(); r.release(); identity.release() }
}
fun triangulate(left: List<Point>, right: List<Point>): List<SpatialVector>? {
val points = triangulatePoints(left,right) ?: return null
return if(points.any { it == null }) null else points.filterNotNull()
}
private fun triangulatePoints(left: List<Point>, right: List<Point>): List<SpatialVector?>? {
if (left.size != right.size || left.isEmpty()) return null
val a = Mat(2, left.size, CvType.CV_64F); val b = Mat(2, right.size, CvType.CV_64F); val out = Mat()
@@ -105,7 +88,7 @@ internal class StereoCalibration(val identity: String, val width: Int, val heigh
val tmp = File(file.parentFile,file.name+".tmp"); tmp.writeText(j.toString())
java.nio.file.Files.move(tmp.toPath(),file.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
override fun close() { (listOf(k1,d1,k2,d2,r,t,p1,p2)+undistortionMaps.flatMap { it.toList() }).forEach { it.release() } }
override fun close() { listOf(k1,d1,k2,d2,r,t,p1,p2).forEach { it.release() } }
companion object {
fun load(file: File, identity: String, width: Int, height: Int): StereoCalibration? =
runCatching { StereoCalibrationProfile.parse(file.readText(), identity, width, height)?.let(::fromProfile) }.getOrNull()
@@ -286,7 +269,6 @@ internal class StereoCalibrator(private val context: Context) : AutoCloseable {
Mat().also { output -> corrected.add(output); Calib3d.fisheye_undistortPoints(pixels,output,k,d,identity,k) }
}
try {
// OpenCV 4.13 fisheye stereo fitting assumes equal corner counts in every view.
Calib3d.stereoCalibrate(objects,images(left,k1,d1),images(right,k2,d2),k1,if(fish)zero else d1,k2,if(fish)zero else d2,
size,r,t,e,f,Calib3d.CALIB_FIX_INTRINSIC)
} finally { (corrected+listOf(e,f,identity,zero)).forEach(Mat::release) }
@@ -383,7 +383,6 @@ internal class StereoHandEngine(private val context: Context, private val token:
message=context.getString(R.string.spatial_frame_changed)
calibrationProgress = calibrationProgress.copy(collecting = false, capturing = false, captureMessage = message)
}
// The callback pose's basis is undocumented; use canonical GL pose history.
val observation=HandObservation(time,generation,trackingFrame)
var captureHead=observation.headPose(SpatialTracking.session,metadata[6]>0)
val w=metadata[0].toInt();val h=metadata[1].toInt()
@@ -499,7 +498,6 @@ internal class StereoHandEngine(private val context: Context, private val token:
dl=pair.first.hands;dr=pair.second.hands
if(scheduled) inferenceSchedule.observe(stamp,dl.map { it.side },dr.map { it.side },pair.first.rawCount,pair.second.rawCount)
val inferenceMs=(System.nanoTime()-inferenceStart)/1e6f
// VIO callbacks can arrive during inference; verify this exact camera stamp before publishing.
captureHead=observation.headPose(SpatialTracking.session,
metadata[6]>0 || VitureSdk.nativeCameraSynchronized(token,metadata[2]))
val hands=Array(2) { SpatialHand() }
@@ -631,7 +629,7 @@ internal class StereoHandEngine(private val context: Context, private val token:
SpatialTracking.publish(System.nanoTime())
}
}
} catch(e: InterruptedException) { /* Shutdown interrupts the idle wait. */ }
} catch(e: InterruptedException) { }
catch(e: Throwable) {
message=context.getString(R.string.spatial_hand_error, e.message.orEmpty())
val unavailable=HandObservationDiagnostic(HandObservationOutcome.INFERENCE_UNAVAILABLE)
@@ -31,7 +31,6 @@ internal class StereoInferenceRunner : AutoCloseable {
catch (e: ExecutionException) { throw e.cause ?: e }
}
} finally {
// Native inference must finish before either camera's pixels or detector can be reused.
if (interrupted) Thread.currentThread().interrupt()
}
}
@@ -12,8 +12,6 @@ internal object UvcRgbDiagnostic {
internal data class UvcStreamHealth(val observationMs: Double, val observedFps: Double,
val maximumGapMs: Double, val healthy: Boolean) {
companion object {
// Health requires the full requested window, 80% of requested FPS, and no gap
// (including the final silent interval) above max(250 ms, three frame periods).
fun assess(metadata: LongArray, requestedFps: Int, durationMs: Int): UvcStreamHealth {
require(metadata.size == 14 && requestedFps > 0 && durationMs > 0)
val first = metadata[7]
@@ -81,7 +81,6 @@ object VitureProtocol {
}
}
/** SDK validates the PID before returning this market name. Never guess a new PID. */
fun sdkModel(marketName: String): Model? {
val family = when (marketName) {
"One", "Lite" -> Family.ONE
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.glasses
import android.util.Log
import kotlin.math.sqrt
/** JNI adapter to VITURE's Android C SDK. The vendor binary is a local build input. */
internal object VitureSdk {
val available: Boolean by lazy {
runCatching {
@@ -27,7 +26,6 @@ internal object VitureSdk {
external fun nativeSpatialDiagnostics(token: Long): DoubleArray?
external fun nativeTracking(token: Long, enabled: Boolean): Int
external fun nativeCommand(token: Long, command: Int, value: Int): Int
/** Returns CLOCK_BOOTTIME receipt time, zero for no new pose, or a negative SDK error. */
external fun nativePose(token: Long, wxyz: FloatArray): Long
external fun nativeNextState(token: Long, event: IntArray): Int
external fun nativeClose(token: Long)
@@ -48,12 +46,9 @@ internal object VitureSpatialIdentity {
}
internal object VitureSdkPose {
// Pro 2 hardware captures use OpenGL axes despite the generic Gen2 callback's
// NWU documentation. Keep that model-specific exception out of other Gen2 devices.
fun usesOpenGlAxes(carina: Boolean, family: VitureProtocol.Family?) =
carina || family == VitureProtocol.Family.PRO2
/** SDK quaternions are wxyz; normalize their coordinate basis at the boundary. */
fun toGlasses(wxyz: FloatArray, openGlAxes: Boolean): FloatArray? {
if (wxyz.size != 4 || wxyz.any { !it.isFinite() }) return null
val length = sqrt(wxyz.sumOf { it.toDouble() * it }.toFloat())
@@ -7,7 +7,6 @@ import android.os.SystemClock
import android.util.Log
import java.io.File
/** SDK owns interface selection (including Ultra bulk endpoints) and all USB I/O. */
internal class VitureSdkLink private constructor(
private val connection: UsbDeviceConnection,
private val token: Long,
@@ -47,7 +46,6 @@ internal class VitureSdkLink private constructor(
if (rc == 0 || !wanted) tracking = wanted
return result("tracking", rc)
}
// Frequency is negotiated against SDK capabilities, including Pro 2's pose limit.
VitureProtocol.MSG_IMU_RATE -> return tracking
VitureProtocol.MSG_GET_IMU -> return true
}
@@ -89,7 +87,6 @@ internal class VitureSdkLink private constructor(
if (VitureSdk.nativeNextState(token, event) == 1) when (event[0]) {
0 -> listener.onValue(VitureProtocol.MSG_GET_BRIGHTNESS, event[1])
1 -> listener.onValue(VitureProtocol.MSG_GET_VOLUME, event[1])
// A device event can use a different display-mode namespace.
2 -> send(VitureProtocol.MSG_GET_DISPLAY)
3 -> listener.onValue(VitureProtocol.MSG_FILM, event[1])
}
@@ -122,7 +119,6 @@ internal class VitureSdkLink private constructor(
if (!running) return
running = false
VitureSdk.nativeClose(token)
// Keep Java's descriptor alive until the SDK and its worker threads have stopped.
connection.close()
}
if (Thread.currentThread() !== worker) worker.join(1000)
Loaded 100 of 819 files, more files were not shown because too many files have changed in this diff. Show more