diff --git a/.gitattributes b/.gitattributes
index 4c0a6c3120..940dbb5f13 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,6 +2,7 @@ tools/linuxfs/** text=auto eol=lf
tools/mangoapp/** text=auto eol=lf
tools/comet/LICENSE whitespace=-blank-at-eof
tools/comet/droiddeck.patch whitespace=-blank-at-eol,-blank-at-eof
+tools/gamescope/patches/0900-enhanced-frame-diagnostics.patch whitespace=-blank-at-eol,-blank-at-eof,-space-before-tab
tools/linuxfs/overlay/** text eol=lf
tools/linuxfs/desktop/** text eol=lf
diff --git a/.github/trusted-test-builds.txt b/.github/trusted-test-builds.txt
index f91528f395..8f7b0148c5 100644
--- a/.github/trusted-test-builds.txt
+++ b/.github/trusted-test-builds.txt
@@ -1,3 +1,4 @@
+ASEbrahim
FX192
K11MCH1
kingokksa
diff --git a/.github/workflows/build-venus.yml b/.github/workflows/build-venus.yml
new file mode 100644
index 0000000000..d355bdcd78
--- /dev/null
+++ b/.github/workflows/build-venus.yml
@@ -0,0 +1,31 @@
+name: Build Venus (Mali)
+# The Mali (Venus) route's binaries from tools/venus (David Cimo's recipes): Mesa's Venus ICD and the
+# Mali compatibility layer (glibc, for the session) and virglrenderer's vtest server (bionic, run by
+# the app over the phone's own Vulkan driver), packed as venus.tzst rooted at app/src/main. The apk
+# build fetches it by tools/venus/release.env (tag + sha256); nothing compiled is kept in this repo.
+on:
+ workflow_dispatch:
+ push:
+ branches: [test/non-adreno-all]
+ paths: ['tools/venus/**', '.github/workflows/build-venus.yml']
+permissions:
+ contents: read
+jobs:
+ build:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@v4
+ - name: Tools
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y -qq ninja-build pkg-config zstd python3-pip
+ pip3 install --break-system-packages 'meson>=1.5'
+ - name: Build
+ run: ANDROID_NDK_HOME="$ANDROID_NDK_LATEST_HOME" WORK=$PWD/venus-work tools/venus/ci-build.sh
+ - uses: actions/upload-artifact@v4
+ with:
+ name: venus
+ path: |
+ venus-work/venus.tzst
+ venus-work/venus.tzst.sha256
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 7418c5bfb5..fcb30d8ac1 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -275,6 +275,19 @@ jobs:
if: steps.proot.outputs.cache-hit != 'true'
run: python3 tools/components/prepare.py proot
+ - name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer)
+ run: |
+ set -euo pipefail
+ bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libvulkan-dev
+ D=app/src/main/assets/linuxfs
+ mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse"
+ aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
+ -o "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
+ aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
+ install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$D/usr/local/lib/droiddeck-xclipse/"
+ aarch64-linux-gnu-gcc -O2 -Wall -o "$D/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
+ aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-glprobe"
+
- name: Check the preloads
run: |
set -euo pipefail
@@ -535,7 +548,9 @@ jobs:
key: pack-inputs-v1-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env') }}
restore-keys: pack-inputs-v1-
- name: Build the add-on packs
- run: bash tools/packs/build.sh app/build/packs
+ run: |
+ python3 tools/powervr/fetch.py
+ bash tools/packs/build.sh app/build/packs
- name: Pin the Syncthing source
id: syncthing-src
@@ -573,6 +588,18 @@ jobs:
- name: Check out MaliBridge
run: git submodule update --init external/MaliBridge
+ - name: Fetch the Mali (Venus) component (tools/venus/release.env)
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ . tools/venus/release.env
+ gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O venus.tzst
+ echo "${VENUS_SHA256} venus.tzst" | sha256sum -c -
+ tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main
+ test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so
+ test -f app/src/main/assets/venus/libvulkan_virtio.so
+ rm venus.tzst
- name: Build
id: build
@@ -581,6 +608,7 @@ jobs:
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
run: |
set -o pipefail
+ python3 tools/powervr/fetch.py
python3 tools/release/runtime_inputs.py record
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
diff --git a/.github/workflows/publish-packs.yml b/.github/workflows/publish-packs.yml
index de4adb3b21..ca61616d18 100644
--- a/.github/workflows/publish-packs.yml
+++ b/.github/workflows/publish-packs.yml
@@ -55,7 +55,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
- for name in proot directaudio tracking xbox comet butler; do
+ for name in proot directaudio tracking xbox comet butler powervr; do
file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1)
diff --git a/.gitignore b/.gitignore
index bfeee76414..0a404ef667 100644
--- a/.gitignore
+++ b/.gitignore
@@ -34,4 +34,5 @@ __pycache__/
.signing.env
app/src/main/assets/directaudio/
+app/src/main/assets/hybris/
/tools/vr/out/
diff --git a/README.md b/README.md
index cc233c380c..e9f172bfa1 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx is experimental. Mali, Xclipse, PowerVR and Adreno 710 are unsupported. No root needed.
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
-3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.6.7/DroidDeck-0.6.7.apk), install the Linux runtime, press **Play** and sign in to Steam.
+3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.6.9/DroidDeck-0.6.9.apk), install the Linux runtime, press **Play** and sign in to Steam.
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
@@ -93,6 +93,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
+- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
diff --git a/app/build.gradle b/app/build.gradle
index 736d728ba2..743ad2a847 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
-def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler'].collectEntries { name ->
+def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -205,7 +205,7 @@ android {
}
androidResources {
- ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:
_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:directaudio'
+ ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:directaudio:hybris'
}
packagingOptions {
@@ -249,6 +249,12 @@ android {
}
}
+// No instrumented tests; the unused androidTest variant breaks the VS Code Kotlin import.
+androidComponents {
+ beforeVariants(selector().all()) { it.androidTest.enable = false }
+}
+
+// Vendor binaries remain in the user's SDK directory; never vendor them into Git.
if (vitureSdkDir) {
android.sourceSets.main.jniLibs.srcDir(new File(vitureSdkDir, 'android'))
def stageVitureNotices = tasks.register('stageVitureNotices', Copy) {
diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt
index fd0b2f20a9..61baf0d379 100644
--- a/app/src/main/cpp/waylandcomp/CMakeLists.txt
+++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt
@@ -11,6 +11,7 @@ add_library(droiddeckwayland SHARED
src/gpu_clock_pin.c
src/droiddeck_ext.c
src/wl_dmabuf.c
+ src/wl_android_buffer.c
src/wl_clipboard.c
src/wl_text_input.c
src/wl_toplevel_icon.c
@@ -22,6 +23,7 @@ add_library(droiddeckwayland SHARED
generated/color-management-v1-protocol.c
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
+ generated/wayland-android-protocol.c
generated/viewporter-protocol.c
generated/banner-desktop-v1-protocol.c
generated/presentation-time-protocol.c
diff --git a/app/src/main/cpp/waylandcomp/generated/wayland-android-protocol.c b/app/src/main/cpp/waylandcomp/generated/wayland-android-protocol.c
new file mode 100644
index 0000000000..79e171faa2
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/generated/wayland-android-protocol.c
@@ -0,0 +1,104 @@
+/* Generated by wayland-scanner 1.26.0 */
+
+/*
+ * Copyright © 2012 Collabora, Ltd.
+ *
+ * Permission to use, copy, modify, distribute, and sell this
+ * software and its documentation for any purpose is hereby granted
+ * without fee, provided that the above copyright notice appear in
+ * all copies and that both that copyright notice and this permission
+ * notice appear in supporting documentation, and that the name of
+ * the copyright holders not be used in advertising or publicity
+ * pertaining to distribution of the software without specific,
+ * written prior permission. The copyright holders make no
+ * representations about the suitability of this software for any
+ * purpose. It is provided "as is" without express or implied
+ * warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
+ * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
+ * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+ * THIS SOFTWARE.
+ */
+
+#include
+#include
+#include
+#include "wayland-util.h"
+
+#ifndef __has_attribute
+# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
+#endif
+
+#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
+#define WL_PRIVATE __attribute__ ((visibility("hidden")))
+#else
+#define WL_PRIVATE
+#endif
+
+extern const struct wl_interface android_wlegl_handle_interface;
+extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
+extern const struct wl_interface wl_buffer_interface;
+
+static const struct wl_interface *android_types[] = {
+ NULL,
+ NULL,
+ &android_wlegl_handle_interface,
+ NULL,
+ NULL,
+ &wl_buffer_interface,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ &android_wlegl_handle_interface,
+ &android_wlegl_server_buffer_handle_interface,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ &wl_buffer_interface,
+ NULL,
+ NULL,
+};
+
+static const struct wl_message android_wlegl_requests[] = {
+ { "create_handle", "nia", android_types + 2 },
+ { "create_buffer", "niiiiio", android_types + 5 },
+ { "get_server_buffer_handle", "2niiii", android_types + 12 },
+};
+
+WL_PRIVATE const struct wl_interface android_wlegl_interface = {
+ "android_wlegl", 3,
+ 3, android_wlegl_requests,
+ 0, NULL,
+};
+
+static const struct wl_message android_wlegl_handle_requests[] = {
+ { "add_fd", "h", android_types + 0 },
+ { "destroy", "", android_types + 0 },
+};
+
+WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
+ "android_wlegl_handle", 1,
+ 2, android_wlegl_handle_requests,
+ 0, NULL,
+};
+
+static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
+ { "buffer_fd", "h", android_types + 0 },
+ { "buffer_ints", "a", android_types + 0 },
+ { "buffer", "nii", android_types + 17 },
+ { "linear_layout", "3uu", android_types + 0 },
+};
+
+WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
+ "android_wlegl_server_buffer_handle", 3,
+ 0, NULL,
+ 4, android_wlegl_server_buffer_handle_events,
+};
diff --git a/app/src/main/cpp/waylandcomp/generated/wayland-android-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/wayland-android-server-protocol.h
new file mode 100644
index 0000000000..0fd3b6d68f
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/generated/wayland-android-server-protocol.h
@@ -0,0 +1,341 @@
+/* Generated by wayland-scanner 1.26.0 */
+
+#ifndef ANDROID_SERVER_PROTOCOL_H
+#define ANDROID_SERVER_PROTOCOL_H
+
+#include
+#include
+#include "wayland-server.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct wl_client;
+struct wl_resource;
+
+/**
+ * @page page_android The android protocol
+ * @section page_ifaces_android Interfaces
+ * - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
+ * - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
+ * - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
+ * @section page_copyright_android Copyright
+ *
+ *
+ * Copyright © 2012 Collabora, Ltd.
+ *
+ * Permission to use, copy, modify, distribute, and sell this
+ * software and its documentation for any purpose is hereby granted
+ * without fee, provided that the above copyright notice appear in
+ * all copies and that both that copyright notice and this permission
+ * notice appear in supporting documentation, and that the name of
+ * the copyright holders not be used in advertising or publicity
+ * pertaining to distribution of the software without specific,
+ * written prior permission. The copyright holders make no
+ * representations about the suitability of this software for any
+ * purpose. It is provided "as is" without express or implied
+ * warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
+ * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
+ * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+ * THIS SOFTWARE.
+ *
+ */
+struct android_wlegl;
+struct android_wlegl_handle;
+struct android_wlegl_server_buffer_handle;
+struct wl_buffer;
+
+#ifndef ANDROID_WLEGL_INTERFACE
+#define ANDROID_WLEGL_INTERFACE
+/**
+ * @page page_iface_android_wlegl android_wlegl
+ * @section page_iface_android_wlegl_desc Description
+ *
+ * Interface used in the Android wrapper libEGL to share
+ * graphics buffers between the server and the client.
+ * @section page_iface_android_wlegl_api API
+ * See @ref iface_android_wlegl.
+ */
+/**
+ * @defgroup iface_android_wlegl The android_wlegl interface
+ *
+ * Interface used in the Android wrapper libEGL to share
+ * graphics buffers between the server and the client.
+ */
+extern const struct wl_interface android_wlegl_interface;
+#endif
+#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
+#define ANDROID_WLEGL_HANDLE_INTERFACE
+/**
+ * @page page_iface_android_wlegl_handle android_wlegl_handle
+ * @section page_iface_android_wlegl_handle_desc Description
+ *
+ * The Android native_handle_t is a semi-opaque object, that
+ * contains an EGL implementation specific number of int32
+ * values and file descriptors.
+ *
+ * We cannot send a variable size array of file descriptors
+ * over the Wayland protocol, so we send them one by one.
+ * @section page_iface_android_wlegl_handle_api API
+ * See @ref iface_android_wlegl_handle.
+ */
+/**
+ * @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
+ *
+ * The Android native_handle_t is a semi-opaque object, that
+ * contains an EGL implementation specific number of int32
+ * values and file descriptors.
+ *
+ * We cannot send a variable size array of file descriptors
+ * over the Wayland protocol, so we send them one by one.
+ */
+extern const struct wl_interface android_wlegl_handle_interface;
+#endif
+#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
+/**
+ * @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
+ * @section page_iface_android_wlegl_server_buffer_handle_desc Description
+ *
+ * On creation a server_side_buffer object will immediately send
+ * the "buffer_fd" and "buffer_ints" events needed by the client to
+ * reference the gralloc buffer, followed by the "buffer" event carrying
+ * the wl_buffer object.
+ * @section page_iface_android_wlegl_server_buffer_handle_api API
+ * See @ref iface_android_wlegl_server_buffer_handle.
+ */
+/**
+ * @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
+ *
+ * On creation a server_side_buffer object will immediately send
+ * the "buffer_fd" and "buffer_ints" events needed by the client to
+ * reference the gralloc buffer, followed by the "buffer" event carrying
+ * the wl_buffer object.
+ */
+extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
+#endif
+
+#ifndef ANDROID_WLEGL_ERROR_ENUM
+#define ANDROID_WLEGL_ERROR_ENUM
+enum android_wlegl_error {
+ ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
+ ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
+};
+#endif /* ANDROID_WLEGL_ERROR_ENUM */
+
+#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
+#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
+/**
+ * @ingroup iface_android_wlegl
+ * Validate a android_wlegl error value.
+ *
+ * @return true on success, false on error.
+ * @ref android_wlegl_error
+ */
+static inline bool
+android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
+ switch (value) {
+ case ANDROID_WLEGL_ERROR_BAD_HANDLE:
+ return version >= 1;
+ case ANDROID_WLEGL_ERROR_BAD_VALUE:
+ return version >= 1;
+ default:
+ return false;
+ }
+}
+#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
+
+/**
+ * @ingroup iface_android_wlegl
+ * @struct android_wlegl_interface
+ */
+struct android_wlegl_interface {
+ /**
+ * Create an Android native_handle_t object
+ *
+ * This creator method initialises the native_handle_t object
+ * with everything except the file descriptors, which have to be
+ * submitted separately.
+ * @param ints an array of int32_t
+ */
+ void (*create_handle)(struct wl_client *client,
+ struct wl_resource *resource,
+ uint32_t id,
+ int32_t num_fds,
+ struct wl_array *ints);
+ /**
+ * Create a wl_buffer from the native handle
+ *
+ * Pass the Android native_handle_t to the server and attach it
+ * to the new wl_buffer object.
+ *
+ * The android_wlegl_handle object must be destroyed immediately
+ * after this request.
+ */
+ void (*create_buffer)(struct wl_client *client,
+ struct wl_resource *resource,
+ uint32_t id,
+ int32_t width,
+ int32_t height,
+ int32_t stride,
+ int32_t format,
+ int32_t usage,
+ struct wl_resource *native_handle);
+ /**
+ * @since 2
+ */
+ void (*get_server_buffer_handle)(struct wl_client *client,
+ struct wl_resource *resource,
+ uint32_t id,
+ int32_t width,
+ int32_t height,
+ int32_t format,
+ int32_t usage);
+};
+
+
+/**
+ * @ingroup iface_android_wlegl
+ */
+#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
+/**
+ * @ingroup iface_android_wlegl
+ */
+#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
+/**
+ * @ingroup iface_android_wlegl
+ */
+#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
+
+#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
+#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
+enum android_wlegl_handle_error {
+ ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
+};
+#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
+
+#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
+#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
+/**
+ * @ingroup iface_android_wlegl_handle
+ * Validate a android_wlegl_handle error value.
+ *
+ * @return true on success, false on error.
+ * @ref android_wlegl_handle_error
+ */
+static inline bool
+android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
+ switch (value) {
+ case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
+ return version >= 1;
+ default:
+ return false;
+ }
+}
+#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
+
+/**
+ * @ingroup iface_android_wlegl_handle
+ * @struct android_wlegl_handle_interface
+ */
+struct android_wlegl_handle_interface {
+ /**
+ */
+ void (*add_fd)(struct wl_client *client,
+ struct wl_resource *resource,
+ int32_t fd);
+ /**
+ */
+ void (*destroy)(struct wl_client *client,
+ struct wl_resource *resource);
+};
+
+
+/**
+ * @ingroup iface_android_wlegl_handle
+ */
+#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
+/**
+ * @ingroup iface_android_wlegl_handle
+ */
+#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
+
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
+
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ */
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ */
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ */
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ */
+#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
+
+
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ * Sends an buffer_fd event to the client owning the resource.
+ * @param resource_ The client's resource
+ */
+static inline void
+android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
+{
+ wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
+}
+
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ * Sends an buffer_ints event to the client owning the resource.
+ * @param resource_ The client's resource
+ */
+static inline void
+android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
+{
+ wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
+}
+
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ * Sends an buffer event to the client owning the resource.
+ * @param resource_ The client's resource
+ */
+static inline void
+android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
+{
+ wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
+}
+
+/**
+ * @ingroup iface_android_wlegl_server_buffer_handle
+ * Sends an linear_layout event to the client owning the resource.
+ * @param resource_ The client's resource
+ */
+static inline void
+android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
+{
+ wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/app/src/main/cpp/waylandcomp/protocols/wayland-android.xml b/app/src/main/cpp/waylandcomp/protocols/wayland-android.xml
new file mode 100644
index 0000000000..de8a78b66e
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/protocols/wayland-android.xml
@@ -0,0 +1,139 @@
+
+
+
+
+ Copyright © 2012 Collabora, Ltd.
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that copyright notice and this permission
+ notice appear in supporting documentation, and that the name of
+ the copyright holders not be used in advertising or publicity
+ pertaining to distribution of the software without specific,
+ written prior permission. The copyright holders make no
+ representations about the suitability of this software for any
+ purpose. It is provided "as is" without express or implied
+ warranty.
+
+ THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
+ SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
+ AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+ THIS SOFTWARE.
+
+
+
+
+ Interface used in the Android wrapper libEGL to share
+ graphics buffers between the server and the client.
+
+
+
+
+
+
+
+
+
+ This creator method initialises the native_handle_t object
+ with everything except the file descriptors, which have to be
+ submitted separately.
+
+
+
+
+
+
+
+
+
+ Pass the Android native_handle_t to the server and attach it
+ to the new wl_buffer object.
+
+ The android_wlegl_handle object must be destroyed immediately
+ after this request.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ The Android native_handle_t is a semi-opaque object, that
+ contains an EGL implementation specific number of int32
+ values and file descriptors.
+
+ We cannot send a variable size array of file descriptors
+ over the Wayland protocol, so we send them one by one.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ On creation a server_side_buffer object will immediately send
+ the "buffer_fd" and "buffer_ints" events needed by the client to
+ reference the gralloc buffer, followed by the "buffer" event carrying
+ the wl_buffer object.
+
+
+
+
+
+
+
+
+
+ This event will be sent after the ints and all the fds have been sent
+
+
+
+
+
+
+
+ Optional metadata sent before the buffer event. The first buffer_fd
+ contains one uncompressed 32-bit RGB plane at byte offset zero.
+ drm_format is its DRM FourCC and stride is its row pitch in bytes.
+ The server has verified the layout and allocation bounds using
+ Android mapper metadata, not inferred them from opaque handle ints.
+ Absence of this event means the layout is unspecified.
+
+
+
+
+
+
+
diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
index cb44478354..e33b0c77b4 100644
--- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
+++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
@@ -79,6 +79,9 @@ static struct ahb_buf *find_buf(uint64_t id) {
}
static void buf_free(struct ahb_buf *ab) {
+ /* A display release does not prove the compositor's Vulkan reads finished.
+ * Keep the AHB reference and its DMA-BUF record even if the client is gone. */
+ if (vkp_completion_unknown()) return;
if (ab->resource) { wl_list_remove(&ab->resource_destroy.link); ab->resource = NULL; }
if (ab->fence_src) { wl_event_source_remove(ab->fence_src); ab->fence_src = NULL; }
if (ab->fence_fd >= 0) { close(ab->fence_fd); ab->fence_fd = -1; }
@@ -103,6 +106,7 @@ static void on_buffer_resource_destroyed(struct wl_listener *l, void *data) {
static void send_deferred_release(struct ahb_buf *ab) {
+ if (vkp_completion_unknown()) return;
if (ab->release_pending && ab->resource)
droiddeck_release_buffer(ab->surface, ab->resource, ab->surface != NULL, ab->deferred_ns);
ab->release_pending = 0;
diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c
index 471748a6d0..21ef1d23f9 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor.c
+++ b/app/src/main/cpp/waylandcomp/src/compositor.c
@@ -154,6 +154,16 @@ static void on_client_destroyed(struct wl_listener *l, void *data) {
free(ci);
}
+/* libwayland's own reasons for dropping a client (a failed read or flush, an invalid object, a
+ * malformed request) go through wl_log, which on Android writes to a closed stderr. */
+static void wl_log_to_session(const char *fmt, va_list ap) {
+ char line[512];
+ vsnprintf(line, sizeof(line), fmt, ap);
+ size_t n = strlen(line);
+ while (n && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0;
+ droiddeck_log("program", "libwayland: %s", line);
+}
+
static void on_client_created(struct wl_listener *l, void *data) {
struct wl_client *client = data;
struct client_info *ci = calloc(1, sizeof(*ci));
@@ -349,6 +359,62 @@ static void perf_note_release(int64_t since_ns) {
}
+/* Completion-unknown is terminal for externally owned DMA-BUF contents too.
+ * Keeping a VkImage alone cannot stop the client from overwriting its backing
+ * memory after wl_buffer.release. All paths (including cursors and idle roles)
+ * use this gate; copied SHM buffers retain their normal release behaviour. */
+static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer);
+static int buffer_release_blocked(struct wl_resource *buffer) {
+ return vkp_completion_unknown() && get_dmabuf(buffer) != NULL;
+}
+/* Buffer tracing on a GPU that is not an Adreno (no KGSL node): every attach and release of the
+ * first 400 buffer events, by wl_buffer id and the line that sent it, and any release of a buffer
+ * already released and not attached again since (gamescope: "Compositor released us but we were
+ * not acquired"). Off on an Adreno. */
+static int g_buf_trace = -1;
+static int g_buf_trace_left = 400;
+static uint32_t g_released_ids[128];
+static int buf_trace_on(void) {
+ if (g_buf_trace < 0) g_buf_trace = access("/dev/kgsl-3d0", F_OK) != 0;
+ return g_buf_trace;
+}
+static void buf_trace_attach(struct wl_resource *buffer) {
+ if (!buffer || !buf_trace_on()) return;
+ uint32_t id = wl_resource_get_id(buffer);
+ for (int i = 0; i < 128; i++) if (g_released_ids[i] == id) g_released_ids[i] = 0;
+ if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "attach id %u", id); }
+}
+static void buf_trace_release(struct wl_resource *buffer, int line) {
+ if (!buffer || !buf_trace_on()) return;
+ uint32_t id = wl_resource_get_id(buffer);
+ int twice = 0, slot = -1;
+ for (int i = 0; i < 128; i++) {
+ if (g_released_ids[i] == id) twice = 1;
+ if (slot < 0 && g_released_ids[i] == 0) slot = i;
+ }
+ if (twice) droiddeck_log("buffer", "DOUBLE release id %u (line %d): released again without an attach", id, line);
+ else if (slot >= 0) g_released_ids[slot] = id;
+ if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "release id %u (line %d)", id, line); }
+}
+
+#define send_buffer_release(b) send_buffer_release_at((b), __LINE__)
+static void send_buffer_release_at(struct wl_resource *buffer, int line) {
+ if (!buffer_release_blocked(buffer)) { buf_trace_release(buffer, line); wl_buffer_send_release(buffer); }
+}
+
+/* Whether a surface other than `except` is showing this buffer right now. gamescope's Wayland
+ * backend moves one buffer between its planes (the game's frame goes from the window to a
+ * subsurface above a black backing while a Steam notification is up): releasing it when the first
+ * surface lets go handed gamescope a buffer still on screen ("Compositor released us but we were
+ * not acquired"). Only the last surface to let go releases it. */
+static int buffer_shown_elsewhere(struct wl_resource *buffer, const struct surface *except) {
+ struct surface *o;
+ if (!buffer) return 0;
+ wl_list_for_each(o, &g_surfaces, link)
+ if (o != except && o->dmabuf == buffer) return 1;
+ return 0;
+}
+
static void pending_release_free(struct pending_release *pr) {
if (pr->surface && pr->surface->releases_pending > 0) pr->surface->releases_pending--;
wl_list_remove(&pr->destroy.link);
@@ -372,7 +438,8 @@ static void arm_release_timer(void) {
int64_t earliest = 0;
if (g_release_timer_fd < 0) return;
wl_list_for_each(pr, &g_pending_releases, link)
- if (!earliest || pr->at_ns < earliest) earliest = pr->at_ns;
+ if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
+ earliest = pr->at_ns;
struct itimerspec its = {0};
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
@@ -384,8 +451,13 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
int64_t now = now_ns() + 300000;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
- if (pr->at_ns <= now) {
- wl_buffer_send_release(pr->buffer);
+ if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
+ /* Attached again since (to its surface or another): that surface releases it later. */
+ if (buffer_shown_elsewhere(pr->buffer, NULL)) {
+ pending_release_free(pr);
+ continue;
+ }
+ send_buffer_release(pr->buffer);
perf_note_release(pr->since_ns);
pending_release_free(pr);
}
@@ -396,9 +468,12 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
}
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
+ /* No allocation or immediate-release fallback is allowed for a quarantined
+ * DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
+ if (buffer_release_blocked(buffer)) return;
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
- if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
+ if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
@@ -406,7 +481,7 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_
if (at > latest) at = latest;
s->next_release_ns = at;
struct pending_release *pr = calloc(1, sizeof(*pr));
- if (!pr) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
+ if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
pr->buffer = buffer;
pr->surface = s;
pr->at_ns = at;
@@ -523,7 +598,10 @@ static void constraints_focus_entered(struct wl_resource *target, struct wl_clie
void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
- if (!b || --b->refs > 0) return;
+ /* Surface/client destruction must not close the backing FDs or free the
+ * imported-buffer record while a GPU read may still be pending. Retain the
+ * reference without allocating a quarantine node; process exit reclaims it. */
+ if (!b || vkp_completion_unknown() || --b->refs > 0) return;
vkp_image_destroy(b->img);
for (int i = 0; i < b->n_planes; i++)
if (b->fd[i] >= 0) close(b->fd[i]);
@@ -622,9 +700,10 @@ static void unmap_toplevel(struct surface *s) {
static void drop_dmabuf(struct surface *s, int paced) {
if (s->dmabuf) {
wl_list_remove(&s->dmabuf_destroy.link);
- if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
+ if (buffer_shown_elsewhere(s->dmabuf, s)) {
+ } else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (paced) release_buffer(s, s->dmabuf, now_ns());
- else wl_buffer_send_release(s->dmabuf);
+ else send_buffer_release(s->dmabuf);
}
s->dmabuf = NULL;
}
@@ -733,7 +812,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
vkp_image_upload_shm(s->shm_img, wl_shm_buffer_get_data(shm), stride);
wl_shm_buffer_end_access(shm);
}
- wl_buffer_send_release(buffer);
+ send_buffer_release(buffer);
s->buf_w = w;
s->buf_h = h;
s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
@@ -777,7 +856,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
}
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4);
- wl_buffer_send_release(buffer);
+ send_buffer_release(buffer);
s->buf_w = 1;
s->buf_h = 1;
s->buf_alpha = bgra[3] != 0xff;
@@ -880,8 +959,9 @@ void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->ahb_state
void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
+ if (buffer_release_blocked(buffer)) return;
if (paced && s) release_buffer(s, buffer, since_ns);
- else { wl_buffer_send_release(buffer); perf_note_release(since_ns); }
+ else { send_buffer_release(buffer); perf_note_release(since_ns); }
}
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
const struct droiddeck_color *droiddeck_surface_color(const struct surface *s) {
@@ -1101,7 +1181,7 @@ static void surface_hold_idle(struct surface *s, struct wl_resource *buffer) {
struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer);
int64_t px = db ? (int64_t)db->width * db->height
: shm ? (int64_t)wl_shm_buffer_get_width(shm) * wl_shm_buffer_get_height(shm) : 0;
- if (px <= 0 || px > CURSOR_MAX_PX) { wl_buffer_send_release(buffer); return; }
+ if (px <= 0 || px > CURSOR_MAX_PX) { send_buffer_release(buffer); return; }
s->idle_buffer = buffer;
s->idle_buffer_destroy.notify = on_idle_buffer_destroyed;
wl_resource_add_destroy_listener(buffer, &s->idle_buffer_destroy);
@@ -1119,7 +1199,7 @@ static struct wl_resource *surface_take_idle(struct surface *s) {
static void surface_drop_idle(struct surface *s) {
surface_forget_idle_px(s);
struct wl_resource *buffer = surface_take_idle(s);
- if (buffer) wl_buffer_send_release(buffer);
+ if (buffer) send_buffer_release(buffer);
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
@@ -1172,11 +1252,12 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
cursor_publish_hidden();
} else {
cursor_publish_buffer(s, buffer);
- wl_buffer_send_release(buffer);
+ send_buffer_release(buffer);
}
} else if (s->role == ROLE_NONE) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
+ buf_trace_attach(buffer);
take_dmabuf(s, db, buffer);
} else if (shm) {
drop_dmabuf(s, 1);
@@ -1187,7 +1268,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else {
drop_dmabuf(s, 1);
s->has_content = 0;
- if (buffer) wl_buffer_send_release(buffer);
+ if (buffer) send_buffer_release(buffer);
}
}
@@ -2437,7 +2518,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) {
cursor_publish_buffer(s, buffer);
- wl_buffer_send_release(buffer);
+ send_buffer_release(buffer);
} else if (g_cursor_shown == s) {
cursor_publish_shown();
} else if (s->idle_px) {
@@ -3836,6 +3917,10 @@ int droiddeck_wayland_run(void) {
return 1;
}
droiddeck_log("display", "Wayland compositor listening on %s/wayland-0", rt ? rt : "?");
+ wl_log_set_handler_server(wl_log_to_session);
+ /* A client that falls behind reading (gamescope at a few fps) must not be dropped for a full
+ * event buffer: libwayland's default is 4 KB per direction. */
+ wl_display_set_default_max_buffer_size(display, 1u << 20);
wl_display_add_client_created_listener(display, &g_client_created);
wl_global_create(display, &wl_compositor_interface, 6, NULL, bind_compositor);
@@ -3846,6 +3931,7 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
+ droiddeck_android_wlegl_init(display);
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
diff --git a/app/src/main/cpp/waylandcomp/src/compositor_internal.h b/app/src/main/cpp/waylandcomp/src/compositor_internal.h
index 0e4229d0a4..c70f9dd193 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor_internal.h
+++ b/app/src/main/cpp/waylandcomp/src/compositor_internal.h
@@ -61,3 +61,6 @@ extern volatile int g_no_render_node;
COMPOSITOR_INTERNAL extern dev_t g_main_device;
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
+
+/* ---- wl_android_buffer.c */
+COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.c b/app/src/main/cpp/waylandcomp/src/effects_chain.c
index aa5e5cb9dd..b73c92f711 100644
--- a/app/src/main/cpp/waylandcomp/src/effects_chain.c
+++ b/app/src/main/cpp/waylandcomp/src/effects_chain.c
@@ -1,5 +1,6 @@
#define _POSIX_C_SOURCE 200809L
#include "effects_chain.h"
+#include "blend_pass.h"
#include "vk_loader.h"
#include "vk_present.h"
#include
@@ -146,6 +147,16 @@ int vkp_effects_active(void) {
return spatial_mode(g_cur.scaling) || effect_count(&g_cur) > 0;
}
+int vkp_effects_upscaling(void) {
+ vkp_effects_sync();
+ return spatial_mode(g_cur.scaling) && g_cur.scaling != 6;
+}
+
+int vkp_effects_postprocessing(void) {
+ vkp_effects_sync();
+ return effect_count(&g_cur) > 0;
+}
+
VkFilter vkp_effects_blit_filter(void) {
vkp_effects_sync();
return g_cur.scaling == 2 ? VK_FILTER_NEAREST : VK_FILTER_LINEAR;
@@ -233,6 +244,7 @@ static VkImageView make_view(VkImage img, VkFormat fmt) {
}
static void target_destroy(struct fx_target *t) {
+ if (t->img) blendp_forget_image(t->img);
if (t->ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &t->ds);
if (t->fb) g_vk.DestroyFramebuffer(g_dev, t->fb, NULL);
if (t->view) g_vk.DestroyImageView(g_dev, t->view, NULL);
diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.h b/app/src/main/cpp/waylandcomp/src/effects_chain.h
index 50e5e34942..9e9ad6859b 100644
--- a/app/src/main/cpp/waylandcomp/src/effects_chain.h
+++ b/app/src/main/cpp/waylandcomp/src/effects_chain.h
@@ -10,6 +10,9 @@ int vkp_effects_sync(void);
int vkp_effects_active(void);
+int vkp_effects_upscaling(void);
+int vkp_effects_postprocessing(void);
+
VkFilter vkp_effects_blit_filter(void);
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
diff --git a/app/src/main/cpp/waylandcomp/src/vk_external_image_sync.h b/app/src/main/cpp/waylandcomp/src/vk_external_image_sync.h
new file mode 100644
index 0000000000..676c36a145
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/vk_external_image_sync.h
@@ -0,0 +1,47 @@
+#ifndef VK_EXTERNAL_IMAGE_SYNC_H
+#define VK_EXTERNAL_IMAGE_SYNC_H
+
+#include
+
+struct vkp_external_client_barrier_pair {
+ VkImageMemoryBarrier acquire;
+ VkImageMemoryBarrier release;
+};
+
+static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
+ return dmabuf && !blit_dst;
+}
+
+/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
+ * FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
+ * acquire/release lifecycle and must never take this source-image path. */
+static inline int vkp_external_client_barrier_pair(
+ VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
+ struct vkp_external_client_barrier_pair *pair) {
+ if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
+
+ const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
+ pair->acquire = (VkImageMemoryBarrier){
+ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
+ .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
+ .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
+ .dstQueueFamilyIndex = queue_family,
+ .image = image,
+ .subresourceRange = range,
+ .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
+ };
+ pair->release = (VkImageMemoryBarrier){
+ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
+ .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
+ .newLayout = VK_IMAGE_LAYOUT_GENERAL,
+ .srcQueueFamilyIndex = queue_family,
+ .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
+ .image = image,
+ .subresourceRange = range,
+ .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
+ };
+ return 1;
+}
+
+#endif
diff --git a/app/src/main/cpp/waylandcomp/src/vk_loader.h b/app/src/main/cpp/waylandcomp/src/vk_loader.h
index 54cb888816..2f5701dd6b 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_loader.h
+++ b/app/src/main/cpp/waylandcomp/src/vk_loader.h
@@ -12,7 +12,7 @@
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
X(GetDeviceProcAddr) X(EnumerateDeviceExtensionProperties) \
X(GetPhysicalDeviceMemoryProperties) X(GetPhysicalDeviceFormatProperties2) \
- X(GetPhysicalDeviceImageFormatProperties2)
+ X(GetPhysicalDeviceImageFormatProperties2) X(GetPhysicalDeviceProperties2)
#define VK_DEVICE_FUNCS(X) \
X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c
index 895e1f6b47..8d0267cc13 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.c
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.c
@@ -1,6 +1,7 @@
#define _POSIX_C_SOURCE 200809L
#include "vk_present.h"
#include "vk_loader.h"
+#include "vk_external_image_sync.h"
#include "sc_layer.h"
#include "effects_chain.h"
#include "cardboard.h"
@@ -19,6 +20,7 @@
#include
#include
#include
+#include
#include
#include
@@ -38,16 +40,59 @@ struct vkp_image {
int in_general;
VkFormat fmt;
int sampled;
+ AHardwareBuffer *android_buffer;
};
static ANativeWindow *g_window;
static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_dev_state;
+static void device_lost(const char *where);
+static const char *vk_result_name(VkResult r);
+
+/* Why the compositor cannot present ("" while it can). Logged as a DD_PRESENT_FAULT line, read
+ * back over JNI, and shown on the session-ended screen instead of a silent black one. */
+static char g_fault[256];
+static char g_swap_reason[160];
+static pthread_mutex_t g_fault_lock = PTHREAD_MUTEX_INITIALIZER;
+static void set_fault(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
+static void set_fault(const char *fmt, ...) {
+ char msg[sizeof(g_fault)];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(msg, sizeof(msg), fmt, ap);
+ va_end(ap);
+ pthread_mutex_lock(&g_fault_lock);
+ int same = !strcmp(msg, g_fault);
+ if (!same) snprintf(g_fault, sizeof(g_fault), "%s", msg);
+ pthread_mutex_unlock(&g_fault_lock);
+ if (!same) droiddeck_log("present", "DD_PRESENT_FAULT: %s", msg);
+}
+static void clear_fault(void) {
+ pthread_mutex_lock(&g_fault_lock);
+ int had = g_fault[0] != 0;
+ g_fault[0] = 0;
+ pthread_mutex_unlock(&g_fault_lock);
+ if (had) droiddeck_log("present", "presentation recovered: fault cleared");
+}
+const char *vkp_fault(void) {
+ static __thread char copy[sizeof(g_fault)];
+ pthread_mutex_lock(&g_fault_lock);
+ snprintf(copy, sizeof(copy), "%s", g_fault);
+ pthread_mutex_unlock(&g_fault_lock);
+ if (!copy[0] && g_dev_state == -3)
+ snprintf(copy, sizeof(copy), "the GPU did not confirm the compositor's work finished; presenting stopped");
+ return copy;
+}
+
+/* The driver that answered for the display, as the driver itself reports it. */
+static char g_display_driver[320];
+const char *vkp_display_driver(void) { return g_display_driver; }
static VkInstance g_inst;
static VkPhysicalDevice g_pd;
static VkDevice g_dev;
static VkQueue g_queue;
+static PFN_vkGetAndroidHardwareBufferPropertiesANDROID g_ahb_properties;
static uint32_t g_qfam;
static VkCommandPool g_pool;
#define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS)
@@ -108,10 +153,22 @@ static void perf_add(int64_t *sum, int64_t *max, unsigned *count, int64_t d) {
if (d > *max) *max = d;
(*count)++;
}
+static void quarantine_pending_work(VkResult result, const char *where) {
+ if (g_dev_state != 1) return;
+ g_dev_state = -3;
+ g_base_black = 0;
+ LOGE("GPU completion unconfirmed (%d in %s): presenting stopped; pending resources retained; "
+ "restart DroidDeck", (int)result, where);
+}
+
static VkResult timed_wait(VkFence fence, uint64_t timeout) {
+ if (g_dev_state != 1)
+ return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
int64_t t0 = perf_now();
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
+ if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
+ quarantine_pending_work(r, "fence wait");
return r;
}
@@ -206,7 +263,12 @@ static void reset_sync(void) {
static void destroy_swapchain(void) {
g_base_black = 0;
if (g_dev_state != 1) return;
- g_vk.DeviceWaitIdle(g_dev);
+ VkResult idle = g_vk.DeviceWaitIdle(g_dev);
+ if (idle != VK_SUCCESS) {
+ if (idle == VK_ERROR_DEVICE_LOST) device_lost("swapchain idle");
+ else quarantine_pending_work(idle, "swapchain idle");
+ return;
+ }
reset_sync();
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
@@ -296,6 +358,7 @@ int vkp_has_window(void) {
}
int vkp_device_lost(void) { return g_dev_state == -2; }
+int vkp_completion_unknown(void) { return g_dev_state == -3; }
void vk_present_set_scale_mode(int mode, int alignment) {
if (mode < VKP_MODE_OFF || mode > VKP_MODE_INTEGER) mode = VKP_MODE_FIT;
@@ -406,11 +469,43 @@ static int has_ext(VkExtensionProperties *e, uint32_t n, const char *name) {
return 0;
}
+static int is_proprietary(VkDriverId id) {
+ return id == VK_DRIVER_ID_ARM_PROPRIETARY || id == VK_DRIVER_ID_QUALCOMM_PROPRIETARY ||
+ id == VK_DRIVER_ID_IMAGINATION_PROPRIETARY || id == VK_DRIVER_ID_SAMSUNG_PROPRIETARY ||
+ id == VK_DRIVER_ID_BROADCOM_PROPRIETARY;
+}
+
+/* What really loaded: adrenotools falls back to the vendor driver when the requested one fails
+ * to load (hook_impl.cpp), so the name asked for is not proof of the driver in use. */
+static void log_display_driver(void) {
+ PFN_vkGetPhysicalDeviceProperties2 props2 = g_vk.GetPhysicalDeviceProperties2;
+ VkPhysicalDeviceDriverProperties drv = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
+ VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &drv};
+ if (!props2) {
+ snprintf(g_display_driver, sizeof(g_display_driver), "%.200s (driver properties not available)", g_gpu_name);
+ droiddeck_log("gpu", "display driver: %s", g_display_driver);
+ return;
+ }
+ props2(g_pd, &p2);
+ int fell_back = g_library_name && is_proprietary(drv.driverID);
+ snprintf(g_display_driver, sizeof(g_display_driver), "%.80s: %.64s %.96s (driver id %d, Vulkan %u.%u.%u)%s", p2.properties.deviceName,
+ drv.driverName, drv.driverInfo, (int)drv.driverID, VK_API_VERSION_MAJOR(p2.properties.apiVersion),
+ VK_API_VERSION_MINOR(p2.properties.apiVersion), VK_API_VERSION_PATCH(p2.properties.apiVersion),
+ fell_back ? " - FELL BACK to the phone's own driver" : "");
+ droiddeck_log("gpu", "display driver loaded: %s", g_display_driver);
+ if (fell_back)
+ droiddeck_log("gpu", "display driver: %s was requested but the phone's own driver answered; the requested "
+ "driver did not load (a missing library beside it, or a rejected ABI - see the adrenotools lines)",
+ g_library_name);
+}
+
static int dev_init(void) {
if (g_dev_state != 0) return g_dev_state == 1 ? 0 : -1;
if (vk_loader_open(g_driver_path, g_library_name, g_native_lib_dir) != 0) {
- LOGE("present: vk_loader_open failed"); g_dev_state = -1; return -1;
+ LOGE("present: vk_loader_open failed"); g_dev_state = -1;
+ set_fault("no Vulkan driver could be loaded for the display (%s)", g_library_name ? g_library_name : "libvulkan.so");
+ return -1;
}
const char *inst_exts[3] = {VK_KHR_SURFACE_EXTENSION_NAME,
@@ -441,13 +536,19 @@ static int dev_init(void) {
.enabledExtensionCount = n_inst_exts,
.ppEnabledExtensionNames = inst_exts};
if (g_vk.CreateInstance(&ici, NULL, &g_inst) != VK_SUCCESS) {
- LOGE("present: vkCreateInstance failed"); g_dev_state = -1; return -1;
+ LOGE("present: vkCreateInstance failed"); g_dev_state = -1;
+ set_fault("vkCreateInstance failed on the display driver (%s)", g_library_name ? g_library_name : "the phone's own");
+ return -1;
}
vk_loader_load_instance(g_inst);
uint32_t npd = 0;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, NULL);
- if (!npd) { LOGE("present: no physical devices"); g_dev_state = -1; return -1; }
+ if (!npd) {
+ LOGE("present: no physical devices"); g_dev_state = -1;
+ set_fault("the display driver exposed no GPU to the app");
+ return -1;
+ }
VkPhysicalDevice pds[8]; if (npd > 8) npd = 8;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, pds);
g_pd = VK_NULL_HANDLE;
@@ -459,7 +560,11 @@ static int dev_init(void) {
for (uint32_t q = 0; q < nq; q++)
if (qs[q].queueFlags & VK_QUEUE_GRAPHICS_BIT) { g_pd = pds[i]; g_qfam = q; break; }
}
- if (g_pd == VK_NULL_HANDLE) { LOGE("present: no graphics queue"); g_dev_state = -1; return -1; }
+ if (g_pd == VK_NULL_HANDLE) {
+ LOGE("present: no graphics queue"); g_dev_state = -1;
+ set_fault("the display GPU offers no graphics queue");
+ return -1;
+ }
{
VkPhysicalDeviceProperties props;
g_vk.GetPhysicalDeviceProperties(g_pd, &props);
@@ -479,6 +584,21 @@ 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);
+ if (!g_library_name || !strstr(g_library_name, "freedreno")) {
+ char names[440];
+ size_t len = 0;
+ names[0] = 0;
+ droiddeck_log("gpu", "device extensions: %u", ne);
+ for (uint32_t i = 0; i < ne; i++) {
+ if (len + strlen(exts[i].extensionName) + 2 > sizeof(names)) {
+ droiddeck_log("gpu", " %s", names);
+ len = 0;
+ names[0] = 0;
+ }
+ len += (size_t)snprintf(names + len, sizeof(names) - len, "%s%s", len ? " " : "", exts[i].extensionName);
+ }
+ if (len) droiddeck_log("gpu", " %s", names);
+ }
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]);
@@ -492,6 +612,8 @@ static int dev_init(void) {
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
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);
+ /* The present path's own AHB import (#561) stays on the phone's own driver. */
+ const int want_ahb = !g_library_name && g_ahb_import;
if (g_ahb_import) {
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
@@ -514,11 +636,17 @@ static int dev_init(void) {
dr = g_vk.CreateDevice(g_pd, &dci, NULL, &g_dev);
}
if (dr != VK_SUCCESS) {
- LOGE("present: vkCreateDevice failed"); g_dev_state = -1; return -1;
+ LOGE("present: vkCreateDevice failed"); g_dev_state = -1;
+ set_fault("vkCreateDevice failed on %s (%s)", g_gpu_name[0] ? g_gpu_name : "the display GPU", vk_result_name(dr));
+ return -1;
}
vk_loader_load_device(g_dev);
+ log_display_driver();
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
vkp_gpu_busy_device(g_pd, g_dev, g_qfam);
+ if (want_ahb)
+ g_ahb_properties = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)
+ g_vk.GetDeviceProcAddr(g_dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
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};
@@ -555,6 +683,7 @@ static int dev_init(void) {
g_dev_state = 1;
reset_sync();
init_black_image();
+ if (g_dev_state != 1) return -1;
vkp_framegen_device_ready(g_dev, g_queue, g_qfam, fg_features != NULL);
return 0;
}
@@ -566,13 +695,15 @@ static int swap_init_locked(void);
static int swap_init(void) {
struct timespec ts;
int64_t now;
- if (!g_window) return -1;
+ if (!g_window || g_dev_state != 1) return -1;
clock_gettime(CLOCK_MONOTONIC, &ts);
now = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
if (now < g_swap_retry_at_ns) return -1;
+ g_swap_reason[0] = 0;
if (swap_init_locked() == 0) {
g_swap_retry_at_ns = 0;
g_swap_fail_logged = 0;
+ clear_fault();
return 0;
}
destroy_swapchain();
@@ -580,11 +711,12 @@ static int swap_init(void) {
if (!g_swap_fail_logged) {
g_swap_fail_logged = 1;
LOGE("present: no swapchain on the screen surface; retrying every 0.5 s");
+ set_fault("no swapchain on the session screen (%s)", g_swap_reason[0] ? g_swap_reason : "unknown reason");
}
return -1;
}
-#define SWLOGE(...) do { if (!g_swap_fail_logged) LOGE(__VA_ARGS__); } while (0)
+#define SWLOGE(...) do { snprintf(g_swap_reason, sizeof(g_swap_reason), __VA_ARGS__); if (!g_swap_fail_logged) LOGE(__VA_ARGS__); } while (0)
static void vk_format_short(VkFormat f, char *out, size_t n) {
const char *s = NULL;
@@ -824,10 +956,15 @@ static void init_black_image(void) {
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
- if (g_vk.QueueSubmit(g_queue, 1, &si, g_fence) == VK_SUCCESS &&
- g_vk.WaitForFences(g_dev, 1, &g_fence, VK_TRUE, 1000000000ULL) == VK_SUCCESS)
- g_black_state = 1;
- else
+ VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
+ if (qr == VK_SUCCESS) {
+ VkResult fr = timed_wait(g_fence, 1000000000ULL);
+ if (fr == VK_SUCCESS) g_black_state = 1;
+ else if (fr == VK_ERROR_DEVICE_LOST) device_lost("black image");
+ } else if (qr == VK_ERROR_DEVICE_LOST) {
+ device_lost("black image submit");
+ }
+ if (g_black_state != 1)
droiddeck_log("gpu", "letterbox black image unavailable: the whole output is cleared every copy-path frame");
}
@@ -926,7 +1063,98 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
}
-int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
+/* Return client sources to FOREIGN after their final read. The consuming paths
+ * wait for our fence before Wayland can release an ordinary dma-buf or an
+ * android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
+ * these image-layout and ownership transfers. */
+static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
+ struct vkp_external_client_barrier_pair pair;
+ if (!img || !vkp_external_client_barrier_pair(
+ img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
+ return;
+ g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
+ VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
+}
+
+static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
+ for (int i = 0; i < count; i++) {
+ int seen = 0;
+ for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
+ if (!seen) release_external_client_image(cmd, draws[i].img);
+ }
+}
+
+int vkp_image_is_dmabuf(const struct vkp_image *img) {
+ return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
+}
+
+int vkp_android_buffer_supported(void) {
+ return dev_init() == 0 && g_ahb_properties != NULL;
+}
+
+struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
+ if (!buffer || !vkp_android_buffer_supported()) return NULL;
+ AHardwareBuffer_Desc desc;
+ AHardwareBuffer_describe(buffer, &desc);
+ if (!desc.width || !desc.height || desc.layers != 1 ||
+ (desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
+ !(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
+ VkAndroidHardwareBufferFormatPropertiesANDROID format = {
+ .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
+ VkAndroidHardwareBufferPropertiesANDROID props = {
+ .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
+ VkResult result = g_ahb_properties(g_dev, buffer, &props);
+ if (result != VK_SUCCESS ||
+ (format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
+ format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
+ !props.memoryTypeBits ||
+ !(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
+ LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
+ vk_result_name(result), format.format);
+ return NULL;
+ }
+ struct vkp_image *img = calloc(1, sizeof(*img));
+ if (!img) return NULL;
+ img->w = (int)desc.width; img->h = (int)desc.height;
+ img->fmt = format.format; img->dmabuf = 1;
+ const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
+ VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
+ img->sampled = (format.formatFeatures & sampled) == sampled;
+ VkExternalMemoryImageCreateInfo external = {
+ .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
+ .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
+ VkImageCreateInfo create = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
+ .imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
+ .extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
+ .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
+ .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
+ .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
+ result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
+ if (result != VK_SUCCESS) goto fail;
+ /* AHB image requirements are not queryable before binding. The AHB query supplies them. */
+ uint32_t memory_type = 0;
+ while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
+ VkImportAndroidHardwareBufferInfoANDROID import = {
+ .sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
+ VkMemoryDedicatedAllocateInfo dedicated = {
+ .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
+ .pNext = &import, .image = img->image};
+ VkMemoryAllocateInfo allocate = {
+ .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
+ .allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
+ result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
+ if (result != VK_SUCCESS) goto fail;
+ result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
+ if (result != VK_SUCCESS) goto fail;
+ AHardwareBuffer_acquire(buffer);
+ img->android_buffer = buffer;
+ return img;
+fail:
+ LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
+ vkp_image_destroy(img);
+ return NULL;
+}
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
uint32_t stride, uint32_t offset, int as_blit_dst) {
@@ -940,7 +1168,27 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
+ /* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
+ * or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
+ {
+ static struct { uint32_t fmt; uint64_t mod; int w, h; } seen[32];
+ static int nseen;
+ int known = 0;
+ for (int i = 0; i < nseen; i++)
+ if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1;
+ if (!known && nseen < 32) {
+ seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++;
+ droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s",
+ drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff,
+ vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt,
+ img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "");
+ }
+ }
+ /* Venus reports a row pitch of 0 for gamescope's 1x1 root buffer, and a zero pitch fails
+ * vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned
+ * row is what a linear buffer that small holds. */
+ if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u;
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
@@ -1211,7 +1459,7 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
}
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
- if (!img || !img->map || !data) return;
+ if (g_dev_state != 1 || !img || !img->map || !data) return;
size_t rowbytes = (size_t)img->w * 4;
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
for (int y = 0; y < img->h; y++)
@@ -1224,12 +1472,14 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
void vkp_image_destroy(struct vkp_image *img) {
if (!img) return;
+ if (g_dev_state == -3) return; /* completion unknown: retain GPU ownership */
if (g_dev) {
blendp_forget_image(img->image);
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
}
+ if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img);
}
@@ -1271,17 +1521,99 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
return map_draw(d, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, (float)scene_w, (float)scene_h, blit);
}
+static int effects_source_draw(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
+ struct vkp_draw *out) {
+ if (!draws) return 0;
+ int opaque_above = 0;
+ for (int i = n - 1; i >= 0; i--) {
+ const struct vkp_draw *d = &draws[i];
+ const struct vkp_image *im = d->img;
+ if (!im || d->blend || d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) {
+ if (im && !d->blend && d->dw * d->dh > opaque_above) opaque_above = d->dw * d->dh;
+ continue;
+ }
+ if (opaque_above > im->w * im->h) return 0;
+ if (d->sx != 0 || d->sy != 0 || d->sw <= im->w - 1.0f || d->sw >= im->w + 1.0f ||
+ d->sh <= im->h - 1.0f || d->sh >= im->h + 1.0f ||
+ im->w <= 0 || im->h <= 0 || im->w > scene_w || im->h > scene_h ||
+ (im->w == scene_w && im->h == scene_h) ||
+ (i + 1 < n && vkp_effects_postprocessing())) return 0;
+ *out = *d;
+ out->dw = im->w;
+ out->dh = im->h;
+ return i + 1;
+ }
+ return 0;
+}
+
+static void effects_source_note(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
+ int input_w, int input_h, int output_w, int output_h) {
+ static uint64_t previous;
+ uint64_t key = 14695981039346656037ULL;
+ const int sizes[] = {scene_w, scene_h, n, input_w, input_h, output_w, output_h};
+ for (unsigned i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++)
+ key = (key ^ (uint32_t)sizes[i]) * 1099511628211ULL;
+ for (int i = 0; i < n; i++) {
+ const struct vkp_draw *d = &draws[i];
+ const int values[] = {d->img ? d->img->w : 0, d->img ? d->img->h : 0, d->dw, d->dh, d->blend,
+ d->sx != 0 || d->sy != 0 || !d->img || d->sw != d->img->w || d->sh != d->img->h};
+ for (unsigned j = 0; j < sizeof(values) / sizeof(values[0]); j++)
+ key = (key ^ (uint32_t)values[j]) * 1099511628211ULL;
+ }
+ if (key == previous) return;
+ previous = key;
+ droiddeck_log("effects", "input %dx%d -> %dx%d, logical scene %dx%d, %d draws",
+ input_w, input_h, output_w, output_h, scene_w, scene_h, n);
+ for (int i = 0; i < n && i < 8; i++) {
+ const struct vkp_draw *d = &draws[i];
+ droiddeck_log("effects", "draw %d: buffer %dx%d, source %.1f,%.1f %.1fx%.1f -> scene %d,%d %dx%d, blend %d",
+ i, d->img ? d->img->w : 0, d->img ? d->img->h : 0,
+ d->sx, d->sy, d->sw, d->sh, d->dx, d->dy, d->dw, d->dh, d->blend);
+ }
+}
+
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
const struct vkp_image *im = d->img;
+ const int external_client = vkp_image_is_dmabuf(im);
if (d->blend && im->sampled &&
- blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
+ blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
+ target, target_fmt, target_w, target_h,
blit) == 0)
return;
- g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
+ g_vk.CmdBlitImage(cmd, im->image,
+ external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
}
+static void effects_overlay_draws(VkCommandBuffer cmd, VkImage result, int result_w, int result_h,
+ int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
+ if (n <= 0) return;
+ VkImageMemoryBarrier b = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
+ .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
+ .image = result, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
+ .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
+ .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
+ VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT};
+ g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
+ VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
+ 0, 0, NULL, 0, NULL, 1, &b);
+ for (int i = 0; i < n; i++) {
+ VkImageBlit blit;
+ if (!draws[i].img || !map_draw(&draws[i], (float)result_w / scene_w, (float)result_h / scene_h,
+ 0, 0, 0, 0, (float)result_w, (float)result_h, &blit)) continue;
+ record_draw(cmd, &draws[i], &blit, result, SCENE_FMT, result_w, result_h, VK_FILTER_LINEAR);
+ }
+ b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+ b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
+ b.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
+ b.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
+ g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
+ 0, 0, NULL, 0, NULL, 1, &b);
+}
+
static void destroy_scene_image(void) {
if (g_scene.img) vkp_effects_forget_image(g_scene.img);
if (g_scene.img) hdrc_forget_image(g_scene.img);
@@ -1412,6 +1744,7 @@ static void device_lost(const char *where) {
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);
+ set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s)", where);
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
@@ -1509,6 +1842,7 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
for (int attempt = 0; ; attempt++) {
+ if (g_dev_state != 1) return -1;
if (!g_swapchain && (!first || swap_init() != 0)) return -1;
const int64_t t_acq = perf_now();
VkResult ar = g_vk.AcquireNextImageKHR(g_dev, g_swapchain, 1000000000ULL, g_acqs[k], VK_NULL_HANDLE, img);
@@ -1518,7 +1852,7 @@ static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
if (ar == VK_ERROR_OUT_OF_DATE_KHR || ar == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on acquire: rebuilding the swapchain", vk_result_name(ar));
destroy_swapchain();
- if (first && attempt == 0) continue;
+ if (first && attempt == 0 && g_dev_state == 1) continue;
return -1;
}
droiddeck_log("error", "present: acquire %d failed (%s %d)", k, vk_result_name(ar), (int)ar);
@@ -1635,6 +1969,7 @@ static void send_hdr_metadata(const struct droiddeck_color *c) {
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *how) {
if (how) *how = 0;
+ if (g_dev_state < 0) return -1;
vkp_apply_window_request();
sc_layer_hide_base();
check_surface_changed();
@@ -1653,6 +1988,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
: "no HDR frames through the screen swapchain any more: rebuilding it as SDR");
destroy_swapchain();
}
+ if (g_dev_state != 1) return -1;
g_swap_hdr_want = want_hdr;
uint32_t img = 0;
@@ -1673,6 +2009,20 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
cb = 0;
}
vkp_cardboard_begin_frame();
+ int input_w = scene_w, input_h = scene_h;
+ int pass_n = n;
+ int overlay_start = n;
+ struct vkp_draw source_draw;
+ const struct vkp_draw *pass_draws = draws;
+ const int source_end = fx && !hf && vkp_effects_upscaling()
+ ? effects_source_draw(scene_w, scene_h, draws, n, &source_draw) : 0;
+ if (source_end) {
+ input_w = source_draw.dw;
+ input_h = source_draw.dh;
+ pass_draws = &source_draw;
+ pass_n = 1;
+ overlay_start = source_end;
+ }
const int deep = hf && n > 0 && fg && g_swap_is_hdr && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) &&
ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
@@ -1692,7 +2042,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
"into the HDR10 swapchain (%s): banding possible in smooth gradients", sw);
}
}
- const int pass = deep || ((fx || fg || cb || (hf && n > 0)) && ensure_scene_image(scene_w, scene_h) == 0);
+ const int pass = deep || ((fx || fg || cb || (hf && n > 0)) && ensure_scene_image(input_w, input_h) == 0);
+ const int draw_n = pass ? pass_n : n;
+ if (pass && fx && !hf && vkp_effects_upscaling())
+ effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
+ (int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
VkImage scene_img = deep ? g_fgscene.img : g_scene.img;
const VkFormat scene_fmt = deep ? FG_HDR_FMT : SCENE_FMT;
const VkFilter blit_filter = vkp_effects_blit_filter();
@@ -1718,13 +2072,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
- if (im->dmabuf) {
- bars[nb++] = (VkImageMemoryBarrier){
- .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
- .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
- .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
- .image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
- } else if (!im->in_general) {
+ struct vkp_external_client_barrier_pair pair;
+ if (vkp_external_client_barrier_pair(
+ im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
+ bars[nb++] = pair.acquire;
+ } else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1743,11 +2095,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int covered = 0;
VkImageBlit cover_blit;
if (!(hf && pass)) {
- for (int i = n - 1; i >= 0 && !covered; i--) {
- const struct vkp_draw *d = &draws[i];
- if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w ||
- d->dy + d->dh < scene_h) continue;
- covered = pass ? draw_to_scene_blit(d, scene_w, scene_h, &cover_blit) : draw_to_blit(d, &cover_blit);
+ for (int i = draw_n - 1; i >= 0 && !covered; i--) {
+ const struct vkp_draw *d = pass ? &pass_draws[i] : &draws[i];
+ const int target_w = pass ? input_w : scene_w, target_h = pass ? input_h : scene_h;
+ if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < target_w ||
+ d->dy + d->dh < target_h) continue;
+ covered = pass ? draw_to_scene_blit(d, input_w, input_h, &cover_blit) : draw_to_blit(d, &cover_blit);
}
}
const int cleared = covered && (pass || record_bars_clear(cmd, target, &cover_blit));
@@ -1771,20 +2124,22 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
hdr_how = g_swap_is_hdr ? 1 : 2;
drawn = n;
}
- for (int i = 0; i < n && !hdr_how; i++) {
+ for (int i = 0; i < draw_n && !hdr_how; i++) {
VkImageBlit blit;
- if (!draws[i].img) continue;
- if (pass ? !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit) : !draw_to_blit(&draws[i], &blit)) continue;
- record_draw(cmd, &draws[i], &blit, target, pass ? scene_fmt : g_swap_fmt,
- pass ? scene_w : (int)g_extent.width, pass ? scene_h : (int)g_extent.height,
+ const struct vkp_draw *d = pass ? &pass_draws[i] : &draws[i];
+ if (!d->img) continue;
+ if (pass ? !draw_to_scene_blit(d, input_w, input_h, &blit) : !draw_to_blit(d, &blit)) continue;
+ record_draw(cmd, d, &blit, target, pass ? scene_fmt : g_swap_fmt,
+ pass ? input_w : (int)g_extent.width, pass ? input_h : (int)g_extent.height,
pass ? VK_FILTER_LINEAR : blit_filter);
drawn++;
}
+ if (!(pass && fx)) release_external_client_draws(cmd, draws, n);
int ngen = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img;
- int rw = scene_w, rh = scene_h;
+ int rw = input_w, rh = input_h;
if (!pass) {
VkImageMemoryBarrier b_present = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
@@ -1799,7 +2154,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
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);
+ result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
+ effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
+ draws ? draws + overlay_start : NULL, n - overlay_start);
+ release_external_client_draws(cmd, draws, n);
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
}
VkImageMemoryBarrier b_general = {
@@ -1831,6 +2189,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (k > 0) {
VkResult ark;
if (acquire_image(k, 0, &img, &ark) != 0) {
+ /* Teardown may have retained this frame's pending work, or
+ * acquire may have reported real device loss. Neither permits
+ * a completion-marker submit or another fence wait. */
+ if (g_dev_state != 1) return -1;
droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
pr = VK_ERROR_OUT_OF_DATE_KHR;
break;
@@ -1862,15 +2224,22 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
pr = g_vk.QueuePresentKHR(g_queue, &pi);
perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres);
if (k < ngen) presented_gen++;
- if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR || pr == VK_ERROR_DEVICE_LOST) break;
+ if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
+ if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break;
}
if (!fence_submitted) {
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO};
- g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
+ VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
+ if (marker != VK_SUCCESS) {
+ if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit");
+ else quarantine_pending_work(marker, "frame completion submit");
+ return -1; /* no fence was submitted; never wait on its unsignalled state */
+ }
}
VkResult fr = timed_wait(g_fence, UINT64_MAX);
- if (fg) vkp_framegen_presented(presented_gen);
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
+ if (fr != VK_SUCCESS) return -1;
+ if (fg) vkp_framegen_presented(presented_gen);
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
destroy_swapchain();
@@ -1937,6 +2306,7 @@ void vkp_reset_first_frame(void) {
void vkp_signal_first_frame(void) {
if (g_first_frame_done) return;
g_first_frame_done = 1;
+ clear_fault();
droiddeck_on_first_frame();
}
@@ -1950,6 +2320,7 @@ int vkp_update_map(int scene_w, int scene_h) {
return g_map.valid ? 0 : -1;
}
check_surface_changed();
+ if (g_dev_state != 1) return -1;
if (!g_swapchain && swap_init() != 0) return -1;
update_map(scene_w, scene_h);
return g_map.valid ? 0 : -1;
@@ -1972,7 +2343,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
- if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
+ if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -1985,17 +2356,21 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
+ struct vkp_external_client_barrier_pair src_pair;
+ const int src_external = vkp_external_client_barrier_pair(
+ src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
- {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
+ src_external ? src_pair.acquire : (VkImageMemoryBarrier){
+ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
- .srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
- .dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
+ .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
- if (!src->dmabuf) {
+ if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
@@ -2009,8 +2384,9 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image,
- src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
+ src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
+ release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
@@ -2045,7 +2421,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb;
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
- if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
+ if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
g_dev_state == -2 || dev_init() != 0)
return -1;
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
@@ -2086,11 +2462,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
+ struct vkp_external_client_barrier_pair src_pair;
+ const int src_external = vkp_external_client_barrier_pair(
+ src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
- {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
+ src_external ? src_pair.acquire : (VkImageMemoryBarrier){
+ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
- .srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
- .dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
+ .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
@@ -2108,15 +2488,20 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
- .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
- {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
+ .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}};
+ uint32_t done_count = 1;
+ if (!src_external) {
+ done[done_count++] = (VkImageMemoryBarrier){
+ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
- .srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
- .dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
- .image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
+ .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
+ .image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
+ }
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
- 0, 0, NULL, 0, NULL, 2, done);
+ 0, 0, NULL, 0, NULL, done_count, done);
+ release_external_client_image(cmd, src);
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
@@ -2158,13 +2543,31 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
if (g_pass.active) vkp_pass_abort();
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
+ int input_w = scene_w, input_h = scene_h;
+ int pass_n = n, overlay_start = n;
+ struct vkp_draw source_draw;
+ const struct vkp_draw *pass_draws = draws;
+ const int source_end = !hf && vkp_effects_upscaling()
+ ? effects_source_draw(scene_w, scene_h, draws, n, &source_draw) : 0;
+ if (source_end) {
+ input_w = source_draw.dw;
+ input_h = source_draw.dh;
+ effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
+ (int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
+ pass_draws = &source_draw;
+ pass_n = 1;
+ overlay_start = source_end;
+ } else if (!hf && vkp_effects_upscaling()) {
+ effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
+ (int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
+ }
if (hf) {
if (ensure_img(&g_hdrscene, scene_w, scene_h, HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
"HDR composition (picture)") != 0)
return -1;
- } else if (ensure_scene_image(scene_w, scene_h) != 0) return -1;
+ } else if (ensure_scene_image(input_w, input_h) != 0) return -1;
VkCommandBuffer cmd = g_cmds[0];
g_vk.ResetCommandBuffer(cmd, 0);
@@ -2188,13 +2591,11 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
- if (im->dmabuf) {
- bars[nb++] = (VkImageMemoryBarrier){
- .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
- .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
- .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
- .image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
- } else if (!im->in_general) {
+ struct vkp_external_client_barrier_pair pair;
+ if (vkp_external_client_barrier_pair(
+ im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
+ bars[nb++] = pair.acquire;
+ } else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -2224,19 +2625,22 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 1, &mb, 0, NULL, 0, NULL);
- for (int i = 0; i < n; i++) {
+ for (int i = 0; i < pass_n; i++) {
VkImageBlit blit;
- if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue;
- record_draw(cmd, &draws[i], &blit, g_scene.img, SCENE_FMT, scene_w, scene_h,
+ if (!pass_draws[i].img || !draw_to_scene_blit(&pass_draws[i], input_w, input_h, &blit)) continue;
+ record_draw(cmd, &pass_draws[i], &blit, g_scene.img, SCENE_FMT, input_w, input_h,
VK_FILTER_LINEAR);
}
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
}
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
- g_pass.rw = scene_w; g_pass.rh = scene_h;
- g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h,
+ g_pass.rw = input_w; g_pass.rh = input_h;
+ g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h,
&g_pass.rw, &g_pass.rh);
+ effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h,
+ draws ? draws + overlay_start : NULL, n - overlay_start);
+ release_external_client_draws(cmd, draws, n);
g_pass.active = 1;
if (rw) *rw = g_pass.rw;
if (rh) *rh = g_pass.rh;
@@ -2246,8 +2650,9 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; }
g_pass.active = 0;
+ if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; }
VkCommandBuffer cmd = g_cmds[0];
- if (!dst || !dst->blit_dst || g_dev_state == -2) {
+ if (!dst || !dst->blit_dst) {
if (wait_fd >= 0) close(wait_fd);
g_vk.EndCommandBuffer(cmd);
return -1;
@@ -2299,5 +2704,6 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
void vkp_pass_abort(void) {
if (!g_pass.active) return;
g_pass.active = 0;
- g_vk.EndCommandBuffer(g_cmds[0]);
+ if (g_dev_state == 1)
+ g_vk.EndCommandBuffer(g_cmds[0]);
}
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h
index ac975c93d8..3a76b4c0b6 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.h
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.h
@@ -3,6 +3,8 @@
#include
#include
#include
+#include
+
void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir);
@@ -22,6 +24,9 @@ void vkp_output_size(int *w, int *h);
struct vkp_image;
+int vkp_android_buffer_supported(void);
+struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
+
#define VKP_MOD_LINEAR 0x0000000000000000ULL
#define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL
#define VKP_MOD_INVALID 0x00ffffffffffffffULL
@@ -61,6 +66,10 @@ int vkp_ready(void);
int vkp_has_window(void);
int vkp_wait_window_request(int timeout_ms);
int vkp_device_lost(void);
+/* Compositor thread only. Submitted reads may still be pending: retain imported
+ * buffer references and withhold DMA-BUF releases until the app process exits.
+ * This terminal state is distinct from genuine device loss. */
+int vkp_completion_unknown(void);
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n);
int vkp_render_plain(int scene_w, int scene_h);
diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
index 5d69098a62..ffbfdfd935 100644
--- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
+++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
@@ -216,6 +216,24 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompositorTid(JNIEnv
return (jint)g_comp_tid;
}
+/* Why presenting failed ("" while it works), for the session-ended screen and the report. */
+JNIEXPORT jstring JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompositorFault(JNIEnv *env, jclass clazz) {
+ (void)clazz;
+ extern const char *vkp_fault(void);
+ const char *f = vkp_fault();
+ return (*env)->NewStringUTF(env, f ? f : "");
+}
+
+/* The display driver as the driver itself reports it ("" before the compositor's device exists). */
+JNIEXPORT jstring JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeDisplayDriver(JNIEnv *env, jclass clazz) {
+ (void)clazz;
+ extern const char *vkp_display_driver(void);
+ const char *d = vkp_display_driver();
+ return (*env)->NewStringUTF(env, d ? d : "");
+}
+
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStart(JNIEnv *env, jclass clazz,
jstring xdgRuntimeDir) {
diff --git a/app/src/main/cpp/waylandcomp/src/wl_android_buffer.c b/app/src/main/cpp/waylandcomp/src/wl_android_buffer.c
new file mode 100644
index 0000000000..c7b436f463
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/wl_android_buffer.c
@@ -0,0 +1,216 @@
+/* android_wlegl buffer import for the existing libhybris Wayland WSI.
+ * Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
+ * Native handles are cloned through Android; opaque vendor integers are never interpreted. */
+#include "compositor_internal.h"
+#include "droiddeck_ext.h"
+#include "wayland-android-server-protocol.h"
+#include
+#include
+#include
+#include
+#include
+
+/* Stable native_handle_t ABI, unavailable in the public NDK. */
+struct android_native_handle {
+ int version, num_fds, num_ints;
+ int data[];
+};
+struct wire_handle {
+ struct android_native_handle *handle;
+ int received;
+};
+enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
+/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
+ * vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
+ * Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
+enum { CREATE_FROM_HANDLE_CLONE = 3 };
+static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
+ int32_t, AHardwareBuffer **);
+static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
+
+static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
+ return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
+ stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
+ (format == 1 || format == 2 || format == 5);
+}
+
+static void handle_resource_destroy(struct wl_resource *resource) {
+ struct wire_handle *wire = wl_resource_get_user_data(resource);
+ if (!wire) return;
+ for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
+ free(wire->handle);
+ free(wire);
+}
+
+static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
+ struct wire_handle *wire = wl_resource_get_user_data(resource);
+ if (wire->received >= wire->handle->num_fds) {
+ close(fd);
+ wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
+ "more native handle descriptors than declared");
+ return;
+ }
+ wire->handle->data[wire->received++] = fd;
+}
+
+static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
+ wl_resource_destroy(resource);
+}
+
+static const struct android_wlegl_handle_interface handle_impl = {
+ .add_fd = handle_add_fd, .destroy = handle_destroy,
+};
+
+static void create_handle(struct wl_client *client, struct wl_resource *resource,
+ uint32_t id, int32_t fds, struct wl_array *ints) {
+ if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
+ ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
+ return;
+ }
+ struct wire_handle *wire = calloc(1, sizeof(*wire));
+ if (!wire) { wl_client_post_no_memory(client); return; }
+ wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
+ if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
+ wire->handle->version = sizeof(*wire->handle);
+ wire->handle->num_fds = fds;
+ wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
+ if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
+ struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
+ if (!handle) {
+ free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
+ }
+ wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
+}
+
+static void buffer_resource_destroy(struct wl_resource *resource) {
+ dmabuf_buffer_unref(wl_resource_get_user_data(resource));
+}
+
+static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
+ AHardwareBuffer *hardware) {
+ AHardwareBuffer_Desc desc;
+ AHardwareBuffer_describe(hardware, &desc);
+ struct vkp_image *image = vkp_image_from_android_buffer(hardware);
+ if (!image) return NULL;
+ struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
+ if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
+ buffer->refs = 1;
+ buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
+ buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
+ buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
+ buffer->img = image;
+ for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
+ struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
+ if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
+ wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
+ struct client_info *info = client_info_of(client);
+ if (info) info->dmabuf_buffers++;
+ return result;
+}
+
+static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
+ int32_t width, int32_t height, int32_t stride, int32_t format,
+ int32_t usage, struct wl_resource *handle_resource) {
+ /* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
+ * must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
+ if (!valid_description(width, height, stride ? stride : width, format) ||
+ !wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
+ droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
+ width, height, stride, format, (uint32_t)usage);
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
+ return;
+ }
+ struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
+ if (wire->received != wire->handle->num_fds || !wire->received) {
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
+ return;
+ }
+ AHardwareBuffer_Desc desc = {
+ .width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
+ .format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
+ AHardwareBuffer *hardware = NULL;
+ int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
+ if (status != 0 || !hardware) {
+ droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
+ status, width, height, stride, format, (uint32_t)usage,
+ wire->handle->num_fds, wire->handle->num_ints);
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
+ "Android rejected the native handle (status %d)", status);
+ return;
+ }
+ struct wl_resource *buffer = create_android_buffer(client, id, hardware);
+ AHardwareBuffer_release(hardware);
+ if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
+}
+
+static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
+ int32_t width, int32_t height, int32_t format, int32_t usage) {
+ if (!format) format = 1;
+ if (!valid_description(width, height, width, format)) {
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
+ return;
+ }
+ AHardwareBuffer_Desc desc = {
+ .width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
+ .format = (uint32_t)format,
+ .usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
+ AHardwareBuffer *hardware = NULL;
+ if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
+ return;
+ }
+ AHardwareBuffer_describe(hardware, &desc);
+ const struct android_native_handle *handle = native_handle(hardware);
+ if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
+ handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
+ AHardwareBuffer_release(hardware);
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
+ return;
+ }
+ struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
+ if (!buffer) {
+ AHardwareBuffer_release(hardware);
+ wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
+ return;
+ }
+ struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
+ wl_resource_get_version(resource), id);
+ if (!reply) {
+ wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
+ wl_client_post_no_memory(client); return;
+ }
+ struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
+ .alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
+ android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
+ for (int i = 0; i < handle->num_fds; i++)
+ android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
+ /* No linear_layout event: Android's opaque allocation need not be linear. */
+ android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
+ wl_resource_destroy(reply);
+ AHardwareBuffer_release(hardware);
+}
+
+static const struct android_wlegl_interface wlegl_impl = {
+ .create_handle = create_handle, .create_buffer = create_buffer,
+ .get_server_buffer_handle = get_server_buffer,
+};
+
+static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
+ struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
+ version < 3 ? version : 3, id);
+ if (!resource) { wl_client_post_no_memory(client); return; }
+ wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
+}
+
+void droiddeck_android_wlegl_init(struct wl_display *display) {
+ if (!vkp_android_buffer_supported()) return;
+ void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
+ if (!library) return;
+ import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
+ native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
+ if (!import_handle || !native_handle) { dlclose(library); return; }
+ /* Keep the platform entry points valid for the compositor's lifetime. */
+ if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
+ droiddeck_log("display", "android_wlegl v3: Android buffer import available");
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt
index 0d099cbf0b..5ef39f6b6e 100644
--- a/app/src/main/java/com/droiddeck/launcher/App.kt
+++ b/app/src/main/java/com/droiddeck/launcher/App.kt
@@ -3,6 +3,7 @@ package com.droiddeck.launcher
import android.app.Application
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.session.CrashHandler
+import com.droiddeck.launcher.session.EnhancedSessionLogShare
import com.droiddeck.launcher.session.GpuClockPin
class App : Application() {
@@ -16,6 +17,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
+ Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
HomeApp.trackRecents(this)
diff --git a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt
index 200deb55aa..35a043c1ff 100644
--- a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt
+++ b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt
@@ -14,10 +14,12 @@ import androidx.compose.runtime.mutableIntStateOf
import com.droiddeck.launcher.gpu.AutoDriverTrial
import com.droiddeck.launcher.gpu.AutoPicks
import com.droiddeck.launcher.gpu.DriverBundle
+import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
+import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService
@@ -42,7 +44,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
var canRestoreBundled by mutableStateOf(false)
private val releaseProgress = HashMap()
var linuxSelected by mutableStateOf("")
- val gpu: GpuInfo = GpuInfo.detect()
+ var gpu: GpuInfo = GpuInfo.detect()
+ private set
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
var pairRows by mutableStateOf>(emptyList())
var pairBusy by mutableStateOf(null)
@@ -65,13 +68,14 @@ 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, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
+ gpuName = gpu.displayName(activity), gpuFamily = if (gpu.name.contains("Xclipse", ignoreCase = true)) gpu.family.label(gpu.name) else 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,
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
- activeBundle = activeBundle,
+ activeBundle = activeBundle, powerVr = gpu.family == GpuInfo.Family.POWERVR,
+ systemPowerVr = SystemVulkanDriver.usesDefault(linuxSelected),
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
canRestart = !sessionRunning,
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
@@ -142,7 +146,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE)
}
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
- if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
+ if (id.isEmpty()) DriverRow("", activity.getString(if (gpu.family == GpuInfo.Family.POWERVR) R.string.gpu_system_powervr else R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
else bundleRow(id, linux = true) ?: DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
@@ -177,6 +181,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun summary(): String {
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
+ ?: if (SystemVulkanDriver.usesDefault(linuxSelected) && androidSelected == TurnipDriver.AUTO) activity.getString(R.string.gpu_system_powervr) else null
val display = displaySlot().name
val base = when {
uiMode == GPU_MODE_AUTO -> activity.getString(R.string.drivers_summary, activity.getString(R.string.common_auto), active ?: display)
@@ -193,17 +198,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val recommended = if (QuestExperimental.isSupported()) null else recommendedKey(pairs)
pairRows = pairs.map { p ->
- val bundle = p.bundle?.let { installedBundle(it) }
+ val nad = DriverPairs.isNonAdreno(p.key)
+ val bundle = p.bundle?.let { if (nad) installedBundleAnyBuild(it) else installedBundle(it) }
val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) }
val linuxId = if (p.bundle != null) bundle?.linuxId else p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) }
val mb = p.assets.sumOf { it.size } / 1_048_576.0
+ val update = nad && bundle != null && p.bundle?.let { TurnipReleases.updateAvailable(activity, it) } == true
+ val builtOn = if (nad) p.bundle?.builtOn.orEmpty() else ""
+ val version = when {
+ !nad -> p.version
+ bundle != null -> bundle.version.ifEmpty { p.version }
+ builtOn.isNotEmpty() -> activity.getString(R.string.drivers_built_on, builtOn)
+ else -> p.version
+ }
PairRow(
- key = p.key, name = p.name, version = p.version,
+ key = p.key, name = p.name, version = version, update = if (update) builtOn.takeIf { it.isNotEmpty() }?.let { activity.getString(R.string.drivers_built_on, it) } ?: p.version else null,
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, mb),
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
installed = displayId != null && linuxId != null,
- active = displayId != null && linuxId != null &&
- SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId,
+ active = displayId != null && linuxId != null && SessionPrefs.linuxDriver(activity) == linuxId &&
+ (SessionPrefs.androidDriver(activity) == displayId ||
+ // A Mali pair under Auto: the display is the phone's own driver.
+ (gpu.family.mali && DriverPairs.isNonAdreno(p.key) && SessionPrefs.androidDriver(activity) == TurnipDriver.AUTO)),
)
}.sortedByDescending { it.recommended }
}
@@ -237,7 +253,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private fun releasesStale(): Boolean {
val cached = TurnipReleases.cached(activity)
return cached == null || System.currentTimeMillis() - cached.checkedAt > RELEASE_CHECK_INTERVAL_MS ||
- cached.assets.none { it.pair.isNotEmpty() }
+ cached.assets.none { it.pair.isNotEmpty() } ||
+ // A list checked before this device's open non-Adreno drivers were offered has none of them.
+ (!DeviceSupport.adreno() && cached.assets.none { DriverPairs.isNonAdreno(it.pair) })
}
fun ensureAuto(force: Boolean) {
@@ -247,9 +265,33 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (force) autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
return
}
+ if (gpu.family == GpuInfo.Family.POWERVR && !SystemVulkanDriver.isXclipse()) {
+ // Auto owns both choices. Manual imports remain available when Manual is selected.
+ SessionPrefs.ensurePowerVrAutoDrivers(activity)
+ autoStatus = activity.getString(R.string.drivers_powervr_builtin)
+ refreshDrivers()
+ return
+ }
+ // A Mali pair set by an earlier build put its PanVK Android half on the display, which fails
+ // on Mali gralloc. Under Auto the display is the phone's own driver (Android's loader).
+ if (gpu.family.mali) {
+ // Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
+ // left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
+ if (!SessionPrefs.maliFallbackKnown(activity))
+ SessionPrefs.setMaliFallbackByAuto(activity, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
+ // A lone imported PanVK Android driver set by hand stalls the display the same way
+ // ("black screen with the start-up logo"), so under Auto any imported display goes.
+ val display = SessionPrefs.androidDriver(activity)
+ if (display != TurnipDriver.AUTO) {
+ SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
+ Log.i(TAG, "auto: Mali display back on the phone's own driver (was $display)")
+ }
+ }
AutoDriverTrial.rollbackDue(activity)?.let { trial ->
AutoDriverTrial.rollBack(activity, trial)
autoStatus = activity.getString(R.string.drivers_rolled_back, trial.name)
+ // The drivers before the trial on a Mali are the runtime's Turnip, which finds no GPU there.
+ if (gpu.family.mali && maliHasNoRoute()) useMaliFallback(trial.name)
refreshDrivers()
return
}
@@ -263,6 +305,29 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
return
}
+ if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
+ com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
+ releaseChecking = true
+ autoStatus = activity.getString(R.string.drivers_checking_latest)
+ Thread({
+ com.droiddeck.launcher.gpu.VulkanInfo.query()
+ ui.post {
+ releaseChecking = false
+ gpu = GpuInfo.detect()
+ Log.i(TAG, "auto: Mali named by its driver: ${gpu.name} -> ${gpu.family}")
+ lastAutoCheck = 0L
+ ensureAuto(force)
+ }
+ }, "gpu-name").start()
+ return
+ }
+ Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
+ if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
+ // No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver.
+ autoStatus = useMaliFallback(null)
+ refreshDrivers()
+ return
+ }
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
@@ -275,6 +340,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
runCatching { com.droiddeck.launcher.gpu.VulkanInfo.query() }
ui.post {
releaseChecking = false
+ if (gpu.family == GpuInfo.Family.POWERVR) gpu = GpuInfo.detect()
refreshReleaseRows()
refreshPairs()
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
@@ -284,10 +350,37 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
when {
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
+ gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
+ // RADV is not published right now: the Xclipse falls back to the system route.
+ SessionPrefs.ensurePowerVrAutoDrivers(activity)
+ autoStatus = activity.getString(R.string.drivers_powervr_builtin)
+ refreshDrivers()
+ }
+ gpu.family.mali && (pair == null || !pair.complete) &&
+ (problem != null || TurnipReleases.cached(activity)?.failed?.contains(TurnipReleases.NON_ADRENO_LABEL) == true) -> {
+ // The list could not be read: nothing is known to be missing, so a working route stays.
+ // With no open driver, Venus or bridge the session would run the runtime's Turnip,
+ // which finds no GPU on a Mali, so the stand-in goes on anyway.
+ autoStatus = activity.getString(R.string.upd_couldnt_check, problem ?: TurnipReleases.NON_ADRENO_LABEL)
+ if (maliHasNoRoute()) {
+ useMaliFallback(null)
+ refreshDrivers()
+ }
+ }
+ gpu.family.mali && (pair == null || !pair.complete) -> {
+ // No open driver for this Mali published yet: the phone's own driver until it is.
+ autoStatus = useMaliFallback(key?.let { DriverPairs.nonAdrenoName(it) } ?: gpu.name)
+ refreshDrivers()
+ }
pair == null || !pair.complete ->
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished)
- AutoDriverTrial.release(pair) in AutoDriverTrial.bad(activity) ->
+ AutoDriverTrial.release(pair) in AutoDriverTrial.bad(activity) -> {
autoStatus = activity.getString(R.string.drivers_skipping_bad, pair.name, pair.version)
+ if (gpu.family.mali && maliHasNoRoute()) {
+ useMaliFallback(pair.name)
+ refreshDrivers()
+ }
+ }
SessionState.running -> autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
holdBack && row?.installed != true -> autoStatus = activity.getString(R.string.drivers_auto_waits_for_network, pair.name, pair.version)
else -> installPair(pair, auto = true)
@@ -296,6 +389,53 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-auto").start()
}
+ /**
+ * A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
+ * no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
+ * apk carries it (Steam runs on it from the G57 to the G1 series), the Mali bridge otherwise.
+ * Venus needs Vulkan 1.2 from the phone's driver; the bridge raises a Vulkan 1.1 driver
+ * (r32p1 on the G77, G78 and G610) for gamescope itself, so there the bridge stands in.
+ * The Linux driver choice is left alone (it is the bridge's fallback), and Auto
+ * switches only its own choice off again once a pair is installed ([endMaliFallback]).
+ */
+ private fun useMaliFallback(missing: String?): String {
+ val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
+ val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
+ if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
+ if (venus && !SessionPrefs.venus(activity)) {
+ SessionPrefs.setVenus(activity, true)
+ SessionPrefs.setMaliFallbackByAuto(activity, "venus")
+ } else if (!venus && !SessionPrefs.vkBridge(activity)) {
+ SessionPrefs.setVkBridge(activity, true)
+ SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
+ }
+ val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
+ Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
+ if (oldVulkan != null) return activity.getString(R.string.drivers_mali_old_vulkan_bridge, missing ?: gpu.name, oldVulkan)
+ return if (missing == null) activity.getString(R.string.drivers_mali_no_pair_auto, route)
+ else activity.getString(R.string.drivers_mali_unpublished_auto, missing, route)
+ }
+
+ /** Neither an installed open Linux driver nor Venus or the bridge: the runtime's Turnip would run. */
+ private fun maliHasNoRoute(): Boolean {
+ if (SessionPrefs.vkBridge(activity)) return false
+ // Venus on a Vulkan 1.1 driver does not start (VenusComponent.wanted), so it is no route.
+ if (SessionPrefs.venus(activity) && com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity) == null) return false
+ val linux = SessionPrefs.linuxDriver(activity)
+ return linux.isEmpty() || !LinuxVulkanDriverManager(activity).isInstalled(linux)
+ }
+
+ /** A pair is installed for this Mali: the route Auto switched on in its place goes off again. */
+ private fun endMaliFallback() {
+ when (SessionPrefs.maliFallbackByAuto(activity)) {
+ "venus" -> SessionPrefs.setVenus(activity, false)
+ "bridge" -> SessionPrefs.setVkBridge(activity, false)
+ else -> return
+ }
+ Log.i(TAG, "auto: pair installed; ${SessionPrefs.maliFallbackByAuto(activity)} (Auto's stand-in) off")
+ SessionPrefs.setMaliFallbackByAuto(activity, "")
+ }
+
fun selectPair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
@@ -304,7 +444,15 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
installPair(pair, auto = false)
}
- private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) {
+ /** A newer build of an installed open non-Adreno pair: replaced in place, still selected if it was. */
+ fun updatePair(key: String) {
+ if (pairBusy != null) return
+ val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
+ val wasActive = pairRows.firstOrNull { it.key == key }?.active == true
+ installPair(pair, auto = wasActive && mode == SessionPrefs.GPU_DRIVERS_AUTO, force = true, select = wasActive)
+ }
+
+ private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean, force: Boolean = false, select: Boolean = true) {
if (!pair.complete) return
pairBusy = pair.key
pairPercent = 0
@@ -314,7 +462,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val result = runCatching {
val zips = pair.assets
val ids = zips.mapIndexed { i, asset ->
- installedIdOf(asset)
+ (if (force) null else installedIdOf(asset))
?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / zips.size } }.also { downloaded = true }
}
if (pair.bundle != null) DriverBundle.get(activity, ids[0])!!.let { listOf(it.androidId, it.linuxId) } else ids
@@ -322,23 +470,39 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
ui.post {
pairBusy = null
pairPercent = -1
- result.onSuccess { (displayId, linuxId) ->
+ result.onSuccess { (pairDisplayId, linuxId) ->
+ if (!select) {
+ android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_pair_updated, pair.name), android.widget.Toast.LENGTH_LONG).show()
+ return@onSuccess
+ }
if (auto && SessionState.running) {
lastAutoCheck = 0L
autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
return@onSuccess
}
+ // A Mali pair under Auto: the compositor draws on the phone's own Mali driver
+ // (dma-buf, modifiers and AHB all work there) and the guest runs the pair's
+ // PanVK. Its Android half stays installed for a manual pick.
+ // The same when the pair is picked by hand: a PanVK Android half on the display
+ // stalls Mali gralloc ("Waiting for Steam's first frame"); it stays a manual pick
+ // under "Runtime and display drivers separately".
+ val displayId = if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) TurnipDriver.AUTO else pairDisplayId
val previousDisplay = SessionPrefs.androidDriver(activity)
val previousLinux = SessionPrefs.linuxDriver(activity)
val displayChanged = previousDisplay != displayId
SessionPrefs.setAndroidDriver(activity, displayId)
SessionPrefs.setLinuxDriver(activity, linuxId)
+ // A route Auto switched on in place of a missing pair goes off now that one is
+ // here. A Mali bridge or Venus switch the user set stays: it wins for the session
+ // (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
+ if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
val restart = displayChanged && CompositorHost.isStarted
if (auto) {
val trial = AutoDriverTrial.current(activity)
val lastGood = trial?.let { setOf(it.previousDisplay, it.previousLinux) } ?: setOf(previousDisplay, previousLinux)
val changed = previousDisplay != displayId || previousLinux != linuxId
- SessionPrefs.setGpuAutoInstalled(activity, SessionPrefs.gpuAutoInstalled(activity) + setOf(displayId, linuxId))
+ // A Mali pair's display is the phone's own driver (AUTO): not a download to own or prune.
+ SessionPrefs.setGpuAutoInstalled(activity, SessionPrefs.gpuAutoInstalled(activity) + setOf(displayId, linuxId).filter { it.isNotEmpty() && it != TurnipDriver.AUTO })
if (changed) AutoDriverTrial.begin(
activity, AutoDriverTrial.release(pair), "${pair.name} ${pair.version}", displayId, linuxId,
trial?.previousDisplay ?: previousDisplay, trial?.previousLinux ?: previousLinux,
@@ -366,6 +530,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
+ private fun installedBundleAnyBuild(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
+ TurnipReleases.installedIdAnyBuild(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
+
private fun installedIdOf(asset: TurnipReleases.Asset): String? = when {
asset.bundle -> installedBundle(asset)?.id
asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled)
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index db25be9ca9..986277ae2e 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -163,6 +163,8 @@ class FrontEndActivity : ComponentActivity() {
private var tuSysmem by mutableStateOf(false)
private var zinkLazy by mutableStateOf(false)
private var vkBridge by mutableStateOf(false)
+ private var venus by mutableStateOf(false)
+ private var venusHostVulkan by mutableStateOf(null)
private var vkBridgeSafe by mutableStateOf(true)
private var bridgeProtonDxvk by mutableStateOf(false)
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
@@ -197,6 +199,7 @@ class FrontEndActivity : ComponentActivity() {
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf(null)
+ private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
@@ -208,6 +211,7 @@ class FrontEndActivity : ComponentActivity() {
private var wifiDiscoveryBlocked by mutableStateOf(false)
private var integrationState by mutableStateOf(SteamIntegration.State())
private var integrationFocus by mutableStateOf(null)
+ private var pendingSessionLogExport: File? = null
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshWifiDiscovery()
@@ -266,6 +270,26 @@ class FrontEndActivity : ComponentActivity() {
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
}
+ private val pickSessionLogExport = registerForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
+ val folder = pendingSessionLogExport.also { pendingSessionLogExport = null } ?: return@registerForActivityResult
+ if (uri != null) {
+ SessionLogShare.prepare(this, { folder }) { zip ->
+ if (zip == null) {
+ android.widget.Toast.makeText(this, R.string.setup_log_export_failed, android.widget.Toast.LENGTH_LONG).show()
+ } else Thread({
+ val saved = runCatching {
+ contentResolver.openOutputStream(uri)?.use { output -> zip.inputStream().buffered().use { it.copyTo(output) } }
+ ?: error("Could not open destination")
+ }.isSuccess
+ ui.post {
+ android.widget.Toast.makeText(this,
+ if (saved) R.string.setup_log_export_saved else R.string.setup_log_export_failed,
+ android.widget.Toast.LENGTH_LONG).show()
+ }
+ }, "save-session-logs").start()
+ }
+ }
+ }
private fun refreshWifiDiscovery() {
wifiDiscoveryPermission = WifiDiscovery.permissionGranted(this)
@@ -410,6 +434,27 @@ class FrontEndActivity : ComponentActivity() {
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_saves_pick_zip, name), GameSaves.savesDir().parentFile?.parentFile?.path))
}
+ private fun importAddons(name: String, target: com.droiddeck.launcher.runtime.WowAddons.Target) {
+ if (SessionState.running) {
+ android.widget.Toast.makeText(this, R.string.main_addons_close_session, android.widget.Toast.LENGTH_LONG).show()
+ return
+ }
+ onSavePicked = { zip ->
+ saveAction(getString(R.string.main_addons_importing, name)) {
+ if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session)
+ val imported = try {
+ com.droiddeck.launcher.runtime.WowAddons.import(zip, target)
+ } catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) {
+ return@saveAction getString(R.string.main_addons_too_large, zip.name)
+ }
+ if (imported.isEmpty()) getString(R.string.main_addons_none, zip.name)
+ else resources.getQuantityString(R.plurals.main_addons_imported, imported.size, imported.size, target.flavor)
+ }
+ }
+ val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path
+ pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads))
+ }
+
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
onSavePicked = { dir ->
saveAction(getString(R.string.main_saves_exporting, name)) {
@@ -533,10 +578,15 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf>(emptyList())
private var runningLabel by mutableStateOf(null)
private var logsEnabled by mutableStateOf(true)
+ private var enhancedDiagnosticsArmed by mutableStateOf(false)
private var gameDebugLogsEnabled by mutableStateOf(false)
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
+ private var graphicsLogs by mutableStateOf(false)
+ private var steamGpuDrawing by mutableStateOf(false)
+ private var bridgeFellBack by mutableStateOf(false)
+ private var bridgeFellBackMemory by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
private var adbPaired by mutableStateOf(false)
private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
@@ -1026,6 +1076,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
@@ -1083,7 +1134,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,
+ vkBridge = vkBridge, venus = venus, venusHostVulkan = venusHostVulkan, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
shortcutPicker = shortcutPicker,
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
@@ -1091,8 +1142,10 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
+ enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
+ graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
@@ -1162,8 +1215,13 @@ class FrontEndActivity : ComponentActivity() {
onSteamGame = { g ->
if (shortcutPicker) chooseGameShortcut(g)
else {
- com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
- com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
+ val request = gameLaunchRequest.incrementAndGet()
+ com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) {
+ if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) return@beforeLaunch
+ com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
+ if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
+ }
+ }
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -1233,9 +1291,18 @@ class FrontEndActivity : ComponentActivity() {
onRemovePackage = { id -> removePackage(id) },
onRuntime = { onRuntimeButton() },
onVkBridge = { on ->
- SessionPrefs.setVkBridge(this, on); vkBridge = on
+ SessionPrefs.setVkBridge(this, on); SessionPrefs.setMaliFallbackByAuto(this, ""); vkBridge = on
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
+ onVenus = { on ->
+ SessionPrefs.setVenus(this, on)
+ SessionPrefs.setMaliFallbackByAuto(this, "")
+ venus = on
+ if (on && !com.droiddeck.launcher.core.DeviceSupport.adreno()) Thread({
+ com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
+ runOnUiThread { venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this) }
+ }, "venus-host-vulkan").start()
+ },
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
onBridgeProtonDxvk = { on ->
SessionPrefs.setBridgeProtonDxvk(this, on); bridgeProtonDxvk = on
@@ -1253,6 +1320,13 @@ class FrontEndActivity : ComponentActivity() {
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
+ onAddonImport = { sg, target -> importAddons(sg.name, target) },
+ onAddonDelete = { target, name ->
+ saveAction(getString(R.string.main_addons_deleting, name)) {
+ com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
+ getString(R.string.main_addons_deleted, name)
+ }
+ },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
@@ -1270,6 +1344,15 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
+ onEnhancedDiagnostics = {
+ val requested = !com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
+ if (!com.droiddeck.launcher.session.EnhancedDiagnostics.setArmed(this, requested)) {
+ android.widget.Toast.makeText(
+ this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
+ ).show()
+ }
+ enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
+ },
onGameDebugLogs = {
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
if (!changed) android.widget.Toast.makeText(
@@ -1278,6 +1361,14 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
+ onSteamGpuDrawing = {
+ SessionPrefs.setSteamGpuCompositing(this, !SessionPrefs.steamGpuCompositing(this))
+ steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
+ },
+ onGraphicsLogs = {
+ SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
+ graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
+ },
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
@@ -1293,11 +1384,40 @@ class FrontEndActivity : ComponentActivity() {
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
},
onShareLogs = {
- SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
+ val folder = SessionLogShare.latest(this)
+ if (folder == null) {
+ android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
+ } else if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
+ SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
+ if (zips.isEmpty()) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
+ else shareEnhancedArchives(zips)
+ }
+ } else {
+ SessionLogShare.prepare(this, { folder }) { zip ->
+ if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
+ else startActivity(SessionLogShare.shareIntent(this, zip))
+ }
+ }
+ },
+ onShareSessionLog = { folder ->
+ SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
}
},
+ onSaveSessionLog = { folder ->
+ pendingSessionLogExport = folder
+ pickSessionLogExport.launch("DroidDeck-${folder.name}.zip")
+ },
+ onDeleteSessionLog = { folder, done ->
+ Thread({
+ val deleted = runCatching { SessionLogShare.deleteSession(this, folder) }.getOrDefault(false)
+ ui.post {
+ if (!deleted) android.widget.Toast.makeText(this, R.string.setup_log_delete_failed, android.widget.Toast.LENGTH_SHORT).show()
+ done()
+ }
+ }, "delete-session-logs").start()
+ },
onClearLogs = {
Thread({
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
@@ -1468,6 +1588,7 @@ class FrontEndActivity : ComponentActivity() {
onStickClick = { on -> ControllerPrefs.setStickClick(this, on); refreshController() },
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
onRumble = { on -> ControllerPrefs.setRumble(this, on); refreshController() },
+ onDeadZone = { v -> ControllerPrefs.setDeadZone(this, v); refreshController() },
onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
@@ -1585,6 +1706,9 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.frontend.GamesFolderMigration.run(this)
SessionLogShare.clear(this)
SessionArtifacts.finishAbandoned(this)
+ if (SessionPrefs.takeMemoryKillNotice(this)) runOnUiThread {
+ android.widget.Toast.makeText(this, R.string.session_killed_for_memory, android.widget.Toast.LENGTH_LONG).show()
+ }
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
}, "finish-abandoned").start()
@@ -1802,6 +1926,7 @@ class FrontEndActivity : ComponentActivity() {
super.onSaveInstanceState(outState)
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
+ pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
@@ -1816,6 +1941,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
+ gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
@@ -2030,6 +2156,7 @@ class FrontEndActivity : ComponentActivity() {
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
onAuto = { on -> drivers.setMode(on) },
onPair = { key -> drivers.selectPair(key) },
+ onPairUpdate = { key -> drivers.updatePair(key) },
onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() },
onSelectLinux = { id -> drivers.selectDriver(id, linux = true) },
onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) },
@@ -2580,6 +2707,8 @@ class FrontEndActivity : ComponentActivity() {
tuSysmem = SessionPrefs.tuSysmem(this)
zinkLazy = SessionPrefs.zinkLazy(this)
vkBridge = SessionPrefs.vkBridge(this)
+ venus = SessionPrefs.venus(this)
+ venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
noXalia = SessionPrefs.noXalia(this)
@@ -2602,6 +2731,32 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
!SessionPaths.currentSessionLogsRetained(this)
+ private fun shareEnhancedArchives(zips: List) {
+ if (isFinishing || isDestroyed) return
+ val choices = zips.map { zip ->
+ val label = when {
+ zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
+ zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
+ else -> getString(R.string.diagnostics_share_games)
+ }
+ label to listOf(zip)
+ } + (getString(R.string.diagnostics_share_all) to zips)
+ android.app.AlertDialog.Builder(this)
+ .setTitle(R.string.diagnostics_share_title)
+ .setItems(choices.map { it.first }.toTypedArray()) { _, which ->
+ val selected = choices[which].second
+ runCatching {
+ startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
+ else SessionLogShare.shareEnhancedIntent(this, selected))
+ }.onFailure {
+ android.util.Log.w("SessionLogShare", "could not share latest session logs", it)
+ android.widget.Toast.makeText(this, R.string.session_logs_share_failed, android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
+ .setNegativeButton(android.R.string.cancel, null)
+ .show()
+ }
+
private fun refresh() {
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
@@ -2626,10 +2781,15 @@ class FrontEndActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
+ enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
+ graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
+ steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
+ bridgeFellBack = SessionPrefs.bridgeFellBack(this)
+ bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
memoryHud = SessionPrefs.memoryHud(this)
@@ -2867,6 +3027,7 @@ class FrontEndActivity : ComponentActivity() {
companion object {
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
+ private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 2d0ffcc636..a1789aa75c 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -96,6 +96,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PointerGestures
+import com.droiddeck.launcher.input.PointerSpace
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
import com.droiddeck.launcher.input.SecondScreenMode
@@ -207,6 +208,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private val guestKeysDown = mutableSetOf()
+ private val guestButtonsDown = mutableMapOf()
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
@@ -374,6 +376,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onCancel = { padBridge?.cancelBackQam() },
holds = { backHold },
)
+ private val mouseBackInput = com.droiddeck.launcher.input.MouseBackInput(
+ sendRight = { down -> heldButtons.set(32, PointerGestures.BTN_RIGHT, down) },
+ mouseAttached = ::mouseAttached,
+ )
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
private var drawerDirectionDeviceId = -1
@@ -628,6 +634,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "input device $deviceId disconnected")
dropMouseCursor()
backQamInput.onDeviceRemoved(deviceId)
+ mouseBackInput.onDeviceRemoved(deviceId)
joyConVr?.refresh()
physicalInputBindings?.disconnected(deviceId)
padBridge?.onDeviceRemoved(deviceId)
@@ -708,7 +715,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchPointerCaptureChanged(hasCapture: Boolean) {
super.dispatchPointerCaptureChanged(hasCapture)
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
- if (!hasCapture) uiHandler.postDelayed(::updatePointerCapture, 250)
+ if (!hasCapture) {
+ releaseHeldGuestInput()
+ uiHandler.postDelayed(::updatePointerCapture, 250)
+ }
}
}
sessionRoot = root
@@ -720,6 +730,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
+ bridge.setStickDeadZone(ControllerPrefs.deadZone(this))
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) }
@@ -775,6 +786,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
.also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink)
+ touchSlop = PointerGestures.slop(this)
threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2)
twoFingerGestures = com.droiddeck.launcher.input.TwoFingerGestures(PointerGestures.slop(this) * 2,
object : com.droiddeck.launcher.input.TwoFingerGestures.Listener {
@@ -1248,6 +1260,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionDrawer(drawerOpen || (docked && drawerPinned), drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, docked = docked,
backRequest = drawerBackRequests, onLayerChange = { drawerLayerOpen = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
+ systemPowerVr = com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(
+ SessionPrefs.linuxDriver(this@SessionActivity)),
direct = noSteamSession(),
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
@@ -1918,7 +1932,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Toast.makeText(this, R.string.session_no_logs, Toast.LENGTH_LONG).show()
return
}
- SessionLogShare.prepare(this, { folder }) { zip ->
+ if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
+ SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
+ if (zips.isEmpty()) {
+ Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
+ } else runCatching { shareEnhancedArchives(zips) }
+ .onFailure {
+ Log.w(TAG, "could not share current session logs", it)
+ Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+ } else SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else {
@@ -1931,6 +1955,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
+ private fun shareEnhancedArchives(zips: List) {
+ val choices = zips.map { zip ->
+ val label = when {
+ zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
+ zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
+ else -> getString(R.string.diagnostics_share_games)
+ }
+ label to listOf(zip)
+ } + (getString(R.string.diagnostics_share_all) to zips)
+ android.app.AlertDialog.Builder(this)
+ .setTitle(R.string.diagnostics_share_title)
+ .setItems(choices.map { it.first }.toTypedArray()) { _, which ->
+ val selected = choices[which].second
+ runCatching {
+ startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
+ else SessionLogShare.shareEnhancedIntent(this, selected))
+ }.onFailure {
+ Log.w(TAG, "could not share current session logs", it)
+ Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+ .setNegativeButton(android.R.string.cancel, null)
+ .show()
+ }
+
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -2260,7 +2309,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun windowOutputSize(width: Int, height: Int): Pair? {
- if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
+ if (width <= 0 || height <= 0) return null
+ if (isInPictureInPictureMode) return com.droiddeck.launcher.session.PipPolicy.outputSize(
+ width, height, SessionState.outputSize.first, SessionState.outputSize.second)
if (bottomGame != null) return when {
SessionState.followScreen ->
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, false, SessionState.followScale)
@@ -2466,10 +2517,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = true)
updateGlassesScreen()
updateHeadTracker()
- if (status == 0) {
+ Thread({
+ val hint = sessionExitHint(status)
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
- SessionState.relaunch?.let { next ->
+ if (status == 0) SessionState.relaunch?.let { next ->
SessionState.relaunch = null
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
@@ -2477,14 +2529,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
recreate()
return@runOnUiThread
}
- finish()
- }
- return
- }
- Thread({
- val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
- runOnUiThread {
- if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint)
}
}, "session-end-hint").start()
@@ -2549,13 +2593,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
}
+ private fun presentationFault(): String? {
+ runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault() }.getOrNull()
+ ?.takeIf { it.isNotEmpty() }?.let { return it }
+ val waylandLog = SessionState.logDirectory?.let { File(it, "wayland.log") }?.takeIf { it.isFile } ?: return null
+ return try {
+ java.io.RandomAccessFile(waylandLog, "r").use { f ->
+ val start = maxOf(0L, waylandLog.length() - 256L * 1024)
+ f.seek(start)
+ val bytes = ByteArray((waylandLog.length() - start).toInt())
+ f.readFully(bytes)
+ var fault: String? = null
+ String(bytes, Charsets.ISO_8859_1).lineSequence().forEach { line ->
+ val i = line.indexOf("DD_PRESENT_FAULT: ")
+ if (i >= 0) fault = line.substring(i + 18).trim().ifEmpty { null }
+ else if (line.contains("presentation recovered: fault cleared")) fault = null
+ }
+ fault
+ }
+ } catch (_: Exception) {
+ null
+ }
+ }
+
private fun prootFailureHint(): EndHint? {
if (SessionState.failureCode != "PROOT_MISSING") return null
val message = SessionState.failureMessage ?: return null
return EndHint(message)
}
+ private fun presentationFaultHint(): EndHint? = presentationFault()?.let {
+ EndHint(getString(R.string.session_end_present_fault, it), evenOnSuccess = true)
+ }
+
+ private fun sessionExitHint(status: Int): EndHint? = if (status == 0) presentationFaultHint()
+ else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
+
private fun sessionEndHint(log: File?): EndHint? {
+ presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
var enosys = 0
@@ -2582,8 +2657,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val fallback = if (SessionState.steamClientArch == "arm64") getString(R.string.session_end_steam_try_x64) else null
EndHint(listOfNotNull(message, fallback).joinToString("\n"))
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.VULKAN_DEVICE_MISSING) {
- val adreno = com.droiddeck.launcher.gpu.GpuInfo.detect().family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO
- EndHint(getString(if (adreno) R.string.session_end_vulkan_device else R.string.session_end_gpu_unsupported))
+ val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
+ val family = gpu.family
+ val adreno = family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO &&
+ family != com.droiddeck.launcher.gpu.GpuInfo.Family.POWERVR && !family.mali
+ val message = getString(R.string.session_end_vulkan_device)
+ EndHint(if (adreno) message else "${gpu.name} (${family.label(gpu.name)})\n$message")
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
@@ -2638,6 +2717,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}) return true
}
+ if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
+ Log.i(TAG, String.format(java.util.Locale.ROOT, "back key device=%d (%s) source=0x%x flags=0x%x",
+ event.deviceId, event.device?.name, event.source, event.flags))
+ }
+ val mouseToGuest = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
+ !SessionState.suspended && !(::loading.isInitialized && (loading.visible || loading.ended))
+ if (mouseBackInput.onKeyEvent(event, mouseToGuest)) return true
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
@@ -2985,7 +3071,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val gestureOutput = object : TouchscreenGestures.Output {
override fun moveTo(x: Float, y: Float) {
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
if (pointerLocked) {
if (gesturePointerReady) moveBy(x - gesturePointerX, y - gesturePointerY, true)
} else movePointer(x, y)
@@ -2995,7 +3081,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorVisible = false
}
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
- val rect = drawnRect() ?: return
+ val rect = (if (pointerLocked) drawnRect() else pointerSurfaceRect()) ?: return
if (relative || pointerLocked) {
val scale = sceneScale(rect)
sendSceneDelta(dx * scale, dy * scale)
@@ -3006,7 +3092,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun prepareRelativePan() {
if (pointerLocked) return
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
moveTo(rect.centerX(), rect.centerY())
}
override fun key(code: Int, down: Boolean) {
@@ -3050,7 +3136,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val scrollListener = object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) {
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
@@ -3060,7 +3146,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
heldButtons.set(1, button, pressed)
}
override fun onScroll(dx: Float, dy: Float) {
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width()
scrollRestY += dy * out.second / rect.height()
@@ -3079,7 +3165,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onScrollStart() {
scrollRestX = 0f
scrollRestY = 0f
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
val x = rect.left + rect.width() * PAD_SCROLL_POINTER_X
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, outputView().width), InputSpace.y(rect.centerY(), outputView().height))
cursorVisible = false
@@ -3092,7 +3178,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onNavigate() {
cursorVisible = false
}
- override fun scrollSpeed(): Float = (drawnRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
+ override fun scrollSpeed(): Float = (pointerSurfaceRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
}
private fun padMouseMode(): Boolean {
@@ -3115,7 +3201,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
(routedTouchMode == SessionPrefs.TOUCH_AUTO || routedTouchMode == SessionPrefs.TOUCH_DIRECT) && padMouseMode()
private fun fingerScroll(dx: Float, dy: Float) {
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width() * AXIS_UNITS_PER_PIXEL
scrollRestY += dy * out.second / rect.height() * AXIS_UNITS_PER_PIXEL
@@ -3138,7 +3224,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
- if (rect.contains(x, y)) touchpad.place(x, y)
+ touchpad.place(x.coerceIn(rect.left, rect.right), y.coerceIn(rect.top, rect.bottom))
}
private fun moveLockedPointer(x: Float, y: Float) {
@@ -3150,7 +3236,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun movePointer(x: Float, y: Float, fromMouse: Boolean = false) {
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
@@ -3555,7 +3641,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (width <= 0f || height <= 0f) return
val nx = (x / width).coerceIn(0f, 1f)
val ny = (y / height).coerceIn(0f, 1f)
- val rect = drawnRect() ?: return
+ val rect = pointerSurfaceRect() ?: return
val px = rect.left + nx * rect.width()
val py = rect.top + ny * rect.height()
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, outputView().width), InputSpace.y(py, outputView().height))
@@ -3703,7 +3789,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun sendSceneButton(code: Int, down: Boolean) {
- val writer = if (evdevMouseActive) mouseWriter else null
+ val raw = if (down) evdevMouseActive.also { guestButtonsDown[code] = it }
+ else guestButtonsDown.remove(code) ?: evdevMouseActive
+ val writer = if (raw) mouseWriter else null
if (writer != null) writer.writeMouseButton(code.toShort(), down)
else WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
@@ -3741,10 +3829,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return android.graphics.RectF(left, top, left + drawnW, top + drawnH)
}
+ /**
+ * Where the pointer can travel on this view. With the glasses owning the output the view is
+ * not showing the picture, so the whole view is the touchpad; using the letterboxed picture
+ * rect there would leave the pointer unable to reach the scene edges.
+ */
+ private fun pointerSurfaceRect(): android.graphics.RectF? {
+ val view = outputView()
+ return PointerSpace.area(view.width, view.height, glassesOutputActive, drawnRect())
+ }
+
private var ignoreGameTouch = false
- private var lockedTouchTurns = false
private var touchEditorOpen by mutableStateOf(false)
private var lockedSwipeUsed = false
+ private var touchSlop = 0f
private var lockedSwipeX = 0f
private var lockedSwipeY = 0f
private var dismissTouch = false
@@ -3789,15 +3887,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
com.droiddeck.launcher.input.TouchRouter.Route.SCROLL -> scrollTouch.onTouch(event)
else -> {
- if (event.actionMasked == MotionEvent.ACTION_DOWN) {
- val inPicture = drawnRect()?.let { !topPictureMapped || it.contains(event.x, event.y) } ?: false
- lockedTouchTurns = programLocksPointer() && inPicture && route != com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD
- }
if (com.droiddeck.launcher.input.TouchRouter.steamKeyboardZone(snapshot)) {
val wasActive = threeFingerTap.active
if (threeFingerTap.onTouch(event)) padBridge?.triggerSteamKeyboard()
if (threeFingerTap.active && !wasActive) {
- if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD || lockedTouchTurns) touchpad.cancel()
+ if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) touchpad.cancel()
else {
directTouchHold.cancel()
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
@@ -3805,8 +3899,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
if (threeFingerTap.active || wasActive) return true
}
- if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD || lockedTouchTurns) {
- val rect = drawnRect() ?: return false
+ if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) {
+ val rect = (if (pointerLocked) drawnRect() else pointerSurfaceRect()) ?: return false
if (touchpad.bounds != rect) {
val fresh = touchpad.bounds.width() <= 1f
touchpad.bounds = rect
@@ -3859,8 +3953,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun forwardTouch(event: MotionEvent, rect: android.graphics.RectF): Boolean {
val swipeX = lockedSwipeX
val swipeY = lockedSwipeY
- lockedSwipeX = event.x
- lockedSwipeY = event.y
+ if (programLocksPointer() && event.actionMasked == MotionEvent.ACTION_MOVE && !lockedSwipeUsed &&
+ abs(event.x - swipeX) <= touchSlop && abs(event.y - swipeY) <= touchSlop) return true
+ val anchor = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && event.actionIndex == 0 && event.pointerCount > 1) 1 else 0
+ lockedSwipeX = event.getX(anchor)
+ lockedSwipeY = event.getY(anchor)
if ((event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) && lockedSwipeUsed) {
lockedSwipeUsed = false
directTouchHold.cancel()
@@ -3892,14 +3989,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
- val button = when (event.actionButton) {
- MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
- MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
- MotionEvent.BUTTON_BACK -> BTN_SIDE
- MotionEvent.BUTTON_FORWARD -> BTN_EXTRA
- else -> PointerGestures.BTN_LEFT
- }
- heldButtons.set(8, button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
+ guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
@@ -3914,7 +4004,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun isHardwareMouse(d: InputDevice?): Boolean =
d != null && !d.isVirtual && (d.supportsSource(InputDevice.SOURCE_MOUSE) || d.supportsSource(InputDevice.SOURCE_MOUSE_RELATIVE))
- private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { isHardwareMouse(InputDevice.getDevice(it)) }
+ /** Android also sends the Back and Forward buttons as key events, so they are handled as keys. */
+ private fun guestMouseButton(actionButton: Int): Int? = when (actionButton) {
+ MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
+ MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
+ MotionEvent.BUTTON_BACK, MotionEvent.BUTTON_FORWARD -> null
+ else -> PointerGestures.BTN_LEFT
+ }
+
+ private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { id ->
+ val d = InputDevice.getDevice(id)
+ isHardwareMouse(d) && d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) != true
+ }
private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
@@ -4012,14 +4113,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
moveCapturedMouse(dx, dy)
}
}
- MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
- val button = when (event.actionButton) {
- MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
- MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
- else -> PointerGestures.BTN_LEFT
- }
- heldButtons.set(8, button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
- }
+ MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE ->
+ guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) sendSceneWheel(-Math.round(v))
@@ -4205,6 +4300,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
+ private fun releaseHeldGuestInput() {
+ mouseBackInput.cancel()
+ heldButtons.release(1 or 2 or 8 or 16)
+ guestKeysDown.toList().forEach { sendGuestKey(it, false) }
+ heldKeys.release(8)
+ }
+
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
@@ -4426,6 +4528,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
+ padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
joyConVr?.refresh()
@@ -4460,6 +4563,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (runtimeRemovalBlocked) { super.onPause(); return }
physicalShortcuts.clear()
backQamInput.cancel()
+ mouseBackInput.cancel()
capturePausedFrame()
padBridge?.setInputEnabled(false)
sessionClipboard.stop()
@@ -5033,11 +5137,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
if (!hasFocus) backQamInput.cancel()
+ if (!hasFocus) mouseBackInput.cancel()
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return
if (!hasFocus) {
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
+ if (::scrollTouch.isInitialized) scrollTouch.cancel()
+ releaseHeldGuestInput()
}
if (hasFocus && !pipUi) {
goFullscreen()
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt
index a4322909ad..c1955caa05 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt
@@ -18,12 +18,15 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
+import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
+import java.nio.file.Files
+import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -93,6 +96,7 @@ class AgentBridgeProvider : ContentProvider() {
}
"prefs" -> prefs(context, request)
"glasses" -> glasses(context, request)
+ "logs" -> logs(context)
"access" -> JSONObject().put("ok", true).put("commands", AgentAccess.commandsAllowed(context))
.put("debugBuild", BuildConfig.DEBUG).put("inbox", AgentEnv.inbox(context).absolutePath)
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
@@ -197,9 +201,46 @@ class AgentBridgeProvider : ContentProvider() {
private fun hex(text: String, max: Int): Int? =
text.removePrefix("0x").removePrefix("0X").takeIf { it.isNotEmpty() }?.toIntOrNull(16)?.takeIf { it in 0..max }
+ private fun logDir(context: Context): File? =
+ SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
+
+ private fun cleanupExpiredLogExports(exports: File) {
+ val now = System.currentTimeMillis()
+ val canonicalRoot = exports.canonicalFile
+ exports.listFiles()?.forEach { candidate ->
+ val isUuid = runCatching { UUID.fromString(candidate.name).toString() == candidate.name }.getOrDefault(false)
+ if (!isUuid || !candidate.isDirectory || Files.isSymbolicLink(candidate.toPath())) return@forEach
+ if (candidate.canonicalFile.parentFile != canonicalRoot) return@forEach
+ if (now - candidate.lastModified() >= LOG_EXPORT_RETENTION_MS) candidate.deleteRecursively()
+ }
+ }
+
+ // The session folder is app-private, so adb pulls this copy from external files instead.
+ private fun logs(context: Context): JSONObject {
+ val dir = logDir(context)?.takeIf { it.isDirectory }
+ ?: return error("NO_SESSION_LOGS", "No session artifact directory is available")
+ val externalFiles = context.getExternalFilesDir(null)
+ ?: return error("NO_SESSION_LOGS", "External app storage is unavailable")
+ val exports = File(externalFiles, "agent-logs")
+ if ((!exports.exists() && !exports.mkdirs()) || !exports.isDirectory) {
+ return error("NO_SESSION_LOGS", "Could not create the session export directory")
+ }
+ cleanupExpiredLogExports(exports)
+ val output = File(exports, UUID.randomUUID().toString())
+ val zip = try {
+ SessionLogShare.zipFolder(context, dir, output)
+ } catch (error: Exception) {
+ output.deleteRecursively()
+ throw error
+ }
+ ?: return error("NO_SESSION_LOGS", "The session artifact directory is empty")
+ return JSONObject().put("ok", true).put("command", "logs").put("sessionId", dir.name)
+ .put("zip", zip.absolutePath).put("cleanupDir", output.absolutePath)
+ }
+
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
- val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
+ val dir = logDir(context)
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -351,6 +392,7 @@ class AgentBridgeProvider : ContentProvider() {
const val RESULT_JSON = "json"
const val EXTRA_REQUEST = "request"
const val SCHEMA = 2
+ private const val LOG_EXPORT_RETENTION_MS = 24 * 60 * 60 * 1000L
private val recoveryComplete = CountDownLatch(1)
fun awaitRecovery() {
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentInput.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentInput.kt
index 94cf533885..e491b5f9ad 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentInput.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentInput.kt
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.agent
+import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -143,9 +144,10 @@ object AgentInput {
val right = request.optString("stick", "left") == "right"
val x = request.optDouble("x", 0.0).toFloat().coerceIn(-1f, 1f)
val y = request.optDouble("y", 0.0).toFloat().coerceIn(-1f, 1f)
- bridge.applyTouch { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
+ val stickWrite = if (right) PadBridge.RIGHT_STICK else PadBridge.LEFT_STICK
+ bridge.applyTouch(stickWrite) { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
hold(request, 300)
- bridge.applyTouch { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
+ bridge.applyTouch(stickWrite) { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
return JSONObject().put("stick", if (right) "right" else "left")
}
diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
index 32d5f5189e..08c463dfdc 100644
--- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
+++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
@@ -130,22 +130,46 @@ public class PulseAudioComponent extends SessionPart {
private void ensureClientSink(java.io.PrintWriter out) {
try {
- long deadline = System.currentTimeMillis() + 15000L;
+ // Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
+ // daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
+ // fallbacks are loaded here, after it is up, each pactl call bounded by its timeout.
+ long started = System.currentTimeMillis();
+ long deadline = started + 30000L;
String sinks = null;
+ boolean socketSeen = false;
while (System.currentTimeMillis() < deadline && pid > 1) {
- if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
+ socketSeen |= socket().exists();
+ if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
+ note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
+ + (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
+ + (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
String line;
if (sinks == null) {
- line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
+ line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
} else {
- boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
- && pactl("set-default-sink", "AAudioSink") != null;
- line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
- : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
+ // AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
+ // still switching the output route as the session starts (seen on a Galaxy S24 FE):
+ // try DirectAudio again, then the plain sink, a few times over ten seconds.
+ String loadedAs = null;
+ for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
+ try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
+ if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
+ "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
+ && pactl("set-default-sink", "DirectAudio") != null) {
+ loadedAs = "DirectAudio on attempt " + attempt;
+ } else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
+ "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
+ && pactl("set-default-sink", "AAudioSink") != null) {
+ loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
+ }
+ }
+ line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
+ : "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ + " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
Log.w(TAG, line);
}
Log.i(TAG, line);
@@ -155,6 +179,14 @@ public class PulseAudioComponent extends SessionPart {
}
}
+ /** A timestamped line in the session's audio log. */
+ private void note(java.io.PrintWriter out, String what) {
+ String line = "== " + new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + what;
+ Log.i(TAG, line);
+ if (out != null) synchronized (out) { out.println(line); out.flush(); }
+ }
+
+ /** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) return null;
diff --git a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt
index 383dd98bbd..4f88d90e34 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt
@@ -149,5 +149,8 @@ internal class AddonPack(
listOf("version", "comet"))
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
listOf("version", "butler", "7z.so", "libc7zip.so"))
+ @JvmField
+ val POWERVR = AddonPack("powervr", BuildConfig.PACK_POWERVR_SHA256, BuildConfig.PACK_POWERVR_SIZE,
+ listOf("runtime.tzst", "version.txt"))
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
index 309716d3fc..cb0b9487b8 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
@@ -10,6 +10,8 @@ import android.os.PowerManager
import android.os.StatFs
import android.provider.Settings
import android.util.Log
+import com.droiddeck.launcher.gpu.DeviceInfo
+import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.view.Display
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
@@ -110,6 +112,7 @@ object DeviceReport {
runCatching {
val info = context.packageManager.getPackageInfo(context.packageName, 0)
k("Version", "${info.versionName} (${info.longVersionCode})")
+ k("App build", "${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
}
k("Package", context.packageName)
k("targetSdk", context.applicationInfo.targetSdkVersion)
@@ -186,7 +189,11 @@ object DeviceReport {
h("GPU")
k("KGSL gpu_model", readSys("/sys/class/kgsl/kgsl-3d0/gpu_model"))
k("KGSL chip id", readSys("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))
- k("System Vulkan ICD", if (File("/vendor/lib64/hw/vulkan.adreno.so").exists()) "/vendor/lib64/hw/vulkan.adreno.so" else "not at the usual path")
+ k("System Vulkan ICD", when {
+ SystemVulkanDriver.isPowerVr() -> SystemVulkanDriver.hal()
+ File("/vendor/lib64/hw/vulkan.adreno.so").exists() -> "/vendor/lib64/hw/vulkan.adreno.so"
+ else -> "not at the usual path"
+ })
h("Display")
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
@@ -208,7 +215,7 @@ object DeviceReport {
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
- k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
+ k("GPU", "${gpu.name} · ${gpu.family.label(gpu.name)} · ${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")
@@ -221,19 +228,25 @@ object DeviceReport {
com.droiddeck.launcher.gpu.AutoDriverTrial.bad(context))?.let { " (recommended pair: $it)" } ?: ""))
val turnip = TurnipDriver(context)
val androidChoice = SessionPrefs.androidDriver(context)
- k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
- k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
+ val displayId = androidChoice.ifEmpty { turnip.autoId() }
+ val displayLabel = if (displayId == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
+ else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
+ k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
+ k(" name / version", displayLabel)
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
val lm = LinuxVulkanDriverManager(context)
run {
val id = SessionPrefs.linuxDriver(context)
- val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
+ val label = if (id.isEmpty()) DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = true)
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
- if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
+ if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
+ else " [MISSING - falls back to the runtime's own]"
k("Linux driver", label)
}
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
+ k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
+ else if (com.droiddeck.launcher.session.VenusComponent.available(context)) "available, off" else "not in this build")
h("Runtime")
k("Installed version", LinuxRuntimeInstaller.installedVersion(context))
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt
index ee214fedfe..c847dbcdfc 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.R
+import com.droiddeck.launcher.gpu.SystemVulkanDriver
import java.io.File
object DeviceSupport {
@@ -10,16 +11,35 @@ object DeviceSupport {
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 graphicsAvailable(): Boolean = graphicsAvailable(adreno(), SystemVulkanDriver.isAvailable())
+
+ internal fun graphicsAvailable(adreno: Boolean, powerVrReady: Boolean): Boolean = adreno || powerVrReady
fun vkBridge(context: Context): Boolean =
- !adreno() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
+ bridgeUsable() && !com.droiddeck.launcher.session.VenusComponent.wanted(context) &&
+ com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
- fun canDraw(context: Context): Boolean = adreno() || vkBridge(context)
+ fun mali(): Boolean = isMali
+
+ private val isMali by lazy {
+ !adreno() && (File("/dev/mali0").exists() ||
+ com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
+ }
+
+ fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
+
+ fun openDriverActive(context: Context): Boolean {
+ if (adreno()) return false
+ if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) return false
+ if (bridgeUsable() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)) return false
+ val linux = com.droiddeck.launcher.session.SessionPrefs.linuxDriver(context).ifEmpty { return false }
+ return com.droiddeck.launcher.gpu.DriverPairs.isNonAdreno(com.droiddeck.launcher.gpu.DriverBundle.containing(context, linux, true)?.id)
+ }
+
+ fun canDraw(context: Context): Boolean = graphicsAvailable() || openDriverActive(context) || vkBridge(context) ||
+ com.droiddeck.launcher.session.VenusComponent.wanted(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
diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt
index 4672cc651b..26ffb499cc 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt
@@ -30,8 +30,6 @@ object GameEnvironment {
fun defaults(preset: String, forceSsbs: Boolean = false): Map = linkedMapOf(
"MESA_SHADER_CACHE_DISABLE" to "false",
"DROIDDECK_ANTICHEAT_OFFLINE" to "1",
- "VKD3D_FEATURE_LEVEL" to "12_2",
- "VKD3D_SHADER_MODEL" to "6_9",
"DOTNET_GCRegionRange" to "800000000",
"DOTNET_EnableWriteXorExecute" to "0",
).apply {
diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
index 3230e8ea47..19199873f7 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
@@ -131,42 +131,81 @@ object LogRedactor {
@Volatile
private var accounts: List = emptyList()
- fun learnAccounts(vararg loginUsers: java.io.File) {
+ internal const val MAX_LEARN_INPUT_BYTES = 2 * 1024 * 1024
+ private const val MAX_LEARNED_ACCOUNTS = 2048
+ private const val MAX_LEARNED_ADDRESSES = 1024
+ private const val MAX_ACCOUNT_LENGTH = 256
+
+ private fun boundedText(file: java.io.File): String? = try {
+ file.inputStream().buffered().use { input ->
+ val out = java.io.ByteArrayOutputStream()
+ val buffer = ByteArray(16 * 1024)
+ var remaining = MAX_LEARN_INPUT_BYTES
+ while (remaining > 0) {
+ val read = input.read(buffer, 0, minOf(buffer.size, remaining))
+ if (read < 0) return out.toString(Charsets.UTF_8.name())
+ if (read == 0) continue
+ out.write(buffer, 0, read)
+ remaining -= read
+ }
+ if (input.read() != -1) null else out.toString(Charsets.UTF_8.name())
+ }
+ } catch (_: Exception) {
+ null
+ }
+
+ fun learnAccounts(vararg loginUsers: java.io.File): Boolean {
val names = LinkedHashSet()
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
var unread = false
for (file in loginUsers) {
if (!file.isFile) continue
- val text = try { file.readText() } catch (e: Exception) { unread = true; continue }
- kv.findAll(text).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.forEach { names += it }
+ val text = boundedText(file)
+ if (text == null) {
+ unread = true
+ continue
+ }
+ for (match in kv.findAll(text)) {
+ val name = match.groupValues[2].trim()
+ if (name.length < 3) continue
+ if (name.length > MAX_ACCOUNT_LENGTH || names.size >= MAX_LEARNED_ACCOUNTS) {
+ unread = true
+ break
+ }
+ names += name
+ }
}
val learned = names.map { name ->
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
Learned(Regex("(?i)(? = emptyList()
- fun learnOwnAddresses(linkFile: java.io.File) {
+ fun learnOwnAddresses(linkFile: java.io.File): Boolean {
val found = ArrayList()
try {
- if (linkFile.isFile) linkFile.forEachLine { line ->
- val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
+ val text = if (linkFile.isFile) boundedText(linkFile) ?: return false else ""
+ text.lineSequence().forEach { line ->
+ val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEach
+ if (found.size >= MAX_LEARNED_ADDRESSES) return false
when (kind(addr)) {
"public IPv6" -> {
- val groups = expand6(addr)?.take(4) ?: return@forEachLine
+ val groups = expand6(addr)?.take(4) ?: return@forEach
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
found += Learned(
Regex("(?i)(? = rank(folder).exes
- fun rank(folder: File): GameExePicker.Ranking {
+ fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
+ if (reuse) kept?.rank(folder)?.let { return it }
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
val declared = declaredExes(folder)
val preferred = declared.map { it.path }.toSet()
@@ -114,23 +115,27 @@ object AddedGames {
)
if (ranked.size > 256) ranked.clear()
ranked[key] = now to result
+ kept?.keepRank(folder, result)
return result
}
private val ranked = java.util.concurrent.ConcurrentHashMap>()
private const val RANK_FRESH_MS = 60_000L
+ @Volatile private var kept: AddedGamesCache? = null
private val identified = java.util.concurrent.ConcurrentHashMap()
internal fun identifiedName(folder: File, exe: File): String? {
val key = "${exe.path}|${exe.length()}|${exe.lastModified()}|${folder.lastModified()}"
identified[key]?.let { return it.ifEmpty { null } }
+ kept?.name(key)?.let { identified[key] = it; return it.ifEmpty { null } }
val id = runCatching { GameIdentifier.identify(exe) }.getOrNull()
val found = id?.name?.takeIf {
id.nameSource in setOf(GameIdentifier.Source.STEAM_MANIFEST_ACF, GameIdentifier.Source.GOG_INFO, GameIdentifier.Source.PE_VERSION)
}
val name = found?.let { if (id?.nameSource == GameIdentifier.Source.PE_VERSION) betterSpelling(underscoresToSpaces(it), folder.name) else it }
identified[key] = name.orEmpty()
+ kept?.keepName(key, name.orEmpty())
return name
}
@@ -172,17 +177,17 @@ object AddedGames {
"launcher", "game", "engine", "system", "data", "app",
)
- internal fun groupGames(folder: File): List? {
+ internal fun groupGames(folder: File, reuse: Boolean = false): List? {
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(".") && !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 }
+ return dirs.filter { rank(it, reuse).exes.isNotEmpty() }.takeIf { it.size >= 2 }
}
- private fun expand(folder: File, entries: Set): List =
- if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
+ private fun expand(folder: File, entries: Set, reuse: Boolean = false): List =
+ if (folder.path in entries) listOf(folder) else groupGames(folder, reuse) ?: listOf(folder)
private fun entryFolders(context: Context): Set = AddedExes.list(context).map { it.folder }.toSet()
@@ -192,7 +197,19 @@ object AddedGames {
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
- fun scan(context: Context): List {
+ private val scanning = Any()
+
+ fun scan(context: Context): List = synchronized(scanning) {
+ val file = File(context.filesDir, AddedGamesCache.FILE)
+ val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
+ try {
+ scanAll(context)
+ } finally {
+ cache.save()
+ }
+ }
+
+ private fun scanAll(context: Context): List {
val out = ArrayList()
GamesFolderMigration.run(context)
val folders = listOfNotNull(
@@ -208,16 +225,16 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
- for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
+ for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
- scanGame(context, folder, out, single = entry)
+ scanGame(context, folder, out, single = entry, reuse = true)
}
- 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 (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
+ for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
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)
}
@@ -398,11 +415,11 @@ object AddedGames {
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
- private fun scanGame(context: Context, folder: File, out: MutableList, single: AddedExes.Entry? = null) {
+ private fun scanGame(context: Context, folder: File, out: MutableList, single: AddedExes.Entry? = null, reuse: Boolean = false) {
run {
val sidecar = StoreGameSidecar.read(folder)
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
- val ranking = rank(folder)
+ val ranking = rank(folder, reuse)
val candidates = ranking.exes
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGamesCache.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGamesCache.kt
new file mode 100644
index 0000000000..c27764dfbd
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGamesCache.kt
@@ -0,0 +1,87 @@
+package com.droiddeck.launcher.frontend
+
+import android.util.AtomicFile
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.util.concurrent.ConcurrentHashMap
+
+internal class AddedGamesCache(val file: File) {
+ private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
+ private class Name(val name: String, val at: Long)
+
+ private val ranks = ConcurrentHashMap()
+ private val names = ConcurrentHashMap()
+ @Volatile private var changed = false
+
+ init {
+ val json = runCatching { JSONObject(AtomicFile(file).readFully().toString(Charsets.UTF_8)) }.getOrNull()
+ json?.optJSONObject("ranks")?.let { all ->
+ for (path in all.keys()) runCatching {
+ val o = all.getJSONObject(path)
+ val exes = o.getJSONArray("exes")
+ val scores = o.getJSONArray("scores")
+ require(exes.length() > 0 && exes.length() == scores.length())
+ ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
+ List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
+ ))
+ }
+ }
+ json?.optJSONObject("names")?.let { all ->
+ for (key in all.keys()) runCatching { all.getJSONObject(key).let { names[key] = Name(it.getString("name"), it.getLong("at")) } }
+ }
+ }
+
+ fun rank(folder: File): GameExePicker.Ranking? {
+ val kept = ranks[folder.path] ?: return null
+ val age = System.currentTimeMillis() - kept.at
+ val top = kept.ranking.exes.first()
+ return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
+ }
+
+ fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
+ if (ranking.exes.isEmpty()) {
+ if (ranks.remove(folder.path) != null) changed = true
+ return
+ }
+ ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
+ changed = true
+ }
+
+ fun name(key: String): String? = names[key]?.takeIf { System.currentTimeMillis() - it.at in 0 until KEEP_MS }?.name
+
+ fun keepName(key: String, name: String) {
+ names[key] = Name(name, System.currentTimeMillis())
+ changed = true
+ }
+
+ @Synchronized
+ fun save() {
+ if (!changed) return
+ changed = false
+ val oldest = System.currentTimeMillis() - KEEP_MS
+ val keptRanks = JSONObject()
+ ranks.forEach { (path, r) ->
+ if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
+ .put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
+ .put("uncertain", r.ranking.uncertain))
+ }
+ val keptNames = JSONObject()
+ names.forEach { (key, n) -> if (n.at >= oldest) keptNames.put(key, JSONObject().put("name", n.name).put("at", n.at)) }
+ val atomic = AtomicFile(file)
+ var out: java.io.FileOutputStream? = null
+ try {
+ out = atomic.startWrite()
+ out.write(JSONObject().put("ranks", keptRanks).put("names", keptNames).toString().toByteArray())
+ atomic.finishWrite(out)
+ } catch (e: Exception) {
+ out?.let(atomic::failWrite)
+ changed = true
+ }
+ }
+
+ companion object {
+ const val FILE = "added-games-scan.json"
+ const val KEEP_MS = 7L * 24 * 3600 * 1000
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt
index 1d4fb5ef55..1359ecf953 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
+import android.os.Handler
+import android.os.Looper
import android.os.PowerManager
import android.util.AtomicFile
import android.util.Log
@@ -20,7 +22,11 @@ object AutoComponents {
private const val TAG = "AutoComponents"
fun appKey(game: Library.SteamGame): String? =
- if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
+ when {
+ game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> game.profileKey
+ game.library == Library.ADDED -> Integer.toUnsignedString(game.appId)
+ else -> game.appId.takeIf { it > 0 }?.toString()
+ }
fun autoPicks(findings: List, catalog: Map): Map {
val out = LinkedHashMap()
@@ -48,6 +54,8 @@ object AutoComponents {
val downloading = MutableStateFlow