feat: non-Adreno graphics stack (Venus, open driver pairs, gamescope patches) (#2029)

* Retain compositor resources when GPU completion is unconfirmed

* Stop quarantined GPU callers before retries and mapped writes

* Support Android hardware-buffer presentation over Wayland

* Support PowerVR swapchains and linear image imports in Gamescope

* Bundle verified PowerVR graphics components through existing build preparation

* Detect and select the system Vulkan backend on PowerVR

* Apply PowerVR Steam and game compatibility during normal launches

* Show PowerVR support through existing driver and component controls

* Update existing hardware guidance for system Vulkan support

* Import the shared system Vulkan readiness check

* Discover and propagate the actual PowerVR render node

* Prune obsolete PowerVR runtimes after guest processes exit

* Retain external DMA-BUF ownership after GPU quarantine

* Name the PowerVR HAL selection explicitly

* Isolate component UI tests from application startup

* Cover the inherited FEX preset in PowerVR profile tests

* Log test worker failures for CI diagnosis

* Remove temporary test logging after diagnostic CI

* Prefer system dependencies for the Android Vulkan loader

* Capture raw stderr before test worker termination

* Remove the temporary test worker crash probe

* Import pinned DXVK recipe prerequisite from PowerVR PR570

Copy only the standalone build recipe, source pin, BC-format prerequisite
and presentation-sync patch/check from wallentx/DroidDeck at d0f7264ea8.
Source: https://github.com/Droid-Deck/DroidDeck/pull/570
Preserve that proposal attribution; no Android app, compositor, managed
pack, private data or fork development history is imported.

* Add opt-in low32 GPU mapping adapter and integrity probes

* Add opt-in D3D9 single-sample workaround and fix HUD texel format

* Document verified production game workaround and publication scope

* Restrict reset diagnostics and create private output atomically

* Target official runtime review and document PR570 prerequisite provenance

* Fix runtime tool output isolation, mmap64 chaining and DST ambiguity

* Normalize swapchain backbuffers for the opt-in D3D9 single-sample path

* Experimental Samsung Xclipse support on the system Vulkan path

Detect Samsung's Vulkan HAL (vulkan.samsung.so) and its sgpu render node
alongside PowerVR, and run Xclipse through the same libhybris bridge:

- VK_LAYER_DROIDDECK_xclipse (tools/linuxfs/xclipse-layer), built with the
  glibc preloads and enabled only on Xclipse: sets bionic's environ for the
  driver's shader compiler, avoids immutable YCbCr samplers in compute
  layouts, forwards the KHR calibrated-timestamp entry points to the EXT
  ones, and reports textureCompressionBC and BC4/BC5 filtering over the
  compat layer's BC emulation.
- Upstream DXVK 2.6.2, pinned as a tar.gz component and selected on Xclipse:
  the driver has 128 bytes of push constants, DXVK 3 needs 256.
- android_wlegl accepts a zero stride and passes it through unchanged:
  Samsung's gralloc records none for GPU-only buffers.

Tested on a Galaxy A56 (Xclipse 540, driver 24.0.560): Steam Big Picture
and PICO PARK (D3D9).

* Xclipse layer: copy the device chain and track samplers per device

- Clear textureCompressionBC in a copy of the device-create chain (every
  structure up to the VkPhysicalDeviceFeatures2 that enables it) instead of
  writing the caller's structure; a chain led by a structure of unknown size
  is passed on unchanged.
- Track YCbCr samplers per device in a growable list, drop them on
  vkDestroySampler and device teardown, and fail sampler creation rather
  than leave one untracked when the list cannot grow.
- Fail descriptor set layout creation with VK_ERROR_OUT_OF_HOST_MEMORY when
  a replacement sampler array cannot be allocated, instead of passing the
  original YCbCr samplers to the driver.

* Xclipse layer: copy any device-chain structure the headers define

The chain copy that clears the emulated textureCompressionBC only knew a
handful of structure sizes, so a valid chain such as
VkPhysicalDeviceTimelineSemaphoreFeatures -> VkPhysicalDeviceFeatures2 was
passed on unchanged and the compat layer refused the bit. Size every
structure that may extend VkDeviceCreateInfo from a table generated from the
Vulkan registry (gen_device_chain.py, Vulkan-Headers 1.3.275, the headers
the build compiles with), and copy onto the heap instead of a fixed buffer.
Only a structure newer than those headers still passes the chain unchanged.

Add a regression test that runs the layer between a simulated loader and a
mock driver: the timeline-semaphore chain, pEnabledFeatures, an unknown
structure, the caller's structures left untouched, per-device YCbCr sampler
tracking with handle reuse, and the KHR calibrated-timestamp forwarding. CI
installs libvulkan-dev for it.

* Mali bridge (#517, by ASEbrahim) on the non-Adreno test branch

Squash of Droid-Deck/DroidDeck#517 (ASEbrahim/DroidDeck mali-bridge @ 6b823341): the Vulkan
bridge (tools/vkbridge) that runs the guest's Vulkan on the phone's own driver, with BC1-BC7,
clip/cull distance, vertex-divisor and depth-clip emulation and dma-heap memory sharing for Mali.
All of the bridge is ASEbrahim's work; squashed only to carry it on this test branch.

Combined with #570 on this branch, a device draws through exactly one path:
- Adreno: Turnip, unchanged (checked first; the bridge setting is ignored there).
- PowerVR / Xclipse with the system HAL and a render node: the system-Vulkan path (#570).
- Anything else with the Setup toggle on (Mali): the bridge.

* Test branch: keep #570's DXVK build recipe so its pinned PowerVR components verify

#602 adds output checks to tools/dxvk/build.sh; tools/powervr/fetch.py pins the exact
recipe the published PowerVR DXVK was built from, so the branch carries #570's copy.

* Test branch: make #570, #602 and #560/#561 pass each other's tests

- tools/dxvk/build.sh: #602's copy (its output checks) and the PowerVR pin in
  tools/powervr/release.json moved to that file's hash; the recipe's outputs are unchanged.
- droiddeck-session: the presentation block sets _bl_cef for #570's PowerVR path, and the UI
  block keeps main's order, defaulting to -cef-use-angle=vulkan when the block has not run.
- Compositor test harnesses: AHardwareBuffer stubs for #570's AHB import, and a stub for
  vkp_effects_forget_image (main #597) that #561's caller harness predates.

* Auto drivers for Mali and Xclipse on the non-Adreno test branch

Auto now picks an open driver pair for the GPU, the way it does for Adreno:
- Mali (no KGSL, /dev/mali0): the GPU's name ("Mali-G720-Immortalis MC12", from the vendor
  Vulkan driver or kbase's gpuinfo) picks the PanVK build: G52-G78 (Job Manager), G610/G710,
  G615 or G720. A Mali none of them covers (G925...), or one whose pair is not published yet,
  draws through the Mali bridge, switched on by Auto.
- Xclipse keeps the system-driver path as Auto; the RADV pair is offered as a manual choice.
- The pairs come from The412Banner/droiddeck-nonadreno-drivers (one pre-release per driver,
  each a DriverBundle zip). Only a device without an Adreno reads that repo.
- The importers accept PanVK and RADV libraries (libvulkan_panfrost / libvulkan_radeon).
- An open driver pair and the Mali bridge are alternatives: a selected pair turns the bridge off.
- TU_DEBUG is only set for Turnip, on an Adreno.

Every new branch is reached only when the device has no Adreno; an Adreno's detection, release
sources, Auto choice and session environment are unchanged.

* Auto: the one-binary PanVK kbase build for Mali v9-v13 on Android 15+

The412Banner/droiddeck-nonadreno-drivers adds panvk-mali-kbase: one PanVK build for
G57/G68/G77/G78, G610/G710, G615/G715, G720/G725 and G925, whose display half needs Android 15.
On Android 15+ Auto prefers it for every Mali it covers; below 15, and whenever its release is
not listed, Auto falls back to the GPU generation's own pair. G52/G76 keep the Job Manager
build; a G715/G725/G925 below Android 15, or any Mali no pair covers, draws through the bridge.
Every pair stays selectable by hand.

* Test: the G925 is in the kbase build's family now

* Offer faux123's device PanVK builds (RP4 Pro, Ace, RG556) as manual pairs for their Mali

* Detailed graphics logs for non-Adreno test reports

- graphics-report.txt in every session folder: the graphics path the session draws with and why
  (Turnip, system Vulkan #570, Mali bridge #517, or an open driver pair with its release), the
  driver mode and choices, what Auto would pick, the GPU (family, Vulkan device name, kbase
  gpuinfo, Android, SoC, kernel), the GPU nodes the app can see (access, device numbers, SELinux
  label; nothing is opened) and the guest's graphics environment. At the end it adds the
  compositor's driver lines from app.log and the game launches that were logged.
- vulkan-summary.txt: the session's own vulkaninfo --summary with the driver as exported, in the
  background with a 10 s timeout.
- Per-game logs under games/<time>-<appid>/: Proton's log, DXVK's and vkd3d-proton's, Mesa's and
  PanVK's startup messages and the launch environment, from droiddeck-game-env. Each file is cut
  to 20 MB and the folder to 120 MB at the session's end.
- The per-game logs and the Vulkan summary are on for a GPU that is not an Adreno, and on an
  Adreno only with Setup's new "Detailed graphics logs" switch. Share logs already takes the
  whole session folder, so all of it is in the zip, scrubbed as before.

* Mali pairs: a stand-in render node, the driver's real library name, and a Mali known by its chip

- Auto on Jim's Dimensity 9300+ chose the bridge: the GPU had no name (the app had not asked
  Vulkan yet and kbase's gpuinfo is unreadable under SELinux), so a Mali-G720 counted as a Mali
  no build covers. The name now falls back to the GPU the chip is known to carry (Dimensity,
  Helio, Kompanio, Tensor); and when nothing names it, Auto asks the vendor Vulkan driver off the
  main thread before it settles for the bridge. Auto logs what it decided and why.
- An open Mali driver pair gets /dev/mali0 as the guest's render node, as the bridge does
  (bindGpuNode, BL_DRM_STANDIN): gamescope needs the node the driver reports. The session shim
  only answers libdrm's PRIME and GEM-close calls on it, which PanVK on kbase never makes.
- A PanVK or RADV runtime half is installed as libvulkan_panfrost.so / libvulkan_radeon.so rather
  than under Turnip's name; Turnip keeps libvulkan_freedreno.so.
- graphics-report.txt names the render node the guest got, adds the session script's driver lines
  and flags a failed Mali-bridge self-test at the top.

* Auto takes the RADV pair on a Samsung Xclipse, with the system route as its fallback

A tester's Galaxy S24 FE (Xclipse 940) boots to Steam with the RADV-Xclipse pair, where the
system-driver route fails at Steam's OpenGL (glamor and GLX cannot load a driver). Auto now
downloads and selects RADV on an Xclipse like the Mali pairs, and falls back to the system route
only when RADV is not published. #570's reset of both drivers at each start no longer undoes an
open driver pair. PowerVR (vulkan.powervr.so) keeps the system driver as before.

* An Exynos with a Mali is a Mali, not an Xclipse

The system route took vulkan.samsung.so as Samsung's Xclipse, but an Exynos 1280/1380 (Galaxy Tab
S9 FE: Mali-G68) may name its HAL the same; with /dev/mali0 present that HAL is not the system
route's, and the device is detected as the Mali it is. The chip table adds the Exynos 1380 and
1280 (s5e8835, s5e8825: Mali-G68).

* Auto fetches the open drivers itself; Xclipse named as such; sound and frame-gen in the logs

- Auto looks online again when its saved release list predates this device's open drivers, so a
  Samsung or Mali phone gets its pair without pressing refresh first.
- A Samsung Xclipse is labelled "Samsung Xclipse" (not PowerVR), with its own support line.
- Per-game logs add audio-streams.txt: PulseAudio's sink inputs 20 s and 60 s into the launch,
  so a silent game shows whether its stream reached Pulse.
- graphics-report.txt states the frame-generation setting and keeps the LSFG gate, FrameGen and
  audio lines from app.log.

* Client sound retries a briefly disconnected AAudio; kbase ioctl refusals explained in the report

A Galaxy S24 FE's session had no sound at all: the DirectAudio sink's AAudio stream opened with
AAUDIO_ERROR_DISCONNECTED while the output route was still changing at session start, and the
plain AAudio fallback failed the same moment. The sink guard now retries DirectAudio, then the
plain sink, five times over ten seconds and says which one it got. graphics-report.txt keeps the
client-sink and kbase lines, and explains a KBASE_IOCTL_MEM_EXEC_INIT EPERM as the kbase driver's
own answer rather than the session's sandbox.

* Mali pairs draw the display on the phone's own Mali driver; Xwayland falls back without glamor

- Testers' Mali pairs got the guest drawing (gamescope on the stand-in node, Zink on PanVK) but
  the compositor's PanVK Android half failed on Mali gralloc: it probes AHB formats 0x38/0x3b that
  mali_gralloc does not have, and "vkCreateImage w/ native buffer failed". Under Auto a Mali pair
  now leaves the display on the phone's own Vulkan driver (dma-buf, modifiers and AHB all pass the
  testers' checks) and runs the pair's PanVK in the guest; the Android half stays installed for a
  manual pick. "Pair in use" now follows the runtime half.
- A session after one whose Xwayland crashed (segfault, then gamescope's X11 I/O error) starts
  Xwayland with XWAYLAND_NO_GLAMOR=1 on a non-Adreno device, and says so in app.log.
- graphics-report.txt names the display driver the compositor used, and keeps gralloc, dma-buf,
  modifier and import lines from app.log and Xwayland's own lines from the session log.

* Non-Adreno sound: the daemon falls back on its own; the build's commit in device.txt and the report

The S24 FE's session still had no sound: its AAudio refuses DirectAudio's low-latency stream with
AAUDIO_ERROR_DISCONNECTED, and the sink guard never got to retry because pactl did not reach the
daemon in time ("the daemon did not answer in 15 s"). On a GPU that is not an Adreno the daemon's
own start-up script now asks DirectAudio again without low latency and loads the plain AAudio sink
underneath it, so a default sink exists whatever pactl does. device.txt and graphics-report.txt
name the build label and source commit, so a log says which build it came from.

* Non-Adreno sound: no second DirectAudio load (it hung the daemon); the plain AAudio sink underneath

On the S24 FE the daemon stopped after DirectAudio's failed low-latency load: the second
DirectAudio load in the same daemon never returned, so nothing after it ran and pactl never
connected. The daemon now loads only the plain AAudio sink (no low latency) after DirectAudio,
inside .nofail, and sets whichever exists as the default.

* gamescope: explicit sync off where the kernel or the stand-in node cannot signal its timelines

Adds tools/gamescope/patches/0126 (GAMESCOPE_DISABLE_EXPLICIT_SYNC=1 for the nested backends) and
sets it on a GPU that is not an Adreno when the kernel is older than 6.6 (no
DRM_IOCTL_SYNCOBJ_EVENTFD) or the guest's render node is Mali's stand-in. The graphics report
lists it with the rest of the guest's graphics environment.

* Test branch: gamescope with the explicit-sync switch (0126), pinned by sha

Built by build-gamescope.yml run 38335744351 from 0136fb61 and published as a component release
of The412Banner/droiddeck-nonadreno-drivers; the apk build fetches it by tag and checks the sha.

* Sound: nothing that can block in the daemon's start-up; Steam's web compositing in software on open pairs

- The S24 FE (US) daemon hung loading the plain AAudio sink from default.pa (its AAudio open
  blocks rather than fails), so it never finished starting. default.pa is back to DirectAudio
  alone inside .nofail; the fallbacks are loaded from the app once the daemon answers, each pactl
  bounded by its timeout (DirectAudio, then the plain sink with and without low latency). The
  guard waits 30 s and logs, with timestamps, how long the daemon took, whether its socket and
  pactl exist, and what it finally got.
- With an open driver pair on a GPU that is not an Adreno, Steam's CEF composites in software
  (-cef-disable-gpu-compositing) with GPU raster kept: RADV on Xclipse showed stale, half-written
  tiles, as #570 saw on PowerVR. The session log says so.

* Mali under Auto: the display always on Android's own Vulkan loader; a reboot hint for refused audio

Axel's Tab S9 FE still drew its display with the PanVK Android half, set by an earlier build, and
stalled at "Waiting for Steam's first frame" on Mali gralloc's format probes. Under Auto a Mali's
display now goes to Android's own loader whatever was set before (DriverMenus resets it, and the
compositor's driver choice ignores a pair's Android half), with no HAL path to find first. A pair
counts as in use when its runtime half is. A manual pick of the PanVK display is kept.
When audio.log shows AAUDIO_ERROR_DISCONNECTED, the report and the client-sink line say Android
refused the output and that rebooting the phone usually fixes it.

* Fix: call SessionPrefs.gpuDriverMode through its instance from Java

* Compositor: log each new dma-buf format/modifier/size it imports (for colour and swizzle reports)

Steam's software web compositing already covers every open driver pair, Mali included.

* Open driver pairs: vkd3d-proton reports the driver's caps; buffer attach/release tracing; Mesa log

- With a PanVK or RADV pair (BL_OPEN_DRIVER=1), droiddeck-game-env drops the app-wide
  VKD3D_FEATURE_LEVEL=12_2 and VKD3D_SHADER_MODEL=6_9 so vkd3d-proton reports what the driver has
  (an Unreal DX12 game crashed at start on PanVK with the overrides); a game's own setting still
  wins, and launch.txt records DROIDDECK_VKD3D_CAPS=driver.
- The compositor traces, on a GPU that is not an Adreno, the first 400 dma-buf attaches and buffer
  releases by wl_buffer id and sending line, and logs any release of a buffer already released
  and not attached again (gamescope's "Compositor released us but we were not acquired" on G925).
- Per-game logs no longer set MESA_DEBUG=silent, which kept mesa.log empty.

* Tests: the dma-buf quarantine harness follows send_buffer_release's tracing macro

* Mali (Venus): David Cimo's Venus route sources and recipes

From DavidCimo/droiddeck-mali, branch mali-venus @ 4f838891 (prototype 13; his 12 commits on top
of DroidDeck 0.3.1, GPL-3.0), by David Cimo:
- tools/venus: Mesa Venus vtest patch (incl. the per-queue submit_mutex fix and the cached-memory
  frame readback), virglrenderer Android patch, the Mali compatibility layer (the six features
  DXVK needs: fill modes, multi-viewport, robustness2, clip/cull distance, BC1-BC7) and his tools.
- tools/linuxfs/preload/venus.c: keeps Zink's kopper under Venus.
- tools/gamescope/patches/0127 (his 0114): shm buffers uploaded on every commit.
- docs/development/mali-venus.md: his design notes.
- tools/venus/ci-build.sh and build-venus.yml: his build recipes as one CI job that packs the
  component (vtest server, ICD, layer) as venus.tzst for the apk.

Co-authored-by: Dersim Abbas <derabb0620@gmail.com>

* Mali (Venus) as a selectable route, by David Cimo

Ports David Cimo's Venus route (DavidCimo/droiddeck-mali, mali-venus @ 4f838891) onto this branch
as "Mali (Venus)", one tap in Setup next to the Mali bridge:
- VenusComponent (his): stages the Venus ICD and runs virglrenderer's vtest server over the
  phone's own Vulkan driver; the guest gets VK_ICD_FILENAMES, VN_DEBUG=vtest, VTEST_SOCKET_NAME and
  MESA_VK_WSI_DEBUG=sw.
- Selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an Adreno nor
  a system-driver one (PowerVR, Xclipse), and the apk carries it. It then replaces the Mali bridge
  and any open driver pair for the session, and the display stays on the phone's own driver.
  Auto is unchanged (the PanVK pair). Adreno never takes any of it.
- The compositor enables only the dma-buf extensions the driver has, logs a vendor driver's
  extension list, and gives a zero row pitch a packed row (his vk_present.c changes).
- The Mali compatibility layer is staged into the runtime on non-Adreno devices only.
- The component (vtest server, ICD, layer) comes from build-venus.yml as venus.tzst, published on
  The412Banner/droiddeck-nonadreno-drivers and pinned by sha in tools/venus/release.env.
- gamescope 3.16.29-p15 adds his shm upload patch (0127) next to 0126; pinned by sha.
- device.txt and graphics-report.txt name the route.

Co-authored-by: Dersim Abbas <derabb0620@gmail.com>

* Mali: Venus gamescope without robustness2, the bridge switch honoured and kept, clean driver switches

- gamescope 0128: VK_EXT_robustness2 is optional. A Mali driver through Venus has none, and
  gamescope stopped at "Missing required extension: VK_EXT_robustness2" (the wayland_surface error
  after it was only the knock-on). Without it, unused descriptor slots point at a 1x1 texture
  instead of VK_NULL_HANDLE. (David Cimo's Pixel 9 driver has robustness2, so his build never
  needed this.) gamescope component rebuilt and pinned by sha.
- Open-files limit: on a GPU that is not an Adreno the session script raises the soft limit to the
  hard limit for the whole session tree (a PanVK-kbase session froze on "Too many open files"
  after ten minutes) and graphics-report.txt shows before and after. A stopgap; the driver leak is
  fixed separately.
- The Mali bridge switch is honoured: when on and usable it wins over a PanVK pair for the
  session (Venus still wins over it). Selecting a pair no longer switches the bridge off, which is
  why the switch did not survive an app restart (Auto re-selected the pair at start). Setup says
  when this phone cannot use the bridge at all.
- Driver switching: picking a Mali pair by hand keeps the display on the phone's own driver, as
  Auto does (a PanVK Android display stalls on Mali gralloc at "Waiting for Steam's first frame",
  and stayed set after switching back); installing a bundle again replaces it instead of adding a
  "-2" copy beside the old one.
- graphics-report.txt names the runtime driver's folder and libraries, and the previous session's
  drivers, flagged when they changed.

* gamescope p16 (0128 robustness2 optional), pinned by sha; graphics-report says who chose the display driver

* Bundle replace only for open non-Adreno pairs; Adreno bundles keep their numbered copies

* Rebuilt open drivers reach phones: re-downloaded when their digest changes, release list hourly on non-Adreno

The non-Adreno driver releases replace their assets in place (the PanVK kbase sync-file fd leak
fix). A download is now remembered with its GitHub sha256, and an asset whose digest changed
counts as not installed, so Auto fetches it again and the bundle replaces the old one; the release
list is re-read after an hour instead of a day on a GPU that is not an Adreno.

* Mali compatibility layer: multiDrawIndirect, depthClipEnable and robustness2 for DXVK on Venus

A Galaxy A15 (Mali-G57) on Venus got gamescope and Steam up, but DXVK refused the GPU:
"Device does not support required feature 'multiDrawIndirect'". DXVK 3.1 stops at the first
missing feature, so the rest of its required list (dxvk_device_info.cpp) was checked against what
the testers' Mali drivers cannot have, and covered in the same pass, on top of David Cimo's six:
- multiDrawIndirect: reported, taken off the device, and an indirect draw with drawCount > 1 is
  recorded as single draws at offset + i * stride; maxDrawIndirectCount reported as 2^30.
  (drawIndirectCount is optional for DXVK and stays as the driver says.)
- VK_EXT_depth_clip_enable (required): offered when the driver lacks it; depthClipEnable off in a
  pipeline becomes depthClampEnable, and the extension's structures never reach the driver.
- VK_EXT_robustness2 missing entirely (gamescope saw the same on these phones): offered with
  robustBufferAccess2 (as robustBufferAccess, as before) and nullDescriptor, emulated by small
  stand-ins (a zeroed buffer, a 1x1 image) for VK_NULL_HANDLE buffers, image views and vertex
  buffers in plain, template and push descriptor writes and vertex-buffer binds. A null
  texel-buffer view stays null (its format is not known).
The layer logs every feature it emulates per device.

* Venus component 22694a38 (layer: multiDrawIndirect, depthClipEnable, robustness2), pinned by sha

* Non-Adreno round 3: bridge images, Venus GL, shared buffers, Steam GPU drawing

- vkbridge: the memory model skips lazily allocated types. Mali-G615 lists
  DEVICE_LOCAL|LAZILY_ALLOCATED first; taken as the device-local type it left
  images with no memory type (self-test "image clear/draw: setup" FAIL,
  gamescope "No compatible image memory type").
- Session: a bridge self-test that fails images or draws falls back to the
  runtime's driver pair for that session (BL_VKBRIDGE_FALLBACK_ICD); Setup
  and the graphics report say so.
- Venus: the Mali compatibility layer runs in every process but gamescope
  (DROIDDECK_MALI_COMPAT=1), so Zink in Steam and Xwayland gets
  nullDescriptor; null texel-buffer views get stand-ins too. Without
  nullDescriptor the session's GL goes to llvmpipe.
- gamescope 0129: a refused compute pipeline is named with its SPIR-V
  capabilities.
- Compositor: a buffer on two surfaces at once (gamescope's planes while a
  notification is up) is released only when the last one lets go.
- Open driver pairs: processes.txt timeline for the first three minutes;
  Setup "Steam interface: GPU drawing" turns off software web compositing.

* Pin gamescope p17 (0129) and Venus 55b30fbf

* Non-Adreno round 4: Mali GPU-drawing block, gamescope YCbCr retry, GL probe, bridge draw sync

- Setup's "Steam interface: GPU drawing" is hidden on Mali and a saved "on" is
  cleared: with PanVK it rebooted an Edge 60 (G615) as steamwebhelper started.
  Kept for Xclipse.
- gamescope 0130: a composite pipeline refused at start-up is retried with a
  layout without immutable YCbCr samplers (G615 through Venus refused every
  composite shader; their SPIR-V has no Float16, so fp16 was not the cause).
- Venus: droiddeck-glprobe opens GL through GLX the way the Steam client does,
  with the loader's reasons logged; when it fails the client's GL goes to
  llvmpipe.
- vkbridge self-test: the draw check waits for the render pass's stores before
  copying out (a tiler read zeros without the dependency).

* Pin gamescope p18 (0130)

* Non-Adreno round 5: gamescope memory fallback, Venus destroy guard, OpenAL depot

- gamescope 0131: DEVICE_LOCAL|HOST_VISIBLE requests fall back to host-visible
  memory (the bridge's unified-memory model lists none with both), with the
  request, type bits and memory types logged on failure; 0130's probe pipeline
  is kept and skipped when forced.
- Venus: GAMESCOPE_NO_YCBCR_SAMPLERS=1 from the start; virglrenderer ignores
  the destroy of a pipeline it never created instead of marking the context
  fatal (vtest server exit 137 on a Mali-G615).
- Steam's OpenAL depot (229020) maps to oalinst_dll, so games that list it
  (Hotline Miami) get OpenAL in their prefix.

* Pin gamescope p19 (0131) and Venus 6199a93f

* Non-Adreno round 6: PowerVR PRIME on old kernels, thermal, hang-up names, bridge flippable images, Venus Zink variants

- drm.c: PR #570's current PRIME ownership check (F_DUPFD_QUERY, then kcmp,
  then the F_SETOWN_EX owner marker): on a kernel before 6.10 with kcmp
  blocked, drmPrimeFDToHandle answered EOPNOTSUPP for every PowerVR import
  (Pixel 10, Android 17: Zink "failed drmPrimeFDToHandle", Xwayland error 7,
  gamescope X11 I/O error). The Mali stand-in node is kept.
- A /sys/class/thermal the kernel will not list gets an empty directory, so
  mangoapp no longer aborts on it.
- gamescope 0132: a hung-up waitable is named before the abort; 0133: the
  bridge's flippable images use supported-but-unexportable modifiers instead
  of asserting.
- Venus: when Zink does not start, the loader's view is logged and Zink is
  retried without ZINK_DEBUG=compact, with ZINK_DESCRIPTORS=auto and without
  kopper before falling back to llvmpipe.

* Pin gamescope p20 (0132, 0133)

* Non-Adreno round 7: bridge command-buffer guard, Venus Zink trace, PowerVR mangoapp, Xclipse label

- vkbridge server: every command buffer a device hands out is tracked; Begin,
  End (stream replay) and QueueSubmit refuse one it never allocated or has
  freed (VK_ERROR_DEVICE_LOST, logged) instead of passing it to the driver,
  where Mali's vkBeginCommandBuffer crashed the app (SIGSEGV 0x10, Steam's
  Zink on an Edge 60 and a Tab S11).
- vkbridge server: a fault inside the driver while serving a request cuts
  that client off (SIGSEGV/SIGBUS guard per request) and leaves its objects
  alone; the app and the other clients carry on. Other faults go to the
  previous handler.
- vkbridge server: the pipeline cache directory is copied; the JNI string it
  pointed at was freed (garbage in the cache path).
- Venus: DROIDDECK_MALI_COMPAT_TRACE=1 makes the Mali compatibility layer log
  what an application queries before vkCreateDevice; a failed glprobe adds a
  traced run and vulkaninfo --summary under the same environment.
- PowerVR: mangoapp draws with llvmpipe (Zink could not make it a swapchain
  and it crashed at every start).
- Setup: an Xclipse GPU reads "Experimental: RADV or the system Xclipse
  driver", not the PowerVR line.

* Pin Venus e40cd361 (layer trace)

* Non-Adreno round 8: bridge sharing fallback and crash detail, Venus diagnostics and 1.2 gate, compositor disconnect reasons, RADV upstream

- Mali bridge: the self-test fails "memory sharing" when the server offers
  no host-visible memory type (no sharing method passed, RP4 Pro G77); the
  session then falls back to the PanVK pair like a failed draw, and Setup
  says the bridge cannot share memory with that driver. Without a pair to
  fall back on, the log says so.
- Mali bridge: a guarded driver crash now logs the sub-command it was in,
  the fault address and pc (library + offset via dladdr), the command
  buffer's level, begin flags, pool flags and state, and the last 32
  replayed commands. Begin on an executable buffer from a pool without
  RESET_COMMAND_BUFFER_BIT is logged once (implicit reset).
- Venus: vulkan-summary.txt gets the device extension list and key
  features (full vulkaninfo in vulkan-full.txt); a failed GL probe runs
  once with VN_DEBUG=init,result, ZINK_DEBUG=mem, MESA_LOG_LEVEL=debug and
  the layer trace into glprobe-trace.txt. The Mali compatibility layer's
  trace covers every pre-device query (devices, memory, queue families,
  formats, image formats, external handles) and names the extensions.
- Venus: off when the phone's driver reports Vulkan below 1.2 (gamescope
  skips such a device); Setup and the graphics report say why and the
  session uses the PanVK pair.
- Compositor: libwayland's own disconnect reasons go to wayland.log, and a
  client's buffer may grow to 1 MB before a slow reader is dropped. A
  session that ended without teardown records Android's exit reasons.
- Drivers: RADV-Xclipse upstream (radv-xclipse-upstream) is a manual
  choice for Xclipse; Auto keeps radv-xclipse.

* Tests: the terminal-callers harness stubs the Quest layer and Cardboard modules and Android's system properties

* Pin gamescope p21 (main's patches + 0120-0133) and Venus a4d47cf3 (layer trace)

* Display driver Auto: Quest's patched Turnip first; the system driver only for a Mali, other GPUs keep the generic fallback

* Open driver pairs: the installed build's version, its upload date, and an Update when the release is rebuilt in place

- The release check records each asset's GitHub id and updated_at; a
  download records them (with the digest) for an open non-Adreno pair.
- Components > GPU drivers: an installed open pair shows its manifest
  version ("android <tag> + linux <commit>"), one not yet installed shows
  "built YYYY-MM-DD". A different digest, asset id or upload time on the
  same tag marks the installed pair "Update available" with an Update
  action: the pair is downloaded again and replaced in place, and stays
  selected only if it was. Adreno and DD-Turnip pairs are unchanged.
- graphics-report.txt: the pair release line gives the installed and the
  listed upload dates and flags a newer build; an exact bundle id match is
  preferred (RADV-Xclipse-upstream is not RADV-Xclipse).

* Session preload: drop oom_score_adj raises so lmkd does not treat games as cached apps

steam-launch-wrapper starts every game with --oom-score-adjust 900; on
Android 900 is CACHED_APP_MIN_ADJ, so lmkd kills the running game first
when memory runs short (and on Linux 6.1 the raise becomes the process's
permanent minimum). A process in the app cannot go below the score it
inherits, so the writes that succeed from inside are raises: every
write-open of /proc/<pid|self|thread-self>[/task/<tid>]/oom_score_adj (or
oom_adj), through open/openat or fopen, goes to /dev/null, logged once.

Based on the oom_score_adj redirect in the preload's opens.c by jdmg28 (https://github.com/jdmg28/DroidDeck-Mali/commit/6be00e00)

* Display: why presenting failed on the session-ended screen, and the display driver that really loaded

- The compositor records why it cannot present (no Vulkan driver loaded,
  vkCreateInstance/vkCreateDevice failed, no GPU or graphics queue, no
  swapchain on the screen with the driver's reason, device lost, GPU work
  unconfirmed). Each is a DD_PRESENT_FAULT line in wayland.log, read back
  over JNI or from wayland.log; the session-ended screen shows it instead
  of a black screen, and graphics-report.txt gets "!! DISPLAY FAILED". A
  first frame or a working swapchain clears it.
- After the display device is created, the driver that answered is logged
  from VkPhysicalDeviceDriverProperties (device, driverName, driverInfo,
  driver id, Vulkan version) and reported in graphics-report.txt. When a
  driver pair's display half was requested but a vendor driver answered
  (adrenotools falls back to the system driver when the requested one does
  not load), it says so.

Based on DD_PRESENT_FAULT in vk_present.c / waylandcomp_jni.c / SessionActivity by jdmg28 (https://github.com/jdmg28/DroidDeck-Mali/blob/arena/cd8ab18a-droiddeck-mali/app/src/main/cpp/waylandcomp/src/vk_present.c)
Based on the adrenotools silent-fallback finding by ryanistr (https://github.com/ryanistr/DroidDeck-Mali/blob/main/docs/development/panvk-mali-g77-bringup.md)

* tests: steam presentation test sets 0.5.0's steam_client

* Non-Adreno: find every driver pair, Venus before the bridge, fix the bridge's begin info

From the logs testers sent since c9ebb247:
- The app read the drivers repo's newest 15 releases only; the component releases (gamescope,
  Venus) pushed every PanVK pair and RADV-Xclipse past them, so Auto found no pair on any Mali
  and switched the Mali bridge on. The non-Adreno repo is now read in one page of 100.
- Auto's stand-in for a missing pair: Mali (Venus) where the apk carries it (Steam runs on it
  from the G57 to the G1-Ultra), the bridge otherwise, nothing on a driver below Vulkan 1.2. It
  no longer clears the Linux driver, does nothing when the list could not be read, records that
  it chose the route, and turns it off again once a pair is installed. A bridge that earlier
  builds left on under Auto is taken as Auto's.
- Mali bridge: vkBeginCommandBuffer sent its begin info without the count the server decodes, so
  Mali got a zeroed begin info with stale flags and crashed at 0x10 (Pixel 8 Pro G715, Lenovo
  G615, Xiaomi G925, Tab S11).
- Mali-G1 series (MT6993, arch v14) known by its chip; its label says Venus, not the bridge.
- A session Android killed for memory is said so on the next start (the S24 FE "crashes" were
  low-memory kills, not driver faults).
- The in-app updater never installs an official (Adreno-only) build over this test build.

* Venus: destroy the device's object mutex after the objects that lock it

Bionic aborts on locking a destroyed mutex ("pthread_mutex_lock called on a destroyed mutex",
Tab S9 FE G68, Pixel 9a), so a client that exited holding objects took the render worker down.
From BattleTempest's DroidDeck-Pixel (kevinbryant551-ux/DroidDeck-Pixel, GPL-3.0).

* release check: a session helper may be extracted to another runtime path

droiddeck-steam-taskset (#570) goes to usr/local/libexec/droiddeck-steam/taskset, where PATH puts
it in front of Steam's own taskset for the client only; 0.5.0's check wanted every droiddeck-*
helper at its own path.

* Venus component 93038b7d (destroyed-mutex fix)

* Update MaliBridge to v0.5.1 (#1135)

* Mali Auto: never leave a session on the runtime's Turnip

Logs from a Retroid Pocket 4 Pro (G77), Galaxy S21 Ultra (G78), Tab S11 Ultra
(G925) and Xiaomi G610 showed Auto ending on the runtime's Turnip, where
gamescope finds no GPU ("failed to find physical device"): after a pair's
trial rolled back, when the pair is on the bad list, and when the driver
list could not be read. In each case Auto now switches on its stand-in
(Venus, or the bridge) when no open driver, Venus or bridge is set.
Under Auto the Mali display also leaves any imported driver, not only a
pair's PanVK half (a lone PanVK_G720 import gave a black screen).

* Mali bridge: MaliBridge 224b6e36 (v0.5.3 source, by ASEbrahim)

From c65062b6 (v0.5.1). v0.5.2/v0.5.3: Steam mode on older Mali drivers
(G77/G710/G610/G57) gets past "starting display and audio", OpenGL 4.6 on
most Malis through dynamic-rendering and vertex-format emulation, Dimensity
9500 texture fixes, async pipeline compile, RE2 flicker on G925, DirectX on
the Pixel 8 family. JNI entry and session env names are unchanged.

* gamescope 0134: linear when the backend offers no modifier; Venus on Mesa 26.2.5

0134: CVulkanTexture::BInit asserted !modifiers.empty() when the nested Wayland
backend offered no modifier for a flippable image's format (NieR Replicant on a
Pixel 9a under Venus, session exit 134). It now tries linear and logs it.
Venus ICD: mesa-26.2.5 (venus TLS teardown from an unloaded driver, virtio-gpu
devices without 3D skipped); virglrenderer stays on 1.3.0.

* gamescope p22-nonadreno (0134 + main's 0116 cursor fix; build run 40159674290)

* CI: build the non-Adreno additions before the preload check

* build.gradle: drop verifyHandModel (main moved the hand models into the tracking pack)

* Venus component venus-proto13-e24ed8ab (Mesa 26.2.5; build run 40161447324)

* CI: fetch the Mali (Venus) component again (lost when build.yml took main's jobs)

Build a7a1ebf1 (run 40161734101) had no assets/venus or libvirgl_test_server.so, so
VenusComponent.available() was false and Auto's stand-in would have been the bridge.

* Auto: the Mali bridge stands in on a Vulkan 1.1 Mali driver

Auto refused both Venus and the bridge when the phone's driver reports Vulkan
below 1.2, so on the G77, G78 and G610 (r32p1/r38, Vulkan 1.1) a rolled-back or
missing pair left the runtime's Turnip: "failed to find physical device"
(Retroid Pocket 4 Pro after the JM pair's trial, Xiaomi 13T). Only Venus needs
1.2; the bridge raises the driver for gamescope and runs on these phones. A
Venus switch that cannot start on such a driver no longer counts as a route.

* Tests: stub main's g_release_unpaced in the DMA-BUF quarantine probe

The probe copies release_buffer out of compositor.c; since the merge it reads
g_release_unpaced, which the harness did not declare (setUpClass failed to compile).

* Update MaliBridge to v0.5.4 (ASEbrahim)

48477fe6 (tag v0.5.4): Dimensity 9500 green squares and red-tinted textures,
Balatro and other OpenGL text, fewer crashes when memory runs low, one screen
update per game frame, picture kept after a long background pause (SIGHUP no
longer stops the server), wrong colours after changing graphics settings on
the G720, more in the session report. The app-side changes of his DroidDeck
Mali app (Steam menus setting, per-game setup, Send logs, updates) are not
part of the MaliBridge repository and are not in this build.

* gamescope 0135: linear when the driver rejects every offered modifier

An r32p1 Mali-G610 (Vulkan 1.1) behind the Mali bridge answered both of the
backend's modifiers for AR24 with VK_ERROR_FORMAT_NOT_SUPPORTED, so the first
flippable image failed and gamescope asserted in vulkan_create_flat_texture
(Xiaomi 13T). Linear, when offered, is tried anyway; the bridge makes such
images without the handle type and exports them through a dma-heap. If the
image cannot be made, BInit fails as before.

* gamescope: pin the non-Adreno p23 build (0135)

* Tests: the terminal-callers harness stubs take_shm's game-frame detection

Main's take_shm now reads surface damage, parent/role/mapped and the HUD state
to spot game frames; the harness declares them so the copied function compiles
(setUpClass failed in Build APK run 40505286127). No damage, so it stays off.

* gamescope: number the test branch's patches 0920-0935

Main now has its own 0121-0125 (window override walk, host-event wake, commit fences, done at
import, HUD frame times), which sorted in between this branch's 0120-0135. The branch's sixteen
patches move to 0920-0935 with the same last two digits, so they apply after main's set and stay
clear of its next numbers. Applying all 38 to gamescope 3.16.29 in the old order and the new one
gives the same tree (checked with patch -p1, as build-in-arch.sh does). PATCHES.md and the one
code comment that named 0130 follow the new numbers.

* check_session_assets: helpers count in usr/local/bin or the Steam taskset folder only

The merge kept this branch's pattern (any usr/ target), which main's new test rejects: a helper
extracted into a subfolder of usr/local/bin must not count. The pattern now takes usr/local/bin
under any name, as on main, plus usr/local/libexec/droiddeck-steam for droiddeck-steam-taskset.
Every helper in the overlay is still found extracted in SessionFiles.kt.

* gamescope: pin 3.16.29 p24 (non-Adreno)

Built from this branch @d13b9d88 (run 41119284267): main a5b035b2's patches plus this branch's,
now 0920-0935. All 38 applied, gamescope's tests 2/2. sha256 1d1088d4.

* Update MaliBridge to v0.5.4.2 (ASEbrahim)

95a1e600 (tag v0.5.4.2), was v0.5.4 (48477fe6). For the bridge: memory sharing without the handle
type where that is all the self-test passed (unflagged buffers, client/memory.c, server_memory.c),
the older-Mali (G52-G77) game-mode start fixes, the r38p1 beta geometry-shader erratum (gs_hide),
present timeouts and an API cap per process. Client, server and the in-app library all build from
the submodule with MaliBridge's own scripts, which did not change; the protocol only gained
fields an older server sends as 0.

* Session end: the compositor fault query no longer fails the hint when the native library is absent

presentationFault() (6778a224) called WaylandCompositor.compositorFault() directly. Main's new
SessionEndHintTest runs sessionEndHint() in Robolectric, where libdroiddeckwayland cannot load, so
all six cases ended in UnsatisfiedLinkError (Build APK run 41125749537). The call is now wrapped
like runtimeDamageHint()'s, and without an answer the hint reads wayland.log as before.

* test: stub the GPU busy reader in the caller harness

* fix: release build is not debuggable, Mali uses the system display driver, staging failure ends its own session

* fix: address non-Adreno review findings

* fix: preserve current gamescope and GPU warning behavior

* fix: retain graphics failure hints and launch diagnostics

* fix: identify non-Adreno GPUs in driver failure hints

* test: harnesses follow the external client barrier and effects upscaling changes

* fix: client sources return to foreign ownership after the overlay draws

---------

Co-authored-by: Leask Wong <i@leaskh.com>
Co-authored-by: wallentx <william.allentx@gmail.com>
Co-authored-by: Stefan Zijlstra <6730062+stefanz92@users.noreply.github.com>
Co-authored-by: William Allen <wallentx@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: Dersim Abbas <derabb0620@gmail.com>
Co-authored-by: root <root@localhost.localdomain>
Co-authored-by: ASEbrahim <ahmadsmain@gmail.com>
Co-authored-by: The412Banner <the412banner@gmail.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
This commit is contained in:
215 files changed
+19024 -428

No files matched your search

@@ -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<String, Int>()
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<List<PairRow>>(emptyList())
var pairBusy by mutableStateOf<String?>(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
@@ -284,10 +349,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 +388,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 +443,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 +461,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 +469,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 +529,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)
@@ -164,6 +164,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<String?>(null)
private var vkBridgeSafe by mutableStateOf(true)
private var bridgeProtonDxvk by mutableStateOf(false)
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
@@ -582,6 +584,10 @@ class FrontEndActivity : ComponentActivity() {
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)
@@ -1129,7 +1135,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,
@@ -1140,6 +1146,7 @@ class FrontEndActivity : ComponentActivity() {
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),
@@ -1285,9 +1292,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
@@ -1346,6 +1362,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)
@@ -1684,6 +1708,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()
@@ -2137,6 +2164,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) },
@@ -2687,6 +2715,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)
@@ -2764,6 +2794,10 @@ class FrontEndActivity : ComponentActivity() {
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)
@@ -1214,6 +1214,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,
@@ -2476,10 +2478,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))
@@ -2487,14 +2490,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()
@@ -2557,13 +2552,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
@@ -2590,8 +2616,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)
@@ -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;
@@ -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))
@@ -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
@@ -14,6 +14,8 @@ object SteamRedists {
"228988" to ("vcredist2019_dll" to "VC++ 2019"),
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
"228990" to ("d3dx9" to "DirectX (June 2010)"),
// OpenAL 2.0.7.0 (Hotline Miami lists it; without it HotlineGL.exe fails to load, c0000135).
"229020" to ("oalinst_dll" to "OpenAL"),
)
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
@@ -53,7 +53,7 @@ object DeviceInfo {
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
add("GPU", gpu.name)
add("Family", gpu.family.label)
add("Family", gpu.family.label(gpu.name))
add("Model found from", when (gpu.modelSource) {
"kernel" -> "the kernel's GPU name"
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
@@ -146,10 +146,20 @@ object DeviceInfo {
add("Driver mode", SessionPrefs.gpuDriverMode(context))
val turnip = TurnipDriver(context)
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val powerVr = gpu.family == GpuInfo.Family.POWERVR
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val linux = LinuxVulkanDriverManager(context)
val id = SessionPrefs.linuxDriver(context)
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
})
/** Shared by the device card and the session report, which are written in English. */
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
powerVr -> "System PowerVR"
runtime -> "the runtime's own Turnip"
else -> "System Vulkan"
}
}
@@ -75,8 +75,8 @@ object DriverBundle {
val linuxStage = lm.newStagingDir()
val linuxId = try {
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") }
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME))
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && LinuxVulkanDriverManager.isDriverLibrary(it.name) }
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.storedName(library.name)))
val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile }
?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() }
lm.adopt(linuxStage, library?.name, meta, manifest.name)
@@ -86,6 +86,10 @@ object DriverBundle {
}
val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" })
get(context, base)?.takeIf { DriverPairs.isNonAdreno(it.id) }?.let { old ->
Log.i(TAG, "replacing bundle ${old.id} (display ${old.androidId}, runtime ${old.linuxId})")
remove(context, old)
}
val saved = registry(context)
var id = base
var n = 2
@@ -12,6 +12,47 @@ object DriverPairs {
const val DD_TURNIP = "dd-turnip"
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
/** The open non-Adreno drivers (The412Banner/droiddeck-nonadreno-drivers), one pair per driver. */
const val NON_ADRENO = "nad"
const val NAD_RADV_XCLIPSE = "nad:radv-xclipse"
/** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */
const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream"
const val NAD_MALI_JM = "nad:panvk-mali-jm"
const val NAD_MALI_G710 = "nad:panvk-mali-g710"
const val NAD_MALI_G615 = "nad:panvk-mali-g615"
const val NAD_MALI_G720 = "nad:panvk-mali-g720"
/** One PanVK kbase binary for Mali v9-v13; its display half needs Android 15. */
const val NAD_MALI_KBASE = "nad:panvk-mali-kbase"
const val MALI_KBASE_MIN_SDK = 35
/** faux123's PanVK builds for three handhelds: manual choices, never Auto. */
const val NAD_FAUX_RP4PRO = "nad:panvk-faux123-rp4pro"
const val NAD_FAUX_ACE = "nad:panvk-faux123-ace"
const val NAD_FAUX_RG556 = "nad:panvk-faux123-rg556"
/** The one Mali a device-specific build is for, by the number in the GPU's name. */
private val DEVICE_BUILDS = mapOf(NAD_FAUX_RP4PRO to 77, NAD_FAUX_ACE to 610, NAD_FAUX_RG556 to 57)
/** "PanVK-Mali-G720" (the release asset's id) to its pair key, "nad:panvk-mali-g720". */
fun nonAdreno(id: String) = "$NON_ADRENO:" + id.lowercase()
/** True for a non-Adreno pair's key, or a bundle installed from one ("PanVK-Mali-G720"). */
fun isNonAdreno(keyOrBundleId: String?): Boolean = keyOrBundleId != null &&
(keyOrBundleId.startsWith("$NON_ADRENO:") || Regex("""^(?i)(RADV-Xclipse|PanVK-[A-Za-z0-9]+)(-[A-Za-z0-9]+)*$""").matches(keyOrBundleId))
fun nonAdrenoName(key: String): String = describeNonAdreno(key).first
private fun describeNonAdreno(key: String): Pair<String, Set<Family>> = when (key) {
NAD_RADV_XCLIPSE -> "RADV · Samsung Xclipse" to setOf(Family.POWERVR)
NAD_RADV_XCLIPSE_UPSTREAM -> "RADV upstream · Samsung Xclipse" to setOf(Family.POWERVR)
NAD_MALI_JM -> "PanVK · Mali G52-G78" to setOf(Family.MALI_JM)
NAD_MALI_G710 -> "PanVK · Mali-G610/G710" to setOf(Family.MALI_G610_G710)
NAD_MALI_G615 -> "PanVK · Mali-G615" to setOf(Family.MALI_G615)
NAD_MALI_G720 -> "PanVK · Mali-G720" to setOf(Family.MALI_G720)
NAD_FAUX_RP4PRO -> "PanVK faux123 · Retroid Pocket 4 Pro (Mali-G77)" to setOf(Family.MALI_JM)
NAD_FAUX_ACE -> "PanVK faux123 · GameForce Ace (Mali-G610)" to setOf(Family.MALI_G610_G710)
NAD_FAUX_RG556 -> "PanVK faux123 · Anbernic RG556 (Mali-G57)" to setOf(Family.MALI_JM)
NAD_MALI_KBASE -> "PanVK kbase · Mali G57-G925" to
setOf(Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST)
else -> key.removePrefix("$NON_ADRENO:") to emptySet<Family>()
}
class DriverPair(
val key: String,
val name: String,
@@ -24,14 +65,23 @@ object DriverPairs {
val assets: List<TurnipReleases.Asset> get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null)
val version: String
get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") }
fun suits(gpu: GpuInfo) = gpu.family in families ||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
fun suits(gpu: GpuInfo) = when {
// The system-driver family covers PowerVR and Xclipse; RADV is only for the Xclipse.
key == NAD_RADV_XCLIPSE || key == NAD_RADV_XCLIPSE_UPSTREAM ->
gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true)
// One binary for Mali v9-v13, not the older G52/G76 in the Job Manager family.
key == NAD_MALI_KBASE -> gpu.family.mali && GpuInfo.maliKbaseCovered(gpu.name)
key in DEVICE_BUILDS -> gpu.family.mali && GpuInfo.maliNumber(gpu.name) == DEVICE_BUILDS[key]
else -> gpu.family in families ||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
}
}
private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN)
private fun describe(key: String): Pair<String, Set<Family>> = when {
key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO
key.startsWith("$NON_ADRENO:") -> describeNonAdreno(key)
else -> describeFixed(key)
}
@@ -47,7 +97,7 @@ object DriverPairs {
fun from(check: TurnipReleases.Check?): List<DriverPair> {
val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() }
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE)
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE, NON_ADRENO)
return assets.map { it.pair }.distinct()
.sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } }
.map { key ->
@@ -66,7 +116,13 @@ object DriverPairs {
rules: List<AutoPicks.Rule> = AutoPicks.BUILT_IN, bad: Set<String> = emptySet(),
sdk: Int = android.os.Build.VERSION.SDK_INT, blob: Int? = null,
): String? {
if (gpu.family == Family.NOT_ADRENO) return null
when (gpu.family) {
Family.POWERVR -> return NAD_RADV_XCLIPSE.takeIf { gpu.name.contains("Xclipse", ignoreCase = true) }
Family.MALI_OTHER, Family.NOT_ADRENO -> return null
Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST ->
return maliKey(gpu, pairs, sdk)
else -> Unit
}
val keys = AutoPicks.preferences(gpu, rules, sdk, blob)
.ifEmpty { AutoPicks.preferences(gpu, AutoPicks.BUILT_IN, sdk, blob) }
.mapNotNull { if (it == AutoPicks.NEWEST_DD_TURNIP) newestDdTurnip(pairs) else it }
@@ -74,6 +130,20 @@ object DriverPairs {
?: keys.firstOrNull()
}
private fun maliKey(gpu: GpuInfo, pairs: List<DriverPair>, sdk: Int): String? {
val family = when (gpu.family) {
Family.MALI_JM -> NAD_MALI_JM
Family.MALI_G610_G710 -> NAD_MALI_G710
Family.MALI_G615 -> NAD_MALI_G615
Family.MALI_G720 -> NAD_MALI_G720
else -> null
}
val kbase = NAD_MALI_KBASE.takeIf { sdk >= MALI_KBASE_MIN_SDK && GpuInfo.maliKbaseCovered(gpu.name) }
if (pairs.isEmpty()) return kbase ?: family
fun listed(key: String?) = key?.takeIf { k -> pairs.any { it.key == k && it.complete } }
return listed(kbase) ?: listed(family) ?: kbase ?: family
}
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
.maxByOrNull { p ->
@@ -24,8 +24,22 @@ data class GpuInfo(
A7XX("Adreno 7xx"),
A6XX("Adreno 6xx"),
ADRENO_UNKNOWN("Adreno"),
POWERVR("PowerVR"),
/** Mali on Arm's kbase driver, by the open PanVK build each generation needs. */
MALI_JM("Mali (G52-G78)"),
MALI_G610_G710("Mali-G610/G710"),
MALI_G615("Mali-G615"),
MALI_G720("Mali-G720"),
/** Mali-G715/G725/G925: only the one-binary PanVK kbase build covers them (Android 15+). */
MALI_LATEST("Mali-G715/G725/G925"),
/** A Mali no open driver build covers: the Vulkan bridge is its only path. */
MALI_OTHER("Mali"),
NOT_ADRENO("Not an Adreno GPU");
val mali: Boolean get() = name.startsWith("MALI_")
fun label(gpuName: String): String = if (this == POWERVR && gpuName.contains("Xclipse", ignoreCase = true)) "Samsung Xclipse" else label
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
}
@@ -47,10 +61,16 @@ data class GpuInfo(
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
Support.UNTESTED -> if (isA850) "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
else if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
Support.UNTESTED -> when {
family == Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) "Experimental: RADV or the system Xclipse driver"
else "System PowerVR driver: compatibility varies by device"
family == Family.MALI_OTHER -> "Experimental: Mali through the phone's own driver (Venus)"
family.mali -> "Experimental: open Mali driver (test builds)"
isA850 -> "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
family == Family.A7XX_LOW -> "Experimental: its drivers are test builds"
else -> "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
}
Support.UNSUPPORTED -> "Not supported: no compatible graphics backend is available for this GPU"
}
fun supportText(bridge: Boolean): String = when {
@@ -68,8 +88,9 @@ data class GpuInfo(
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> when {
family == Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) R.string.gpuinfo_xclipse else R.string.gpuinfo_powervr
isA850 -> R.string.gpuinfo_a850_experimental
family == Family.A7XX_LOW -> R.string.gpuinfo_experimental
family == Family.A7XX_LOW || family.mali -> R.string.gpuinfo_experimental
else -> R.string.gpuinfo_below_tested
}
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
@@ -91,10 +112,20 @@ data class GpuInfo(
{ VulkanInfo.cachedOrNull()?.get("device") },
{ platformGpuModel },
) else 0 to ""
val family = familyOf(adreno, model)
// Mali, named by the vendor's Vulkan driver ("Mali-G720-Immortalis MC12") or by kbase.
val mali = if (adreno || !File("/dev/mali0").exists()) null else maliName()
val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr(), mali)
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
name = when {
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model"
else -> "Adreno"
},
model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
@@ -136,7 +167,68 @@ data class GpuInfo(
""
}
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
/**
* The Mali's name, "" when nothing names it: the vendor Vulkan driver's own name when this
* process has asked it, kbase's gpuinfo where SELinux lets the app read it (most phones do
* not), else the GPU the chip is known to carry ([MALI_SOCS]).
*/
private fun maliName(): String =
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains("Mali", ignoreCase = true) }
?: FileUtils.readString(File("/sys/class/misc/mali0/device/gpuinfo"))?.trim()?.takeIf { it.contains("Mali", ignoreCase = true) }
?.substringBefore(" ")
?: maliOfSoc(socIds())
?: ""
/** The chip's names as the platform gives them: "mt6989", "MT6989", "gs201". */
private fun socIds(): List<String> = listOfNotNull(
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL else null,
systemProperty("ro.board.platform"), systemProperty("ro.soc.model"), Build.HARDWARE, Build.BOARD,
).filter { it.isNotBlank() }
/** Chips whose Mali is known for certain (MediaTek Dimensity / Helio / Kompanio, Google Tensor). */
private val MALI_SOCS = mapOf(
"mt6993" to "Mali-G1-Ultra", "mt6991" to "Mali-G925", "mt6989" to "Mali-G720", "mt6899" to "Mali-G720", "mt6985" to "Mali-G715",
"mt6983" to "Mali-G710", "mt6897" to "Mali-G615", "mt6878" to "Mali-G615", "mt6895" to "Mali-G610",
"mt6896" to "Mali-G610", "mt6886" to "Mali-G610", "mt6893" to "Mali-G77", "mt6891" to "Mali-G77",
"mt6889" to "Mali-G77", "mt6885" to "Mali-G77", "mt6877" to "Mali-G68", "mt6853" to "Mali-G57",
"mt6833" to "Mali-G57", "mt6835" to "Mali-G57", "mt6789" to "Mali-G57", "mt6785" to "Mali-G76",
"mt6781" to "Mali-G52", "mt6769" to "Mali-G52", "mt8192" to "Mali-G57", "mt8195" to "Mali-G57",
"gs101" to "Mali-G78", "gs201" to "Mali-G710", "zuma" to "Mali-G715", "zumapro" to "Mali-G715",
"s5e8835" to "Mali-G68", "s5e8825" to "Mali-G68",
)
/** The Mali [ids] name a chip of, "Mali-G720 (by chip mt6989)", or null for an unknown chip. */
internal fun maliOfSoc(ids: List<String>): String? = ids.firstNotNullOfOrNull { id ->
MALI_SOCS[id.trim().lowercase()]?.let { "$it (by chip ${id.trim().lowercase()})" }
}
/** The number in a Mali's name: 720 for "Mali-G720-Immortalis MC12". */
fun maliNumber(name: String): Int? =
Regex("""G(\d{2,3})""", RegexOption.IGNORE_CASE).find(name)?.groupValues?.get(1)?.toIntOrNull()
/**
* The Malis the one-binary PanVK kbase build covers (arch v9-v13): G57/G68/G77/G78,
* G610/G710, G615/G715, G720/G725 and G925. Not the older Bifrost G52/G76.
*/
fun maliKbaseCovered(name: String): Boolean =
maliNumber(name) in setOf(57, 68, 77, 78, 610, 710, 615, 715, 720, 725, 925)
/** The PanVK generation a Mali name belongs to; MALI_OTHER when none of the builds covers it. */
internal fun maliFamily(name: String): Family {
val number = maliNumber(name) ?: return Family.MALI_OTHER
return when (number) {
31, 51, 52, 57, 68, 71, 72, 76, 77, 78 -> Family.MALI_JM
610, 710 -> Family.MALI_G610_G710
615 -> Family.MALI_G615
720 -> Family.MALI_G720
715, 725, 925 -> Family.MALI_LATEST
else -> Family.MALI_OTHER
}
}
internal fun familyOf(adreno: Boolean, model: Int, powerVr: Boolean = false, mali: String? = null): Family = when {
!adreno && powerVr -> Family.POWERVR
!adreno && mali != null -> maliFamily(mali)
!adreno -> Family.NOT_ADRENO
model == 0 -> Family.ADRENO_UNKNOWN
model >= 800 -> Family.A8XX
@@ -3,8 +3,12 @@ package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.R;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public final class LinuxVulkanDriver {
private static final String TAG = "LinuxVulkanDriver";
@@ -25,15 +29,36 @@ public final class LinuxVulkanDriver {
return values;
}
public static String resolveIcdPath(Context context, String value) {
if (value == null || value.isEmpty()) return null;
public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return SystemVulkanDriver.isPowerVr()
? context.getString(R.string.gpu_system_powervr) : "Runtime default (built into the runtime)";
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
String icd = m.getIcdPath(value);
if (icd == null) {
Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
return null;
}
Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
if (!m.isInstalled(value)) return value + (SystemVulkanDriver.isPowerVr()
? " (imported, missing)" : " (imported, missing - uses the runtime default)");
String ver = m.getDriverVersion(value);
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
}
public static String resolveIcdPath(Context context, String value) {
boolean powerVr = SystemVulkanDriver.isPowerVr();
return resolveIcdPath(value, powerVr,
() -> SystemVulkanDriver.icdPath(context), id -> {
String icd = new LinuxVulkanDriverManager(context).getIcdPath(id);
if (icd == null) Log.w(TAG, "imported Linux driver \"" + id + "\" is gone"
+ (powerVr ? "" : "; using the runtime's own driver"));
else Log.i(TAG, "Linux session draws with imported driver " + id + " (" + icd + ")");
return icd;
});
}
/** Resolve the selected backend before looking up an imported driver. */
static String resolveIcdPath(String value, boolean powerVr, Supplier<String> systemIcd,
Function<String, String> importedIcd) {
if (SystemVulkanDriver.usesDefault(powerVr, value)) return systemIcd.get();
if (value == null || value.isEmpty()) return null;
String icd = importedIcd.apply(value);
if (powerVr && icd == null) throw new IllegalStateException(
"Selected Linux Vulkan driver \"" + value + "\" is unavailable. Select an installed driver or use Auto.");
return icd;
}
}
@@ -45,7 +45,9 @@ public class LinuxVulkanDriverManager {
public boolean isInstalled(String id) {
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return false;
File dir = getDriverDir(id);
return new File(dir, LIB_NAME).isFile() && new File(dir, ICD_NAME).isFile();
if (!new File(dir, ICD_NAME).isFile()) return false;
for (String name : STORED_NAMES) if (new File(dir, name).isFile()) return true;
return false;
}
public String getIcdPath(String id) {
@@ -107,10 +109,10 @@ public class LinuxVulkanDriverManager {
if (entry.isDirectory()) continue;
String base = new File(entry.getName()).getName();
if (base.isEmpty()) continue;
if (base.startsWith("libvulkan_freedreno") && base.endsWith(".so")) {
if (soName != null) Log.w(TAG, "zip has several libvulkan_freedreno*.so; using the first (" + soName + ")");
if (isDriverLibrary(base)) {
if (soName != null) Log.w(TAG, "zip has several driver libraries; using the first (" + soName + ")");
else {
Files.copy(zis, new File(tmpDir, LIB_NAME).toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy(zis, new File(tmpDir, storedName(base)).toPath(), StandardCopyOption.REPLACE_EXISTING);
soName = base;
}
} else if (base.equals(META_NAME)) {
@@ -142,7 +144,8 @@ public class LinuxVulkanDriverManager {
if (soName == null) {
throw new IllegalArgumentException(context.getString(R.string.lvd_no_library));
}
File so = new File(tmpDir, LIB_NAME);
String stored = storedName(soName);
File so = new File(tmpDir, stored);
if (!isAarch64Elf(so)) {
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName));
}
@@ -167,7 +170,7 @@ public class LinuxVulkanDriverManager {
JSONObject icd = new JSONObject();
icd.put("file_format_version", "1.0.0");
JSONObject icdBody = new JSONObject();
icdBody.put("library_path", new File(dir, LIB_NAME).getAbsolutePath());
icdBody.put("library_path", new File(dir, stored).getAbsolutePath());
icdBody.put("api_version", "1.1.274");
icd.put("ICD", icdBody);
if (!FileUtils.writeString(new File(tmpDir, ICD_NAME), icd.toString(2))) throw new IOException("cannot write icd.json");
@@ -180,6 +183,7 @@ public class LinuxVulkanDriverManager {
meta.put("libc", "glibc");
meta.put("minGlibc", minGlibc);
meta.put("sourceLibraryName", soName);
meta.put("libraryName", stored);
meta.put("importedAt", System.currentTimeMillis());
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
@@ -198,6 +202,24 @@ public class LinuxVulkanDriverManager {
return id;
}
/** The names an installed driver's library is kept under; Turnip keeps {@link #LIB_NAME}. */
private static final String[] STORED_NAMES = {LIB_NAME, "libvulkan_panfrost.so", "libvulkan_radeon.so"};
/**
* The name a driver library is installed under: its own driver's (PanVK, RADV), so the session
* log and the graphics report say which driver it is; a Turnip build keeps {@link #LIB_NAME}.
*/
public static String storedName(String soName) {
if (soName != null && soName.startsWith("libvulkan_panfrost")) return "libvulkan_panfrost.so";
if (soName != null && soName.startsWith("libvulkan_radeon")) return "libvulkan_radeon.so";
return LIB_NAME;
}
public static boolean isDriverLibrary(String base) {
return base.endsWith(".so") && (base.startsWith("libvulkan_freedreno")
|| base.startsWith("libvulkan_panfrost") || base.startsWith("libvulkan_radeon"));
}
static String sanitizeId(String name) {
String s = name.trim().replaceAll("[^A-Za-z0-9._-]+", "_").replaceAll("^[._]+", "");
if (s.length() > 64) s = s.substring(0, 64);
@@ -0,0 +1,261 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.os.Build;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.TarZst;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.TreeSet;
import java.util.UUID;
import java.util.function.Predicate;
import org.json.JSONObject;
/** Isolated glibc-to-Android Vulkan bridge. It does not replace the rootfs's Mesa libraries. */
public final class SystemVulkanDriver {
private static final String ASSET = "hybris/runtime.tzst";
/** Vendor HALs the bridge loads. Samsung Xclipse (Exynos, sgpu) is experimental. */
private static final String[] HALS = {
"/vendor/lib64/hw/vulkan.powervr.so",
"/vendor/lib64/hw/vulkan.samsung.so"
};
private static final String[] REQUIRED = {
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
"lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
"run-proton.py", "wsi/libVkLayer_window_system_integration.so",
"wsi/VkLayer_window_system_integration.json",
"dxvk/x32/d3d8.dll", "dxvk/x32/d3d9.dll", "dxvk/x32/d3d10core.dll",
"dxvk/x32/d3d11.dll", "dxvk/x32/dxgi.dll",
"dxvk/x64/d3d8.dll", "dxvk/x64/d3d9.dll", "dxvk/x64/d3d10core.dll",
"dxvk/x64/d3d11.dll", "dxvk/x64/dxgi.dll"
};
/** Rootfs directory of the Xclipse layer the apk stages (SessionFiles). */
private static final String XCLIPSE_LAYER_DIR = "/usr/local/lib/droiddeck-xclipse";
private SystemVulkanDriver() {}
/**
* The first vendor HAL present, or null. An Exynos with a Mali (Exynos 1280/1380: /dev/mali0)
* may name its HAL vulkan.samsung.so too; that is a Mali, not an Xclipse, and is not taken.
*/
public static String hal() {
for (String path : HALS) {
if (!new File(path).isFile()) continue;
if (path.endsWith("/vulkan.samsung.so") && new File("/dev/mali0").exists()) continue;
return path;
}
return null;
}
/** Samsung's Xclipse (Exynos, sgpu) rather than PowerVR. */
public static boolean isXclipse() {
String hal = hal();
return hal != null && hal.endsWith("/vulkan.samsung.so");
}
/** The system-driver GPU family, for labels. */
public static String gpuName() { return isXclipse() ? "Xclipse" : "PowerVR"; }
/** Whether a system-driver GPU (PowerVR or Xclipse) is present; the name predates Xclipse. */
public static boolean isPowerVr() { return hal() != null; }
/** HAL detection names the GPU; launching also needs the real DRM render node. */
public static boolean isAvailable() { return isPowerVr() && renderNodeAvailable(); }
public static boolean renderNodeAvailable() {
return renderNodePath() != null;
}
/** Select the actual PowerVR node, including devices where another GPU owns renderD128. */
public static String renderNodePath() {
String[] nodes = new File("/dev/dri").list();
if (nodes == null) nodes = new File("/sys/class/drm").list();
return findRenderNode(nodes, SystemVulkanDriver::renderNodeAvailable);
}
static String findRenderNode(String[] nodes, Predicate<String> available) {
TreeSet<String> candidates = new TreeSet<>();
// Android can deny directory listing while allowing direct access. Probe the kernel's
// reserved render range too; directory entries also cover dynamically allocated minors.
for (int minor = 128; minor < 192; minor++) candidates.add("renderD" + minor);
if (nodes != null) for (String node : nodes)
if (node.matches("renderD[0-9]+")) candidates.add(node);
for (String node : candidates) {
String path = "/dev/dri/" + node;
if (available.test(path)) return path;
}
return null;
}
private static boolean renderNodeAvailable(String node) {
try {
if (!renderNodeAvailable(OsConstants.S_ISCHR(Os.stat(node).st_mode),
Os.access(node, OsConstants.R_OK), Os.access(node, OsConstants.W_OK))) return false;
return powerVrDevice(new File("/sys/class/drm/" + new File(node).getName() + "/device"));
} catch (ErrnoException error) {
return false;
}
}
static boolean powerVrDriver(String driver) {
return "pvrsrvkm".equals(driver) || "pvr".equals(driver) || "powervr".equals(driver)
|| "sgpu".equals(driver);
}
static boolean powerVrDevice(File device) {
try {
return powerVrDriver(Files.readSymbolicLink(new File(device, "driver").toPath())
.getFileName().toString());
} catch (IOException error) {
// Some Android policies expose uevent but deny reading the driver symlink.
try (BufferedReader input = Files.newBufferedReader(
new File(device, "uevent").toPath(), StandardCharsets.US_ASCII)) {
String line;
while ((line = input.readLine()) != null)
if (line.startsWith("DRIVER=")) return powerVrDriver(line.substring(7));
} catch (IOException ignored) { }
return false;
}
}
static boolean renderNodeAvailable(boolean characterDevice, boolean readable, boolean writable) {
return characterDevice && readable && writable;
}
public static boolean usesDefault(String choice) {
return usesDefault(isPowerVr(), choice);
}
static boolean usesDefault(boolean powerVr, String choice) {
return powerVr && (choice == null || choice.isEmpty());
}
/** APK-versioned directories stay intact while an older session still has libraries mapped. */
public static synchronized File prepare(Context context) throws IOException {
if (!isPowerVr()) throw new IOException("System PowerVR Vulkan driver is unavailable");
if (!renderNodeAvailable()) throw new IOException(
"System PowerVR requires an identifiable, readable and writable DRM render node");
File target = runtimeDirectory(context);
File base = target.getParentFile();
if (complete(target)) return target;
if (!base.isDirectory() && !base.mkdirs()) throw new IOException("Cannot create system Vulkan directory");
File staged = new File(base, ".stage-" + UUID.randomUUID());
try {
if (!TarZst.extractAsset(context, ASSET, staged)) throw new IOException("Cannot unpack system Vulkan runtime");
for (String name : REQUIRED)
if (!present(staged, name)) throw new IOException("Missing system Vulkan component: " + name);
if (!new File(staged, "run-proton.py").canExecute())
throw new IOException("System Vulkan Proton wrapper is not executable");
JSONObject library = new JSONObject();
library.put("library_path", new File(target, REQUIRED[0]).getPath());
library.put("api_version", "1.3.0");
JSONObject manifest = new JSONObject();
manifest.put("file_format_version", "1.0.0");
manifest.put("ICD", library);
Files.write(new File(staged, "icd.json").toPath(), manifest.toString().getBytes(StandardCharsets.UTF_8));
if (target.exists()) throw new IOException("Incomplete system Vulkan runtime directory: " + target.getName());
if (!staged.renameTo(target)) throw new IOException("Cannot publish system Vulkan runtime");
return target;
} catch (org.json.JSONException error) {
throw new IOException("Cannot write system Vulkan manifest", error);
} finally {
if (staged.exists()) FileUtils.delete(staged);
}
}
/** The current APK's versioned runtime path, without extracting or modifying it. */
public static File runtimeDirectory(Context context) throws IOException {
String version;
try (BufferedReader input = new BufferedReader(new InputStreamReader(
context.getAssets().open("hybris/version.txt"), StandardCharsets.US_ASCII))) {
version = input.readLine();
}
if (version == null || !version.matches("[0-9a-f]{64}")) throw new IOException("Invalid system Vulkan runtime version");
return new File(new File(context.getFilesDir(), "system_vulkan"), version);
}
/** Collect abandoned stages, and obsolete versions once older guests can no longer load them. */
public static synchronized void pruneUnused(Context context, boolean guestsStopped) throws IOException {
pruneUnused(runtimeDirectory(context), guestsStopped);
}
static synchronized void pruneUnused(File current, boolean guestsStopped) {
File base = current.getParentFile();
if (base == null || Files.isSymbolicLink(base.toPath()) || Files.isSymbolicLink(current.toPath())) return;
File[] entries = base.listFiles();
if (entries == null) return;
// Retain the previous good version if publishing the replacement failed.
boolean pruneVersions = guestsStopped && complete(current);
for (File entry : entries) {
if (entry.equals(current)) continue;
String name = entry.getName();
boolean oldVersion = pruneVersions && name.matches("[0-9a-f]{64}");
boolean abandonedStage = name.matches("\\.stage-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
// The prepare monitor excludes any extraction still writing a .stage directory.
if (oldVersion || abandonedStage) FileUtils.delete(entry);
}
}
private static boolean complete(File directory) {
if (!new File(directory, "icd.json").isFile()) return false;
for (String name : REQUIRED) if (!present(directory, name)) return false;
return new File(directory, "run-proton.py").canExecute();
}
private static boolean present(File directory, String name) {
File file = new File(directory, name);
return file.isFile() && file.length() > 0;
}
public static String icdPath(Context context) {
try {
return new File(prepare(context), "icd.json").getPath();
} catch (IOException error) {
throw new IllegalStateException("System Vulkan runtime is unavailable", error);
}
}
public static void addEnvironment(Context context, List<String> environment) {
File directory;
try { directory = prepare(context); }
catch (IOException error) { throw new IllegalStateException("System Vulkan runtime is unavailable", error); }
String node = renderNodePath();
if (node == null) throw new IllegalStateException("System PowerVR render node is unavailable");
environment.add("HYBRIS_ANDROID_SDK_VERSION=" + Build.VERSION.SDK_INT);
environment.add("HYBRIS_VULKAN_HAL=" + hal());
environment.add("HYBRIS_LINKER_DIR=" + new File(directory, "lib/libhybris/linker").getPath());
// Prefer framework dependencies for the system Vulkan loader, including libbase.so.
environment.add("HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64");
boolean xclipse = isXclipse();
// Xclipse gets its own layer (tools/linuxfs/xclipse-layer) in front of everything: it sets
// bionic's environ for the driver's shader compiler, among other driver workarounds. The
// session's own clients need nothing else; games keep the compat layer's BC emulation.
String layers = xclipse ? "VK_LAYER_DROIDDECK_xclipse" : "VK_LAYER_HYBRIS_compat";
environment.add("VK_LAYER_PATH=" + new File(directory, "lib").getPath() + (xclipse ? ":" + XCLIPSE_LAYER_DIR : ""));
environment.add("VK_INSTANCE_LAYERS=" + layers);
// Proton game launches add their WSI layer in front of these (droiddeck-game-env).
environment.add("DROIDDECK_HYBRIS_LAYERS=" + (xclipse ? layers + ":VK_LAYER_HYBRIS_compat" : layers));
if (xclipse) environment.add("DROIDDECK_HYBRIS_LAYER_PATH=" + XCLIPSE_LAYER_DIR);
// DXVK 3 needs 256 bytes of push constants; this driver has 128.
if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
// The Android driver has a render node, but no KMS primary node. SDL presents
// through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
environment.add("BL_GAMESCOPE_BACKEND=sdl");
// The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
environment.add("BL_POWERVR_DRM_HANDLES=1");
environment.add("BL_POWERVR_RENDER_NODE=" + node);
// Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
environment.add("BL_STEAM_GL_PRESENT=1");
// Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
}
}
@@ -263,7 +263,24 @@ public final class TurnipDriver {
}
private String choose() {
SessionPrefs.ensurePowerVrAutoDrivers(context);
String chosen = SessionPrefs.androidDriver(context);
// Mali (Venus): the phone's own driver draws the screen, as Venus replays on it.
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) {
Log.i(TAG, "Mali (Venus): display on the system Vulkan loader");
return null;
}
// A Mali under Auto draws its display on Android's own Vulkan loader, whatever an earlier
// build set: a PanVK Android half fails on Mali gralloc. A manual pick is respected.
if (chosen != null && !chosen.isEmpty() && new File("/dev/mali0").exists()
&& !com.droiddeck.launcher.core.DeviceSupport.INSTANCE.adreno()
&& SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))) {
DriverBundle.Bundle bundle = DriverBundle.INSTANCE.containing(context, chosen, false);
if (bundle != null && DriverPairs.INSTANCE.isNonAdreno(bundle.getId())) {
Log.i(TAG, "Mali under Auto: display on the system Vulkan loader, not " + chosen);
return null;
}
}
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
@@ -289,6 +306,7 @@ public final class TurnipDriver {
if (forced.startsWith("a7")) return DRIVER_A7XX;
if (forced.startsWith("a6")) return DRIVER_A6XX;
}
if (SystemVulkanDriver.isPowerVr()) return null;
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
if (quest != null) return quest;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) {
@@ -296,7 +314,7 @@ public final class TurnipDriver {
return null;
}
GpuInfo gpu = gpuDetector.get();
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO || gpu.getFamily().getMali()) {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
@@ -22,12 +22,17 @@ object TurnipReleases {
private const val KEY_PICKS = "autoPicks"
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String,
val sha256: String = "", val pair: String = "", val bundle: Boolean = false)
val sha256: String = "", val pair: String = "", val bundle: Boolean = false,
val assetId: Long = 0, val updatedAt: String = "") {
/** "2026-10-15" from GitHub's updated_at; empty when the check did not record it. */
val builtOn: String get() = updatedAt.take(10)
}
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false)
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?)
/** [prerelease]: a source whose bundles are all test builds offers them from pre-releases too. */
private class Source(val label: String, val repo: String, val prerelease: Boolean = false, val classify: (name: String, tag: String) -> Kind?)
private val SOURCES = listOf(
Source("Banners-Turnip", "The412Banner/Banners-Turnip") { name, tag ->
@@ -56,8 +61,22 @@ object TurnipReleases {
if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null
Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true)
},
// <Id>-Pair.zip: open drivers for GPUs that are not Adreno (PanVK for Mali, RADV for
// Xclipse), both halves in one zip. One release per driver, replaced in place on each
// rebuild; every one is a test build, published as a pre-release.
Source(NON_ADRENO_LABEL, NON_ADRENO_REPO, prerelease = true) { name, _ ->
val m = Regex("""^(RADV-Xclipse(?:-[A-Za-z0-9]+)*?|PanVK-[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*?)-Pair\.zip$""").find(name) ?: return@Source null
val key = DriverPairs.nonAdreno(m.groupValues[1])
Kind(false, "Android + Linux · " + DriverPairs.nonAdrenoName(key), key, bundle = true)
},
)
private const val NON_ADRENO_REPO = "The412Banner/droiddeck-nonadreno-drivers"
const val NON_ADRENO_LABEL = "Non-Adreno"
private fun sources(): List<Source> =
if (com.droiddeck.launcher.core.DeviceSupport.adreno()) SOURCES.filter { it.repo != NON_ADRENO_REPO } else SOURCES
fun autoPicks(context: Context): List<AutoPicks.Rule> =
AutoPicks.parse(prefs(context).getString(KEY_PICKS, null)) ?: AutoPicks.BUILT_IN
@@ -71,9 +90,13 @@ object TurnipReleases {
val latest = JSONArray()
val failed = ArrayList<String>()
var lastError: Exception? = null
for (src in SOURCES) {
val sources = sources()
for (src in sources) {
try {
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=15"))
// The non-Adreno repo keeps one release per driver plus many component builds (gamescope,
// Venus): its driver pairs fall past the first 15, so it is read in one full page.
val perPage = if (src.repo == NON_ADRENO_REPO) 100 else 15
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=$perPage"))
val seen = HashSet<String>()
var newest: String? = null
for (i in 0 until releases.length()) {
@@ -86,7 +109,7 @@ object TurnipReleases {
val a = list.getJSONObject(j)
val name = a.getString("name")
val kind = src.classify(name, tag) ?: continue
if (kind.bundle && r.optBoolean("prerelease")) continue
if (kind.bundle && r.optBoolean("prerelease") && !src.prerelease) continue
val linux = kind.linux
val label = kind.label
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
@@ -94,7 +117,7 @@ object TurnipReleases {
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
.put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair)
.put("bundle", kind.bundle))
.put("bundle", kind.bundle).put("id", a.optLong("id")).put("updated_at", a.optString("updated_at")))
}
}
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
@@ -103,7 +126,7 @@ object TurnipReleases {
lastError = e
}
}
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
if (failed.size == sources.size) throw lastError ?: IOException("no source answered")
runCatching { get(context, AutoPicks.URL, AutoPicks.URL) }
.onFailure { Log.i(TAG, "auto picks: ${it.message}") }
.getOrNull()?.takeIf { AutoPicks.parse(it) != null }
@@ -154,7 +177,7 @@ object TurnipReleases {
val a = list.getJSONObject(i)
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""),
a.optBoolean("bundle", false)))
a.optBoolean("bundle", false), a.optLong("id"), a.optString("updated_at", "")))
}
val latest = ArrayList<Pair<String, String>>()
val l = json.optJSONArray("latest") ?: JSONArray()
@@ -165,16 +188,53 @@ object TurnipReleases {
return Check(out, latest, failed, json.optLong("checkedAt"))
}
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? {
val d = downloads(context)
if (DriverPairs.isNonAdreno(asset.pair) && asset.sha256.isNotEmpty() &&
!asset.sha256.equals(d.optString(SHA_PREFIX + asset.name, asset.sha256), ignoreCase = true)) return null
return d.optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
}
private const val SHA_PREFIX = "sha256:"
private const val ASSET_ID_PREFIX = "asset:"
private const val UPDATED_PREFIX = "updated:"
/** The id an open non-Adreno pair's asset was installed as, whichever build of it that was. */
fun installedIdAnyBuild(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
/**
* An open non-Adreno pair is rebuilt in place under the same tag: a different digest, asset id
* or upload time than the one installed means a newer build.
*/
fun updateAvailable(context: Context, asset: Asset): Boolean {
if (!DriverPairs.isNonAdreno(asset.pair)) return false
val d = downloads(context)
if (d.optString(asset.name, "").isEmpty()) return false
val sha = d.optString(SHA_PREFIX + asset.name, "")
val id = d.optLong(ASSET_ID_PREFIX + asset.name, 0)
val updated = d.optString(UPDATED_PREFIX + asset.name, "")
return (sha.isNotEmpty() && asset.sha256.isNotEmpty() && !sha.equals(asset.sha256, ignoreCase = true)) ||
(id != 0L && asset.assetId != 0L && id != asset.assetId) ||
(updated.isNotEmpty() && asset.updatedAt.isNotEmpty() && updated != asset.updatedAt)
}
/** When the installed build of [asset] was uploaded, as recorded at download ("" if unknown). */
fun installedBuiltOn(context: Context, asset: Asset): String = downloads(context).optString(UPDATED_PREFIX + asset.name, "").take(10)
fun isDownloaded(context: Context, id: String): Boolean {
val d = downloads(context)
return d.keys().asSequence().any { d.optString(it) == id }
}
fun recordDownload(context: Context, asset: Asset, id: String) {
prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply()
val d = downloads(context).put(asset.name, id)
if (DriverPairs.isNonAdreno(asset.pair)) {
if (asset.sha256.isNotEmpty()) d.put(SHA_PREFIX + asset.name, asset.sha256)
if (asset.assetId != 0L) d.put(ASSET_ID_PREFIX + asset.name, asset.assetId)
if (asset.updatedAt.isNotEmpty()) d.put(UPDATED_PREFIX + asset.name, asset.updatedAt)
}
prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply()
}
fun forget(context: Context, id: String) {
@@ -7,6 +7,7 @@ import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStat;
import android.system.StructUtsname;
import com.droiddeck.launcher.gpu.SystemVulkanDriver;
import com.droiddeck.launcher.session.SessionPrefs;
@@ -191,6 +192,13 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
// The glibc bridge loads the device's existing Android HAL and its dependencies.
// These read-only Android partitions remain subject to the app's normal permissions.
for (String path : new String[]{"/system", "/vendor", "/apex", "/system_ext", "/product", "/odm"})
if (new File(path).isDirectory()) bind(cmd, path);
if (new File("/linkerconfig/ld.config.txt").isFile()) bind(cmd, "/linkerconfig/ld.config.txt");
}
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
@@ -198,6 +206,10 @@ public final class LinuxRuntime {
bind(cmd, "/proc/self/fd/1:/dev/stdout");
bind(cmd, "/proc/self/fd/2:/dev/stderr");
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/fs/selinux");
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, liveDir(context).getPath());
@@ -259,7 +271,11 @@ public final class LinuxRuntime {
if (unreadablePciDevice()) {
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/bus/pci/devices");
}
bindGpuNode(context, cmd);
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
bindPowerVrGpuNode(context, cmd);
} else {
bindGpuNode(context, cmd);
}
bindAdrenoStats(cmd, extraBinds);
bindCpuTemps(cmd, root);
if (extraBinds != null) {
@@ -270,6 +286,24 @@ public final class LinuxRuntime {
return specs;
}
private static void bindPowerVrGpuNode(Context context, List<String> cmd) {
if (new File("/dev/dri").list() != null) return;
String node = SystemVulkanDriver.renderNodePath();
if (node == null) return;
String name = new File(node).getName();
File dri = new File(context.getCacheDir(), "powervr-drm/" + name + "/dri");
try {
if (!dri.isDirectory() && !dri.mkdirs()) return;
new File(dri, name).createNewFile();
} catch (IOException e) {
android.util.Log.w("LinuxRuntime", "Cannot expose the PowerVR render node", e);
return;
}
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, node + ":" + node);
android.util.Log.i("LinuxRuntime", "PowerVR: exposing real " + name + " through a listable directory");
}
private static boolean unreadablePciDevice() {
File[] devices = new File("/sys/bus/pci/devices").listFiles();
if (devices == null) return false;
@@ -279,7 +313,7 @@ public final class LinuxRuntime {
return false;
}
static final String MALI_DEVICE = "/dev/mali0";
public static final String MALI_DEVICE = "/dev/mali0";
static final String[] DRM_RENDER_NODES = {
"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130", "/dev/dri/renderD131",
@@ -287,6 +321,7 @@ public final class LinuxRuntime {
public static String gpuStandIn(Context context) {
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.openDriverActive(context) && new File(MALI_DEVICE).exists()) return MALI_DEVICE;
if (!com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) return null;
return bridgeStandIn(path -> new File(path).exists());
}
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.AppVulkan
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
import com.github.luben.zstd.ZstdOutputStream
@@ -199,9 +200,13 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
require(comp in COMPONENTS)
if (file != null) requireSelectable(context, comp, managed)
val state = loadState(context)
val profiles = state.sub("profiles")
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
@@ -638,11 +643,21 @@ object ComponentsManager {
return PreparedLaunchState(lines.toString(), keep)
}
internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
private fun runtimeManaged(context: Context, comp: String): Boolean =
runtimeManaged(comp, SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)))
private fun requireSelectable(context: Context, comp: String, managed: (String) -> Boolean = { runtimeManaged(context, it) }) {
check(!managed(comp)) { context.getString(R.string.cmgr_powervr_dxvk_managed) }
}
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -668,6 +683,7 @@ object ComponentsManager {
}
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
requireSelectable(context, comp)
val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
@@ -693,7 +709,10 @@ object ComponentsManager {
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
}
fun applyQueued(context: Context): List<String> = synchronized(lock) {
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
fun applyQueued(context: Context): List<String> = applyQueued(context) { runtimeManaged(context, it) }
internal fun applyQueued(context: Context, managed: (String) -> Boolean): List<String> = synchronized(lock) {
val state = loadState(context)
val queued = state.sub("queued")
if (queued.length() == 0) return emptyList()
@@ -705,6 +724,7 @@ object ComponentsManager {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val q = comps.optJSONObject(comp) ?: continue
if (managed(comp)) continue
runCatching {
if (q.optString("kind") == "original") {
val v = q.optString("protonVersion")
@@ -0,0 +1,250 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Build
import android.system.Os
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.gpu.VulkanInfo
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* graphics-report.txt in each session's folder: which graphics path the session drew with and why,
* the GPU and its device nodes, the environment the guest got, and at the end what the compositor
* said about its driver. Written for a non-Adreno test report, where a black screen otherwise comes
* with nothing to read; the Share logs zip takes the whole folder, so it travels with the logs.
* Read-only: nothing here opens a GPU node or changes a setting.
*/
object GraphicsReport {
const val FILE = "graphics-report.txt"
const val GAMES_DIR = "games"
/** One file in games/ past this is cut to its first part at the session's end. */
private const val GAME_FILE_MAX = 20L * 1024 * 1024
/** All of games/ past this loses its oldest launches. */
private const val GAMES_TOTAL_MAX = 120L * 1024 * 1024
/** The guest keys the report repeats: everything that decides which Vulkan driver loads. */
private val ENV_PREFIXES = listOf(
"VK_", "BL_VK", "BL_DRM", "BL_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK",
"DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "BL_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND",
)
/** Per-game graphics logs and the guest's Vulkan summary: on for a non-Adreno GPU, or by Setup's switch. */
fun detailed(context: Context): Boolean = !DeviceSupport.adreno() || SessionPrefs.detailedGraphicsLogs(context)
/** For finish(), which runs from the session's end without a context of its own. */
@Volatile private var appContext: Context? = null
/** Writes the start of the report; never throws. */
fun begin(context: Context, dir: File, guest: List<String>) {
appContext = context.applicationContext
runCatching { File(dir, FILE).writeText(start(context, guest)) }
.onFailure { android.util.Log.w("GraphicsReport", "could not write $FILE", it) }
}
private fun start(context: Context, guest: List<String>): String = buildString {
val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
appendLine("== graphics report, session start $time")
appendLine("build: ${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
appendLine()
val gpu = runCatching { GpuInfo.detect() }.getOrNull()
appendLine("-- path")
appendLine("path: " + path(context))
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
})
val display = SessionPrefs.androidDriver(context)
appendLine("display driver chosen by: " + when {
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
else -> "user (picked on its own)"
})
val linux = SessionPrefs.linuxDriver(context)
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
if (linux.isNotEmpty()) {
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
}
val prefs = context.getSharedPreferences("graphics_report", Context.MODE_PRIVATE)
val previous = prefs.getString("lastDrivers", null)
val now = "display ${SessionPrefs.androidDriver(context).ifEmpty { "(auto)" }}, runtime ${linux.ifEmpty { "(default)" }}, bridge ${DeviceSupport.vkBridge(context)}, venus ${VenusComponent.wanted(context)}"
appendLine("previous session's drivers: " + (previous ?: "(none recorded)") + if (previous != null && previous != now) " << CHANGED" else "")
prefs.edit().putString("lastDrivers", now).apply()
DriverBundle.active(context)?.let { b ->
appendLine("pair: ${b.name} ${b.version} (bundle ${b.id})")
release(context, b.id)?.let { appendLine("pair release: $it") }
}
if (gpu != null) {
val pairs = DriverPairs.from(TurnipReleases.cached(context))
appendLine("auto would pick: " + (DriverPairs.recommendedKey(gpu, pairs) ?: "(no pair: system driver or bridge)"))
}
appendLine("frame generation: " + runCatching { com.droiddeck.launcher.gpu.FrameGen.mode(context).toString() }.getOrDefault("?") +
" (engine=off means it is switched off in Play settings; a driver that fails LSFG's gates logs \"device gates\" below)")
appendLine("mali bridge setting: " + SessionPrefs.vkBridge(context) + ", in use: " + DeviceSupport.vkBridge(context))
val standIn = runCatching { com.droiddeck.launcher.runtime.LinuxRuntime.gpuStandIn(context) }.getOrNull()
appendLine("render node for the guest: " + (standIn?.let { node ->
com.droiddeck.launcher.runtime.LinuxRuntime.deviceNumbers(node)?.let { n -> "/dev/dri/renderD${n.substringAfter(':')} -> $node ($n)" } ?: node
} ?: if (SystemVulkanDriver.isPowerVr()) "the system GPU's own /dev/dri node (#570)" else "none"))
appendLine()
appendLine("-- gpu")
if (gpu != null) {
appendLine("family: ${gpu.family} (${gpu.supportText})")
appendLine("name: ${gpu.name}" + if (gpu.model > 0) ", model ${gpu.model} (${gpu.modelSource})" else "")
}
appendLine("vulkan device (app): " + (VulkanInfo.cachedOrNull()?.get("device") ?: "(not probed)"))
appendLine("system vulkan hal: " + (SystemVulkanDriver.hal() ?: "none"))
read("/sys/class/misc/mali0/device/gpuinfo")?.let { appendLine("mali gpuinfo: $it") }
appendLine("android: ${Build.VERSION.RELEASE} (sdk ${Build.VERSION.SDK_INT}), ${Build.MANUFACTURER} ${Build.MODEL}")
val soc = if (Build.VERSION.SDK_INT >= 31) "${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else Build.HARDWARE
appendLine("soc: $soc, board ${Build.BOARD}, hardware ${Build.HARDWARE}")
appendLine("kernel: " + (System.getProperty("os.version") ?: "?"))
appendLine()
appendLine("-- gpu nodes (from the app; not opened)")
val dri = File("/dev/dri").list()?.sorted()?.map { "/dev/dri/$it" }.orEmpty()
for (path in listOf("/dev/kgsl-3d0", "/dev/mali0") + dri) appendLine(node(path))
if (dri.isEmpty()) appendLine("/dev/dri: " + if (File("/dev/dri").exists()) "not listable" else "absent")
appendLine()
appendLine("-- guest environment (graphics)")
guest.filter { e -> ENV_PREFIXES.any { e.startsWith(it) } }.sorted().forEach { appendLine(it) }
appendLine()
}
/** Which backend this session's Vulkan goes through, as the session decides it. */
private fun path(context: Context): String = when {
DeviceSupport.adreno() -> "Turnip (Adreno, KGSL)"
VenusComponent.wanted(context) -> "Mali (Venus): Mesa Venus over vtest to the phone's own Vulkan driver, with the Mali compatibility layer"
DeviceSupport.vkBridge(context) -> "Mali bridge (#517): the phone's own Vulkan driver through the bridge"
DeviceSupport.openDriverActive(context) -> "open driver pair (PanVK / RADV)"
SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)) && SystemVulkanDriver.isAvailable() ->
"system Vulkan (#570): ${SystemVulkanDriver.gpuName()} driver through libhybris"
SessionPrefs.linuxDriver(context).isNotEmpty() -> "imported runtime driver ${SessionPrefs.linuxDriver(context)}"
else -> "none for this GPU (no Adreno, no system HAL, no pair, bridge off)"
}
/** The release tag and download a pair bundle came from, when the last release check knows it. */
private fun release(context: Context, bundleId: String): String? {
val bundles = TurnipReleases.cached(context)?.assets?.filter { it.bundle }.orEmpty()
val asset = bundles.firstOrNull { it.name.removeSuffix("-Pair.zip") == bundleId }
?: bundles.firstOrNull { bundleId.startsWith(it.name.removeSuffix("-Pair.zip") + "-") }
?: return null
val installed = TurnipReleases.installedBuiltOn(context, asset)
return "${asset.tag} ${asset.url}" +
(if (installed.isNotEmpty()) ", installed build uploaded $installed" else "") +
(if (asset.builtOn.isNotEmpty()) ", listed build uploaded ${asset.builtOn}" else "") +
(if (TurnipReleases.updateAvailable(context, asset)) " << NEWER BUILD AVAILABLE" else "")
}
private fun node(path: String): String {
val f = File(path)
if (!f.exists()) return "$path: absent"
val access = (if (f.canRead()) "r" else "-") + (if (f.canWrite()) "w" else "-")
val rdev = runCatching { Os.stat(path).st_rdev }.getOrNull()
val numbers = rdev?.let { " ${major(it)}:${minor(it)}" }.orEmpty()
val label = runCatching { String(Os.getxattr(path, "security.selinux")).trimEnd('\u0000') }.getOrNull()
return "$path: $access$numbers" + (label?.let { " $it" } ?: "")
}
/** Linux's dev_t split (glibc's gnu_dev_major / gnu_dev_minor). */
internal fun major(dev: Long): Long = ((dev ushr 8) and 0xfff) or ((dev ushr 32) and 0xfffff000L)
internal fun minor(dev: Long): Long = (dev and 0xff) or ((dev ushr 12) and 0xffffff00L)
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
/** The compositor's driver lines from the app's own log. */
private val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
"""graphics driver|display driver|DD_PRESENT_FAULT|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
RegexOption.IGNORE_CASE,
)
/** The session script's driver lines: what it exported, the bridge's self-test, vulkaninfo, gamescope's Vulkan errors. */
private val GUEST = Regex("""== vulkan driver|== vkbridge|== vulkaninfo|vulkan:|panvk|PanVK|radv|primary node|No compatible|DRM format|kbase|AAUDIO|client sink|Xwayland|\(EE\)|glamor|XWAYLAND_NO_GLAMOR""", RegexOption.IGNORE_CASE)
/**
* The end of the report, from the finished folder: the compositor's driver lines out of
* app.log, and games/ held to its size limits. Never throws.
*/
fun finish(dir: File) {
runCatching {
val report = File(dir, FILE)
if (!report.isFile) return
val lines = File(dir, "app.log").takeIf { it.isFile }?.useLines { seq -> seq.filter { COMPOSITOR.containsMatchIn(it) }.take(400).toList() }.orEmpty()
val games = File(dir, GAMES_DIR).listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty()
val guestLines = File(dir, "session.log").takeIf { it.isFile }?.useLines { seq ->
seq.filter { GUEST.containsMatchIn(it) }.take(200).toList()
}.orEmpty()
val fallbackLines = File(dir, "vkbridge-fallback").takeIf { it.isFile }?.readLines()?.map { it.trim() }?.filter { it.isNotEmpty() }
val fellBack = fallbackLines?.firstOrNull()
val fallbackReason = fallbackLines?.getOrNull(1).orEmpty()
runCatching { SessionPrefs.setBridgeFellBack(appContext ?: return@runCatching, fellBack != null, fallbackReason) }
val limits = File(dir, "limits.txt").takeIf { it.isFile }?.readText()?.trim()
val audio = File(dir, "audio.log").takeIf { it.isFile }?.readText().orEmpty()
report.appendText(buildString {
limits?.let { appendLine("open files limit: $it") }
fellBack?.let {
if (fallbackReason == "memory") appendLine("!! MALI BRIDGE FELL BACK: memory sharing = none (no method passed the server's self-test); the session ran on $it")
else appendLine("!! MALI BRIDGE FELL BACK: the self-test failed images or draws; the session ran on $it")
}
com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault().takeIf { it.isNotEmpty() }?.let {
appendLine("!! DISPLAY FAILED: $it")
}
com.droiddeck.launcher.wayland.WaylandCompositor.displayDriver().takeIf { it.isNotEmpty() }?.let {
appendLine("display driver (as loaded): $it")
}
appContext?.let { ctx ->
if (SessionPrefs.venus(ctx)) VenusComponent.hostVulkanTooOld(ctx)?.let {
appendLine("!! VENUS OFF: the phone's driver reports Vulkan $it; gamescope needs 1.2 or newer, so the session did not use Venus")
}
}
if (audio.contains("AAUDIO_ERROR_DISCONNECTED")) {
appendLine("!! SOUND: Android refused the audio output (AAUDIO_ERROR_DISCONNECTED) - rebooting the phone usually fixes this")
}
if (guestLines.any { it.contains("vkbridge", ignoreCase = true) && it.contains("FAIL") }) {
appendLine("!! MALI BRIDGE SELF-TEST FAILED: this GPU's driver did not pass the bridge's checks (see below)")
}
if (guestLines.any { it.contains("MEM_EXEC_INIT") }) {
appendLine("note: kbase refused KBASE_IOCTL_MEM_EXEC_INIT with EPERM. That answer comes from the kbase driver")
appendLine(" itself (proot does not filter ioctls; Android's seccomp would kill or return ENOSYS; SELinux")
appendLine(" would return EACCES), so it is the kernel's policy for this context, not the session's.")
}
appendLine("-- driver lines from the session log (${guestLines.size})")
guestLines.forEach { appendLine(it) }
appendLine()
appendLine("-- compositor and driver lines from app.log (${lines.size})")
lines.forEach { appendLine(it) }
appendLine()
appendLine("-- game launches with detailed logs: ${games.size}")
games.forEach { appendLine(it.name) }
appendLine("== session end " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()))
})
capGames(File(dir, GAMES_DIR))
}.onFailure { android.util.Log.w("GraphicsReport", "could not finish $FILE", it) }
}
/** Cuts each file in [games] to [GAME_FILE_MAX] and drops the oldest launches past [GAMES_TOTAL_MAX]. */
internal fun capGames(games: File, fileMax: Long = GAME_FILE_MAX, totalMax: Long = GAMES_TOTAL_MAX) {
if (!games.isDirectory) return
games.walkTopDown().filter { it.isFile && it.length() > fileMax }.forEach { f ->
runCatching { java.io.RandomAccessFile(f, "rw").use { it.setLength(fileMax) } }
}
val launches = games.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty().toMutableList()
fun size(d: File) = d.walkTopDown().filter { it.isFile }.sumOf { it.length() }
var total = launches.sumOf { size(it) }
while (total > totalMax && launches.size > 1) {
val oldest = launches.removeAt(0)
total -= size(oldest)
FileUtils.delete(oldest)
}
}
}
@@ -11,6 +11,22 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
fun hasOtherProcesses(): Boolean = hasOtherProcesses(
File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(),
) { pid ->
try {
android.system.Os.kill(pid, 0)
true
} catch (error: android.system.ErrnoException) {
error.errno != android.system.OsConstants.ESRCH && error.errno != android.system.OsConstants.EPERM
} catch (error: SecurityException) {
true
}
}
internal fun hasOtherProcesses(pids: List<Int>?, ownPid: Int, signalable: (Int) -> Boolean): Boolean =
pids == null || pids.any { it > 1 && it != ownPid && signalable(it) }
fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
@@ -502,14 +502,20 @@ object SessionArtifacts {
return true
}
/**
* Finishes the folders of sessions whose process died without its teardown. Returns true when
* the newest of them ended because Android killed the app for memory, so the app can say so
* (a game "crashing" on a phone with little free RAM is usually this, not a driver fault).
*/
@Synchronized
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false): Boolean {
val stopWhenSessionStarts = !beforeGuestStart
val parent = LinuxRuntime.logDir(context)
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
}?.sortedWith(SessionPaths.chronological) ?: return
if (abandoned.isEmpty()) return
}?.sortedWith(SessionPaths.chronological) ?: return false
if (abandoned.isEmpty()) return false
var killedForMemory = false
val current = SessionPaths.current()
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -534,8 +540,10 @@ object SessionArtifacts {
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
"session died of a crash, the entry is in there unless the device rebooted.\n" +
(if (newest) exitReasons(context) else "")
)
if (newest && lastExitForMemory(context)) killedForMemory = true
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
(runtimeExpired.exists() || !beforeGuestStart) &&
@@ -593,7 +601,7 @@ object SessionArtifacts {
break
}
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
if (beforeGuestStart) return
if (beforeGuestStart) break
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
val marked = markScrubbed(scrubbed)
if (scrubbed.deferred) break
@@ -604,6 +612,54 @@ object SessionArtifacts {
Log.w(TAG, "could not finish $dir", e)
}
}
// Whoever finishes the folder first (the agent provider starts before the activity) leaves
// the notice for the launcher to show.
if (killedForMemory) SessionPrefs.setMemoryKillNotice(context, true)
return killedForMemory
}
/** Android's newest record for this app's main process says it was killed for memory. */
private fun lastExitForMemory(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < 30) return false
return runCatching {
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return false
am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
.firstOrNull { it.processName == context.packageName }
?.reason == android.app.ApplicationExitInfo.REASON_LOW_MEMORY
}.getOrDefault(false)
}
private fun exitReasons(context: Context): String {
if (android.os.Build.VERSION.SDK_INT < 30) return ""
return runCatching {
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return ""
val reasons = am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
if (reasons.isEmpty()) return ""
val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US)
buildString {
append("\nAndroid's record of how this app's recent processes ended (newest first):\n")
reasons.forEach { r ->
append(" ${fmt.format(java.util.Date(r.timestamp))} ${r.processName} pid ${r.pid}: reason ${reasonName(r.reason)}, " +
"status ${r.status}, importance ${r.importance}, pss ${r.pss / 1024} MB, rss ${r.rss / 1024} MB" +
(r.description?.let { " - $it" } ?: "") + "\n")
}
}
}.getOrDefault("")
}
private fun reasonName(reason: Int): String = when (reason) {
android.app.ApplicationExitInfo.REASON_LOW_MEMORY -> "LOW_MEMORY (killed for memory)"
android.app.ApplicationExitInfo.REASON_SIGNALED -> "SIGNALED"
android.app.ApplicationExitInfo.REASON_CRASH -> "CRASH"
android.app.ApplicationExitInfo.REASON_CRASH_NATIVE -> "CRASH_NATIVE"
android.app.ApplicationExitInfo.REASON_ANR -> "ANR"
android.app.ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> "EXCESSIVE_RESOURCE_USAGE"
android.app.ApplicationExitInfo.REASON_USER_REQUESTED -> "USER_REQUESTED"
android.app.ApplicationExitInfo.REASON_USER_STOPPED -> "USER_STOPPED"
android.app.ApplicationExitInfo.REASON_EXIT_SELF -> "EXIT_SELF"
android.app.ApplicationExitInfo.REASON_DEPENDENCY_DIED -> "DEPENDENCY_DIED"
android.app.ApplicationExitInfo.REASON_OTHER -> "OTHER"
else -> reason.toString()
}
@Synchronized
@@ -45,6 +45,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
@@ -143,6 +144,8 @@ object SessionFiles {
"usr/local/lib/mangoapp/libtraceevent.so.1",
"usr/local/lib/mangoapp/libtracefs.so.1",
).map { it to it }
val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
.map { "usr/local/lib/droiddeck-xclipse/$it" }
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
.map { "usr/local/lib/droiddeck-msitools/$it" } +
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
@@ -172,8 +175,16 @@ object SessionFiles {
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
// The Mali compatibility layer (tools/venus/layer, David Cimo): an implicit Vulkan layer that
// fills in the features DXVK requires and Mali lacks. Idle outside Wine and on GPUs that have them.
// Never staged on an Adreno: an implicit layer is loaded into every Vulkan program there.
val maliCompat = if (com.droiddeck.launcher.core.DeviceSupport.adreno()) emptyList() else listOf(
"usr/local/lib/droiddeck-mali/libVkLayer_droiddeck_mali_compat.so",
"usr/local/share/vulkan/implicit_layer.d/VkLayer_droiddeck_mali_compat.json",
).map { it to it }
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/local/bin/droiddeck-glprobe" to "usr/local/bin/droiddeck-glprobe",
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
@@ -182,7 +193,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import java.io.File
@@ -504,6 +506,17 @@ object SessionPrefs {
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
}
@JvmStatic
fun ensurePowerVrAutoDrivers(context: Context) {
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
}
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
}
fun gpuAutoInstalled(context: Context): Set<String> =
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
@@ -775,8 +788,62 @@ object SessionPrefs {
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
fun hostVulkanApi(context: Context): String = prefs(context).getString("hostVulkanApi", "").orEmpty()
fun setHostVulkanApi(context: Context, api: String) {
if (api != hostVulkanApi(context)) prefs(context).edit().putString("hostVulkanApi", api).apply()
}
fun bridgeFellBack(context: Context): Boolean = prefs(context).getBoolean("bridgeFellBack", false)
fun bridgeFellBackForMemory(context: Context): Boolean = prefs(context).getString("bridgeFallbackReason", "") == "memory"
fun setBridgeFellBack(context: Context, on: Boolean, reason: String = "") {
prefs(context).edit().putBoolean("bridgeFellBack", on).putString("bridgeFallbackReason", if (on) reason else "").apply()
}
fun steamGpuCompositing(context: Context): Boolean {
if (!steamGpuCompositingAllowed()) {
if (prefs(context).getBoolean("steamGpuCompositing", false))
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
return false
}
return prefs(context).getBoolean("steamGpuCompositing", false)
}
fun steamGpuCompositingAllowed(): Boolean =
!com.droiddeck.launcher.core.DeviceSupport.adreno() && !com.droiddeck.launcher.core.DeviceSupport.mali()
fun setSteamGpuCompositing(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamGpuCompositing", on && steamGpuCompositingAllowed()).apply()
}
fun takeMemoryKillNotice(context: Context): Boolean {
val on = prefs(context).getBoolean("memoryKillNotice", false)
if (on) prefs(context).edit().putBoolean("memoryKillNotice", false).apply()
return on
}
fun setMemoryKillNotice(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("memoryKillNotice", on).apply()
}
fun maliFallbackByAuto(context: Context): String = prefs(context).getString("maliFallbackByAuto", "").orEmpty()
fun maliFallbackKnown(context: Context): Boolean = prefs(context).contains("maliFallbackByAuto")
fun setMaliFallbackByAuto(context: Context, route: String) {
prefs(context).edit().putString("maliFallbackByAuto", route).apply()
}
fun setVenus(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("venus", on).apply()
}
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).apply()
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
}
@JvmStatic
@@ -786,6 +853,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
}
@JvmStatic
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
fun setVkBridgeSafe(context: Context, on: Boolean) {
@@ -886,6 +954,13 @@ object SessionPrefs {
}
}
fun detailedGraphicsLogs(context: Context): Boolean =
prefs(context).getBoolean("detailedGraphicsLogs", false)
fun setDetailedGraphicsLogs(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("detailedGraphicsLogs", on).apply()
}
internal fun gameDebugLogsEffective(
context: Context,
logs: Boolean = logsEnabled(context),
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.app.Notification
import android.app.NotificationChannel
@@ -405,6 +406,7 @@ class SessionService : Service() {
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
SessionLogCapture.stopFor(dir)
try {
GraphicsReport.finish(dir)
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
} finally {
SessionPaths.release(this, dir)
@@ -424,6 +426,21 @@ class SessionService : Service() {
return lines
}
/** Whether a kernel release ("6.1.157-android14-11") is older than [major].[minor]; false if unreadable. */
internal fun kernelBefore(release: String, major: Int, minor: Int): Boolean {
val m = Regex("""^(\d+)\.(\d+)""").find(release) ?: return false
val (a, b) = m.destructured
return a.toInt() < major || (a.toInt() == major && b.toInt() < minor)
}
/** Whether the newest finished session's log shows Xwayland itself crashing. */
private fun lastXwaylandCrashed(): Boolean = runCatching {
val last = SessionPaths.sessionFolders(this).filter { it != SessionPaths.current() }.lastOrNull() ?: return false
val log = File(last, "session.log").takeIf { it.isFile } ?: return false
log.useLines { lines -> lines.any { it.contains("(EE) Segmentation fault") } } &&
log.useLines { lines -> lines.any { it.contains("X11 I/O error") || it.contains("Xwayland", ignoreCase = true) } }
}.getOrDefault(false)
private fun tuDebugOverride(): String? = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }?.takeIf { it.isNotEmpty() }
@@ -435,6 +452,13 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionPrefs.ensurePowerVrAutoDrivers(this)
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
if (SessionPrefs.venus(this)) VenusComponent.hostVulkanTooOld(this)?.let {
Log.w(TAG, "venus: off for this session - the phone's driver reports Vulkan $it and gamescope needs 1.2 or newer; the session uses the PanVK pair or the bridge")
}
}
SessionTerminal.clear()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)
try {
@@ -476,7 +500,17 @@ class SessionService : Service() {
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
SessionFiles.stage(this, root, startsSession = true)
try {
if (SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))) {
SystemVulkanDriver.prepare(this)
pruneSystemVulkanRuntime()
}
SessionFiles.stage(this, root, startsSession = true)
} catch (error: Exception) {
Log.e(TAG, "Could not prepare the session graphics runtime", error)
stopSession(-1, gen)
return
}
SessionArtifacts.awaitCollections()
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
@@ -512,18 +546,28 @@ class SessionService : Service() {
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) }
}
addClientEnvironment(guest, steamHere, agentEnvironment)
try {
addClientEnvironment(guest, steamHere, agentEnvironment)
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
stopSession(-1, gen)
return
}
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = startAudio(guest, sessionDir, directAudioPack)
startVkBridge(guest, sessionDir)
if (VenusComponent.wanted(this)) {
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
}
if (steamHere) {
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
encoder.attach(this)
components.add(encoder)
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
}
startVkBridge(guest, sessionDir)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "clocks.log")).let {
it.attach(this)
components.add(it)
@@ -574,6 +618,10 @@ class SessionService : Service() {
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
GraphicsReport.begin(this, sessionDir, guest)
val shellGuest = ArrayList(guest).apply {
add("SHELL=/bin/bash")
add("TERM=xterm-256color")
@@ -673,7 +721,14 @@ class SessionService : Service() {
if (gen == sessionGen) components.clear()
return
}
components.forEach { it.start() }
try {
components.forEach { it.start() }
} catch (e: Exception) {
Log.e(TAG, "Could not start the session components", e)
failSession(gen, "COMPONENT_START_FAILED", e.message ?: "Session component could not be started", -1)
stopSession(-1, gen)
return
}
val line = command.joinToString(" ") {
it.replace("\\", "\\\\").replace(" ", "\\ ")
@@ -816,7 +871,12 @@ class SessionService : Service() {
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
val venus = VenusComponent.wanted(this)
if (venus) {
VenusComponent.guestEnv(this).forEach { guest.add(it) }
} else {
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
}
val linuxDriverId = SessionPrefs.linuxDriver(this)
SessionState.runtimeDriver = linuxDriverId
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
@@ -825,11 +885,39 @@ class SessionService : Service() {
?: SessionPrefs.androidDriver(this),
linuxDriverId,
)
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
val bridge = com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)
if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) {
SystemVulkanDriver.addEnvironment(this, guest)
}
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
}
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("BL_RAISE_NOFILE=1")
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
val kernel = System.getProperty("os.version").orEmpty()
val old = kernelBefore(kernel, 6, 6)
val maliNode = LinuxRuntime.gpuStandIn(this) == LinuxRuntime.MALI_DEVICE
if (old || maliNode) {
guest.add("GAMESCOPE_DISABLE_EXPLICIT_SYNC=1")
Log.i(TAG, "gamescope: explicit sync off (" + (if (old) "kernel $kernel has no SYNCOBJ_EVENTFD" else "Mali stand-in node has no syncobjs") + ")")
}
}
if (!bridge && com.droiddeck.launcher.core.DeviceSupport.openDriverActive(this)) {
if (SessionPrefs.steamGpuCompositing(this)) {
Log.i(TAG, "steam: GPU web compositing (Setup's \"Steam interface: GPU drawing\")")
} else {
guest.add("BL_STEAM_SOFT_COMPOSITING=1")
Log.i(TAG, "steam: software web compositing for the open driver pair (GPU raster kept)")
}
guest.add("BL_OPEN_DRIVER=1")
LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("BL_DRM_STANDIN=$it") }
}
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (SessionPrefs.zinkLazy(this)) {
guest.add("ZINK_DESCRIPTORS=lazy")
guest.add("ZINK_DEBUG=compact")
@@ -878,9 +966,6 @@ class SessionService : Service() {
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
val socket = File(filesDir, "vkbridge/server.sock")
@@ -888,6 +973,10 @@ class SessionService : Service() {
bridge.attach(this)
components.add(bridge)
guest.add("BL_VKBRIDGE=1")
if (SessionPrefs.steamGpuCompositing(this)) guest.add("BL_STEAM_GPU_COMPOSITING=1")
SessionPrefs.linuxDriver(this).takeIf { it.isNotEmpty() }
?.let { runCatching { LinuxVulkanDriver.resolveIcdPath(this, it) }.getOrNull() }
?.let { guest.add("BL_VKBRIDGE_FALLBACK_ICD=$it") }
guest.add("VKBRIDGE_SOCKET=" + socket.path)
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
@@ -897,6 +986,8 @@ class SessionService : Service() {
}
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
val wantsDirectAudio = directAudioPack &&
@@ -1834,6 +1925,12 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
/** Background-only: preserve old runtimes until all earlier guest processes are gone. */
private fun pruneSystemVulkanRuntime() {
runCatching { SystemVulkanDriver.pruneUnused(this, !OrphanReaper.hasOtherProcesses()) }
.onFailure { Log.w(TAG, "could not prune unused system Vulkan runtimes", it) }
}
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
mainHandler.post {
try {
@@ -1973,10 +2070,12 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen, collectEnded)
@@ -0,0 +1,131 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.core.SessionPart
import java.io.File
import java.io.PrintWriter
/**
* Vulkan for the session on a Mali, through Venus (the "Mali (Venus)" route; by David Cimo,
* DavidCimo/droiddeck-mali, ported to this branch).
*
* The guest's processes are glibc and cannot load the vendor's bionic driver. Instead they load
* Mesa's Venus ICD (libvulkan_virtio.so), which serializes every Vulkan call over a unix socket to
* virglrenderer's vtest server. The server runs here, on the Android side, and replays the calls
* on the device's own Vulkan driver. Both ends of the socket are under the app's files directory,
* which the session binds at its own path, so the same path works inside and out.
*/
class VenusComponent(private val logFile: File?) : SessionPart() {
@Volatile private var pid = -1
override fun start() {
val context = app()
stageIcd(context)
val libDir = context.applicationInfo.nativeLibraryDir
val socket = socket(context)
socket.delete()
val env = arrayOf(
"LD_LIBRARY_PATH=$libDir",
// vtest forks a render server per client; this is where its executable is.
"RENDER_SERVER_EXEC_PATH=$libDir/libvirgl_render_server.so",
"TMPDIR=" + context.cacheDir.path,
)
val command = "$libDir/libvirgl_test_server.so --venus --no-virgl --socket-path " + socket.path
val out = logFile?.let { runCatching { PrintWriter(java.io.FileWriter(it, true)) }.getOrNull() }
pid = HostProcess.start(command, env, context.filesDir, { status ->
Log.w(TAG, "vtest server exited: $status")
out?.let { synchronized(it) { it.println("vtest server exited: $status"); it.flush() } }
}, { line ->
Log.i(TAG, line)
out?.let { synchronized(it) { it.println(line); it.flush() } }
})
Log.i(TAG, "vtest server pid $pid on $socket")
}
override fun stop() {
if (pid > 1) Process.killProcess(pid)
pid = -1
}
companion object {
private const val TAG = "Venus"
private const val ASSET = "venus/libvulkan_virtio.so"
private const val DIR = "venus"
private const val LIB = "libvulkan_virtio.so"
private const val ICD = "virtio_icd.json"
/**
* The selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an
* Adreno nor one the system-driver route covers (PowerVR, Xclipse), and the apk carries it.
* It then replaces the Mali bridge and any open driver pair for the session.
*/
@JvmStatic
fun wanted(context: Context): Boolean =
!DeviceSupport.adreno() && !com.droiddeck.launcher.gpu.SystemVulkanDriver.isAvailable() &&
SessionPrefs.venus(context) && available(context) && hostVulkanTooOld(context) == null
/** The phone driver's Vulkan version when it is below 1.2: gamescope skips such a device, so Venus cannot run. */
@JvmStatic
fun hostVulkanTooOld(context: Context): String? {
val api = com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull()?.get("api") ?: SessionPrefs.hostVulkanApi(context)
val parts = api.split('.').mapNotNull { it.trim().toIntOrNull() }
if (parts.size < 2) return null
return api.takeIf { parts[0] < 1 || (parts[0] == 1 && parts[1] < 2) }
}
/** Whether this apk carries the Venus component (tools/venus, venus.tzst). */
@JvmStatic
fun available(context: Context): Boolean = runCatching {
context.assets.list(DIR)?.contains(LIB) == true &&
File(context.applicationInfo.nativeLibraryDir, "libvirgl_test_server.so").isFile
}.getOrDefault(false)
@JvmStatic
fun socket(context: Context): File = File(File(context.filesDir, DIR), "vtest.sock")
/** What the guest needs to find the ICD and the server. */
@JvmStatic
fun guestEnv(context: Context): List<String> {
val dir = File(context.filesDir, DIR)
return listOf(
"VK_ICD_FILENAMES=" + File(dir, ICD).path,
"VN_DEBUG=vtest",
"VTEST_SOCKET_NAME=" + socket(context).path,
// Xwayland has no DRI3 without a DRM node, so swapchains present through shared memory.
"MESA_VK_WSI_DEBUG=sw",
// The Mali compatibility layer in every process but gamescope, not only Wine: Zink
// (Steam's GL, Xwayland's glamor) requires robustness2's nullDescriptor, which the
// layer stands in for. The session script checks it and falls back to llvmpipe.
"DROIDDECK_MALI_COMPAT=1",
"BL_VENUS=1",
// gamescope's composite layout without immutable YCbCr samplers from the start
// (patch 0930): a Mali-G615 refused every composite pipeline with them, and testing
// that through Venus took the render server down.
"GAMESCOPE_NO_YCBCR_SAMPLERS=1",
)
}
/** Copies the ICD out of the APK when it changed, and writes its manifest with an absolute path. */
private fun stageIcd(context: Context) {
val dir = File(context.filesDir, DIR).apply { mkdirs() }
val lib = File(dir, LIB)
// Copied again after every app update: the asset is compressed, so its size is unknown up front.
val installed = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime
if (!lib.isFile || lib.lastModified() < installed) {
val tmp = File(dir, "$LIB.tmp")
context.assets.open(ASSET).use { input -> tmp.outputStream().use { input.copyTo(it) } }
if (!tmp.renameTo(lib)) throw java.io.IOException("could not move the Venus ICD into place")
Log.i(TAG, "staged $lib (${lib.length()} bytes)")
}
if (!FileUtils.writeString(
File(dir, ICD),
"""{"file_format_version":"1.0.1","ICD":{"library_path":"${lib.path}","api_version":"1.4.354"}}""",
)) throw java.io.IOException("could not write the Venus ICD manifest")
}
}
}
@@ -483,17 +483,27 @@ fun ComponentsPage(
)
else -> {
val st = compState(l)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val label = ComponentsManager.LABEL[l] ?: l
if (st == null) InUseBar(false, stringResource(R.string.comp_no_proton), "")
else {
val reappliedAt = view?.reappliedAt?.takeIf { it > 0 }?.let { DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(it * 1000)) }
InUseBar(
queued = st.queued != null,
sentence = (if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
note = if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
onCancel = if (st.queued != null) onCancelQueued else null,
)
Column {
InUseBar(
queued = st.queued != null,
sentence = (if (managedDxvk) stringResource(R.string.comp_in_use, label, stringResource(R.string.gpu_system_powervr)) +
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
else if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null && !managedDxvk) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
note = if (managedDxvk) "" else if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
onCancel = if (st.queued != null) onCancelQueued else null,
maxLines = if (managedDxvk && st.queued != null) 3 else 2,
)
if (managedDxvk) Text(
stringResource(R.string.cmgr_powervr_dxvk_managed),
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp),
)
}
}
}
}
@@ -537,16 +547,17 @@ fun ComponentsPage(
}
else -> {
val label = ComponentsManager.LABEL[l] ?: l
val rows = installedFor(l, view, snapshot)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val rows = installedFor(l, view, snapshot, managedDxvk)
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_stored, label))
val p = view?.proton
rows.forEachIndexed { i, item ->
val key = "row:$l:${item.file ?: item.protonVersion}"
ChoiceLine(
item.name, item.detail, item.selected, item.removable, tag = item.tag,
modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
item.name, item.detail, item.selected, item.removable, tag = item.tag, enabled = !managedDxvk,
modifier = (if (i == 0 && !managedDxvk) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = {
if (item.selected || p == null) return@ChoiceLine
if (managedDxvk || item.selected || p == null) return@ChoiceLine
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
if (item.file != null) ask(key, right, ctx.getString(R.string.comp_swap_title, label), ctx.getString(R.string.comp_swap_body, item.name, p.name, waits), ctx.getString(R.string.comp_swap), false, item.name) {
onSwap(item.file); flyHome(key, l)
@@ -617,14 +628,19 @@ fun ComponentsPage(
}
}
else -> {
SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
SmallButton(
stringResource(R.string.comp_import_wcp), onClick = onImport,
modifier = if (managedDxvk) Modifier.focusRequester(firstRow) else Modifier,
)
val st = compState(l)
val p = view?.proton
val build = p?.let { ComponentsManager.safeName(it.version) }
if (st != null && p != null && st.activeFile != null && view.originals.any { it.comp == l && it.protonVersion == build }) {
val label = ComponentsManager.LABEL[l] ?: l
Box(Modifier.trackRow("restore:$l", rowsAt)) {
FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
if (managedDxvk) SmallButton(stringResource(R.string.comp_restore_original), enabled = false) {}
else FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
ask("restore:$l", false, ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_original_body, p.name, label), ctx.getString(R.string.common_restore), false, ctx.getString(R.string.comp_restore_original)) {
onRestore(build!!); flyHome("restore:$l", l)
}
@@ -770,6 +786,7 @@ fun ComponentsPage(
protonChoice = gameProtonChoice,
packages = snapshot?.packages.orEmpty(),
componentChoices = gameComponents,
systemPowerVr = gpu.systemPowerVr,
componentMenu = gameComponentMenu,
protonMenu = gameProtonMenu,
fexMenu = fexMenu,
@@ -909,11 +926,11 @@ fun ComponentsPage(
}
@Composable
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?): List<InstalledItem> {
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?, runtimeManaged: Boolean = false): List<InstalledItem> {
view ?: return emptyList()
val st = view.components[l] ?: return emptyList()
val build = ComponentsManager.safeName(view.proton.version)
val activeIsOriginal = st.activeFile == null
val activeIsOriginal = !runtimeManaged && st.activeFile == null
return view.originals.filter { it.comp == l }.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
@@ -922,7 +939,7 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
@@ -961,11 +978,12 @@ private fun Stack(
LayerCard(
title = LayerTitle(l),
value = when (l) {
GPU_TAB -> gpuCardValue(gpu, auto)
GPU_TAB -> if (gpu.systemPowerVr) stringResource(R.string.gpu_system_powervr) else gpuCardValue(gpu, auto)
PROTON_TAB -> (view?.proton?.name ?: "") + " ▾"
else -> st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
else -> if (ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
},
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null,
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null && !ComponentsManager.runtimeManaged(l, gpu.systemPowerVr),
selected = l == layer,
landed = landed[l] ?: 0, ring = rings[l] ?: 0,
modifier = Modifier.focusRequester(focus.getValue(l)).onGloballyPositioned { onPlaced(l, it.boundsInRoot()) },
@@ -1032,7 +1050,7 @@ private fun LayerCard(
}
@Composable
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null) {
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null, maxLines: Int = 2) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
@@ -1041,7 +1059,7 @@ private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel:
.border(1.dp, pal.line, RoundedCornerShape(12.dp)).padding(horizontal = 14.dp, vertical = 8.dp),
) {
Box(Modifier.size(8.dp).background(if (queued) QUEUED else pal.good, CircleShape))
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = maxLines, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (onCancel != null) FocusText(stringResource(R.string.common_cancel), pal.signal, onClick = onCancel)
else if (note.isNotEmpty() && !LocalNarrowPane.current) Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
@@ -1076,6 +1094,7 @@ private fun GameComponentOverrides(
protonChoice: ProtonDefault.GameChoice?,
packages: List<ComponentsManager.Package>,
componentChoices: Map<String, String>,
systemPowerVr: Boolean,
componentMenu: String?,
protonMenu: Boolean,
fexMenu: Boolean,
@@ -1167,6 +1186,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "dxvk",
runtimeManaged = ComponentsManager.runtimeManaged("dxvk", systemPowerVr),
packages = packages,
selectedFile = componentChoices["dxvk"],
open = componentMenu == "dxvk",
@@ -1231,13 +1251,16 @@ private fun GamePackageRow(
onMenu: (String?) -> Unit,
onPick: (String, String?) -> Unit,
onRuntimeOptions: (() -> Unit)? = null,
runtimeManaged: Boolean = false,
) {
val choices = packages.filter { it.comp == comp }
val selected = choices.firstOrNull { it.file == selectedFile }
val title = ComponentsManager.LABEL[comp] ?: comp
val enabled = !busy && (!runtimeManaged || selectedFile != null)
SettingsRow(
title,
if (selected == null) {
if (runtimeManaged) stringResource(R.string.cmgr_powervr_dxvk_managed)
else if (selected == null) {
if (proton == null) stringResource(R.string.comp_game_component_general)
else stringResource(R.string.comp_game_component_runtime, proton.name)
} else stringResource(R.string.comp_game_component_override, selected.version),
@@ -1245,18 +1268,18 @@ private fun GamePackageRow(
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Box {
ValueChip(
selected?.version ?: stringResource(R.string.comp_game_use_general),
open,
enabled = !busy,
if (runtimeManaged) stringResource(R.string.gpu_system_powervr) else selected?.version ?: stringResource(R.string.comp_game_use_general),
open && enabled,
enabled = enabled,
modifier = Modifier.widthIn(max = 240.dp),
) { onMenu(if (open) null else comp) }
AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
AnchoredMenu(open && enabled, onDismiss = { onMenu(null) }, title = title) { first ->
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = selected == null,
focusRequester = first,
) { onPick(comp, null); onMenu(null) }
choices.forEach { option ->
if (!runtimeManaged) choices.forEach { option ->
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
onPick(comp, option.file)
onMenu(null)
@@ -1378,13 +1401,13 @@ private fun Tag(text: String) {
@Composable
private fun ChoiceLine(
name: String, detail: String, selected: Boolean, removable: Boolean,
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null,
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null, enabled: Boolean = true,
onSelect: () -> Unit, onDelete: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val hot = rememberHot(src) && enabled
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
@@ -1394,8 +1417,8 @@ private fun ChoiceLine(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
.glideBorder(hot, ROW_SHAPE, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onSelect)
.controllerConfirm(onClick = onSelect)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onSelect)
.controllerConfirm(enabled = enabled, onClick = onSelect)
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).border(2.dp, if (selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
@@ -1405,7 +1428,7 @@ private fun ChoiceLine(
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis,
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
color = if (!enabled) colors.onSurfaceVariant else if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
)
if (tag != null) Tag(tag)
}
@@ -107,6 +107,10 @@ class FrontEndState(
val gameDebugLogsNeedsRestart: Boolean = false,
val vacDiagnostics: Boolean = false,
val agentCommands: Boolean = false,
val graphicsLogs: Boolean = false,
val steamGpuDrawing: Boolean = false,
val bridgeFellBack: Boolean = false,
val bridgeFellBackMemory: Boolean = false,
val clearCachedApps: Boolean = false,
val adbPaired: Boolean = false,
val backgroundAppLimit: Int = -1,
@@ -152,6 +156,8 @@ class FrontEndState(
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val adreno: Boolean = true,
val vkBridge: Boolean = false,
val venus: Boolean = false,
val venusHostVulkan: String? = null,
val vkBridgeSafe: Boolean = true,
val bridgeProtonDxvk: Boolean = false,
val showPhantomGate: Boolean = false,
@@ -211,6 +217,7 @@ class FrontEndActions(
val onRemovePackage: (String) -> Unit,
val onRuntime: () -> Unit,
val onVkBridge: (Boolean) -> Unit = {},
val onVenus: (Boolean) -> Unit = {},
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
@@ -232,6 +239,8 @@ class FrontEndActions(
val onGameDebugLogs: () -> Unit = {},
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
val onGraphicsLogs: () -> Unit = {},
val onSteamGpuDrawing: () -> Unit = {},
val onClearCachedApps: (Boolean) -> Unit = {},
val onMemoryHud: (String) -> Unit = {},
val onBackgroundAppLimit: (Int) -> Unit = {},
@@ -248,6 +248,8 @@ internal fun SetupPanel(
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
when (tab) {
0 -> {
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
CheckRow(
if (gpuOk) CheckState.OK else CheckState.WARN,
@@ -259,19 +261,32 @@ internal fun SetupPanel(
},
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED ->
if (!s.adreno && s.venus && s.venusHostVulkan != null) stringResource(R.string.setup_gpu_venus_host_too_old, gpu.displayName(ctx), s.venusHostVulkan)
else if (!s.adreno && s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpu.displayName(ctx))
else if (!s.adreno && s.vkBridge && s.bridgeFellBack) stringResource(if (s.bridgeFellBackMemory) R.string.setup_gpu_bridge_no_memory_sharing else R.string.setup_gpu_bridge_fell_back, gpu.displayName(ctx))
else stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> if (s.venus && s.venusHostVulkan != null) stringResource(R.string.setup_gpu_venus_host_too_old, gpuName, s.venusHostVulkan)
else if (s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpuName)
else if (s.vkBridge && s.bridgeFellBack) stringResource(if (s.bridgeFellBackMemory) R.string.setup_gpu_bridge_no_memory_sharing else R.string.setup_gpu_bridge_fell_back, gpuName)
else if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
},
divider = divider || (!s.adreno && s.vkBridge),
divider = divider || bridgeModeRow,
action = if (s.adreno) null else { {
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(
stringResource(if (s.venus) R.string.setup_gpu_venus_on else R.string.setup_gpu_venus_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVenus(!s.venus) },
)
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
}
} },
)
if (!s.adreno && s.vkBridge) CheckRow(
if (bridgeModeRow) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_safe),
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on_detail else R.string.setup_bridge_safe_off_detail),
@@ -558,6 +573,8 @@ internal fun SetupPanel(
) { a.onGameDebugLogs() }
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() }
if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
androidx.compose.material3.HorizontalDivider()
@@ -89,6 +89,8 @@ class PairRow(
val complete: Boolean,
val installed: Boolean,
val active: Boolean,
/** A newer build of this installed pair (its build date), or null. */
val update: String? = null,
)
const val GPU_MODE_AUTO = "auto"
@@ -110,6 +112,9 @@ class GpuDriversState(
val supported: Boolean = true,
val unsupported: Boolean = false,
val auto: Boolean = true,
val powerVr: Boolean = false,
/** The selected runtime supplies DXVK for PowerVR game launches. */
val systemPowerVr: Boolean = false,
val pairs: List<PairRow> = emptyList(),
val busy: String? = null,
val percent: Int = -1,
@@ -138,6 +143,7 @@ class GpuDriversState(
class GpuDriversActions(
val onAuto: (Boolean) -> Unit = {},
val onPair: (String) -> Unit = {},
val onPairUpdate: (String) -> Unit = {},
val onRefresh: () -> Unit = {},
val onSelectLinux: (String) -> Unit = {},
val onSelectAndroid: (String) -> Unit = {},
@@ -258,7 +264,7 @@ internal fun GpuDriversBody(
modes.indices.forEach { choice(it, Modifier.weight(1f).fillMaxHeight()) }
}
when (gpu.mode) {
GPU_MODE_AUTO -> AutoBody(gpu)
GPU_MODE_AUTO -> AutoBody(gpu, actions)
GPU_MODE_PAIR -> PairBody(gpu, actions)
else -> MixBody(single, actions, slotFocus, onOpenSlot)
}
@@ -351,14 +357,26 @@ private fun RestartBanner(target: String, canRestart: Boolean, afterLater: Focus
}
@Composable
private fun AutoBody(gpu: GpuDriversState) {
private fun AutoBody(gpu: GpuDriversState, actions: GpuDriversActions) {
val colors = MaterialTheme.colorScheme
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
PanelTitle(
stringResource(if (gpu.activePair != null) R.string.gpu_auto_title else R.string.gpu_auto_builtin_title, gpu.gpuName),
stringResource(R.string.gpu_auto_reason, gpu.gpuFamily),
)
gpu.activePair?.let { p -> PanelRow(p.name, "${p.version} · ${p.detail}", selected = true, onClick = null) }
gpu.activePair?.let { p ->
// An open non-Adreno pair is rebuilt in place while it is tested: offer the newer build.
PanelRow(
p.name, "${p.version} · " + (p.update?.let { stringResource(R.string.proton_update_available, it) } ?: p.detail), selected = true,
trailing = when {
gpu.busy == p.key -> "${gpu.percent.coerceAtLeast(0)}%"
p.update != null -> stringResource(R.string.common_update)
else -> null
},
enabled = gpu.busy == null,
onClick = p.update?.let { { actions.onPairUpdate(p.key) } },
)
}
if (gpu.autoStatus.isNotEmpty()) Text(gpu.autoStatus, fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
@@ -376,15 +394,17 @@ private fun PairBody(gpu: GpuDriversState, actions: GpuDriversActions) {
fontSize = 13.sp, color = colors.onSurfaceVariant,
)
for (p in rows) PanelRow(
p.name, "${p.version} · ${p.detail}", selected = p.active,
p.name, "${p.version} · " + (p.update?.let { stringResource(R.string.proton_update_available, it) } ?: p.detail), selected = p.active,
badge = if (p.recommended) stringResource(R.string.gpu_autos_pick) else null,
trailing = when {
gpu.busy == p.key -> "${gpu.percent.coerceAtLeast(0)}%"
p.update != null -> stringResource(R.string.common_update)
p.installed -> stringResource(R.string.gpu_installed)
else -> stringResource(R.string.common_download)
},
enabled = gpu.busy == null,
onClick = { if (!p.active) actions.onPair(p.key) },
// A rebuilt open non-Adreno pair (same release, newer build) is updated in place.
onClick = { if (p.update != null) actions.onPairUpdate(p.key) else if (!p.active) actions.onPair(p.key) },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (gpu.pairs.any { !it.suits }) FocusText(stringResource(if (showAll) R.string.gpu_hide_other else R.string.gpu_show_other), pal.signal) { showAll = !showAll }
@@ -324,6 +324,7 @@ class DrawerActions(
val onClose: () -> Unit,
val onDismissScreen: (() -> Unit)? = null,
val components: ComponentsManager.Snapshot? = null,
val systemPowerVr: Boolean = false,
val onComponentsRefresh: () -> Unit = {},
val componentCatalog: List<ComponentsManager.CatalogItem> = emptyList(),
val componentCatalogAt: Long = 0,
@@ -1341,7 +1342,11 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
for (component in ComponentsManager.COMPONENTS) {
val value = profile.components.getValue(component)
if (!value.inherited) {
ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
ProfileSummaryRow(
ComponentsManager.LABEL.getValue(component),
if (ComponentsManager.runtimeManaged(component, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else profileValueLabel(value),
)
}
}
if (profile.startWithoutSteam) {
@@ -1450,20 +1455,23 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
label = ComponentsManager.LABEL.getValue(comp),
hint = if (value.inherited) {
hint = if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) else if (value.inherited) {
stringResource(R.string.drawer_component_inherited, value.value)
} else {
null
},
options = options,
selected = gameProfile.componentFiles[comp],
enabled = !managedDxvk || gameProfile.componentFiles[comp] != null,
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
chipModifier = track("cmp-$comp"),
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
)
@@ -1498,7 +1506,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
for (comp in ComponentsManager.COMPONENTS) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (ComponentsManager.runtimeManaged(comp, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else r.components.getValue(comp).inUse,
fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
}
@@ -1526,16 +1538,21 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val build = ComponentsManager.safeName(p.version)
for (comp in ComponentsManager.COMPONENTS) {
val st = view.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (options.isEmpty()) continue
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) +
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
else st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
options, current,
enabled = !managedDxvk,
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
note = if (view.inUseByGame) stringResource(R.string.comp_waits_long) else stringResource(R.string.comp_applies_long),
chipModifier = track("cmp-$comp"),
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
@@ -1648,11 +1665,11 @@ internal fun ComponentDownloadsDrawerGroup(
private fun <T> DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, note: String? = null,
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
chipModifier: Modifier = Modifier, enabled: Boolean = true, valueLabel: String? = null, onPick: (T) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = host.open == key
val open = host.open == key && enabled
Column(
modifier = Modifier.fillMaxWidth()
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
@@ -1660,7 +1677,7 @@ private fun <T> DrawerStackedChoice(
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
ValueChip(valueLabel ?: options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled = enabled, modifier = chipModifier.fillMaxWidth()) {
host.open = if (open) null else key
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
@@ -74,6 +74,12 @@ object AppUpdates {
val updatable: Boolean,
val committedAt: Long = 0L,
val ciBuild: Boolean = BuildConfig.CI_BUILD,
/**
* A build of the non-Adreno test branch (Mali / Xclipse / PowerVR routes). The official
* channels carry the Adreno-only app: installing one over it drops those routes, so none is
* offered. Its updates are published on The412Banner/droiddeck-nonadreno-drivers.
*/
val nonAdrenoTest: Boolean = false,
)
enum class PreviewHistoryKind { CURRENT, BEHIND, RECENT }
@@ -125,6 +131,7 @@ object AppUpdates {
BuildConfig.VERSION_CODE,
releaseSigned,
BuildConfig.COMMIT_TIME,
nonAdrenoTest = BuildConfig.BUILD_LABEL.contains("non-adreno"),
)
fun release(catalog: Catalog, follow: Follow): Release? = when (follow.channel) {
@@ -191,6 +198,7 @@ object AppUpdates {
}
fun installBlock(r: Release, me: Installed = installed()): InstallBlock? = when {
me.nonAdrenoTest -> InstallBlock(R.string.upd_block_non_adreno_test)
r.apk == null -> InstallBlock(R.string.upd_block_no_apk)
r.apk.versionCode < me.versionCode -> InstallBlock(R.string.upd_block_version_code, r.apk.versionCode, me.versionCode)
else -> null
@@ -180,6 +180,28 @@ public final class WaylandCompositor {
public static native int nativeCompositorTid();
private static native String nativeCompositorFault();
private static native String nativeDisplayDriver();
/** Why the compositor cannot present, or "" while it can (or before the library is loaded). */
public static String compositorFault() {
try {
return nativeCompositorFault();
} catch (Throwable t) {
return "";
}
}
/** The driver that answered for the display, as it reports itself; "" when not known yet. */
public static String displayDriver() {
try {
return nativeDisplayDriver();
} catch (Throwable t) {
return "";
}
}
public static native void nativeSetHideShell(boolean hide);
public static native void nativeSetOutputRefreshRate(float hz);