Compare commits

...
Author SHA1 Message Date
The412Banner 14f2004927 Pin the bridge rebuilt with 0015
hybris-runtime-4ed93fb9-dda132a6de-qa (DroidDeck-Components run 40284992208).
2026-10-26 07:22:36 +00:00
The412Banner a132a6de97 Map 32-bit games' GPU memory below 4 GiB on Qualcomm
32-bit DXVK titles failed every vkMapMemory with
VK_ERROR_OUT_OF_HOST_MEMORY: the Qualcomm driver maps above 4 GiB, which
WoW64 Wine rejects unless the device offers VK_EXT_map_memory_placed.

The bridge's placed-memory layer emulates that extension, but its
OPAQUE_FD path made every exportable resource external. This driver
reports OPAQUE_FD export as dedicated-only: external buffers and images
bind only to dedicated exported memory and cannot use the cached
host-visible type, so DXVK's first image bind failed with
VK_ERROR_INVALID_EXTERNAL_HANDLE.

0015-placed-memory-dedicated-export.patch adds a mode for such drivers:
resources stay native and each host-visible allocation that is not
dedicated already is dedicated to a hidden buffer of its size and
exported. The driver binds other resources to that memory, and the
dma-buf mapped at Wine's placed address is coherent with the GPU (probe
on the Pocket FIT: CPU writes through the low mapping, GPU copy, read
back). With a locally built layer, AIO's 32-bit DX11 cube ran 15 s at
142.8 FPS average.

Qualcomm sessions now load the layer with
DROIDDECK_EXPERIMENTAL_PLACED_MEMORY=1; it only acts for devices that
request VK_EXT_map_memory_placed.
2026-10-26 07:18:10 +00:00
The412Banner 3130f7f0c6 Pin the bridge rebuilt with 0014
hybris-runtime-4ed93fb9-dde7fad94b-qa (DroidDeck-Components run 40279099523).
In isolation on the Pocket FIT the driver now reports memory types 3-5 as
device-local only and type 6 as the host-visible coherent cached type that
buffers (0x41) use.
2026-10-26 06:25:02 +00:00
The412Banner e7fad94b70 Hide host flags on covered host-visible memory types in the bridge
On the Pocket FIT's Qualcomm driver every DXVK title crashed right after
creating its device: DXVK 2.4 builds its per-property memory type table
from the first matching type and skips later device-local ones, so for
HOST_VISIBLE|HOST_COHERENT it chose type 4, which no buffer may use
(buffers report 0x41), and its first upload allocation failed
("DxvkMemoryAllocator: Memory allocation failed ... Mem types: 0,6"),
followed by a null read in d3d11.dll. Newer DXVK fixed the table but
requires maintenance5/6, which this driver lacks.

0014-trim-covered-host-memory-types.patch reports host flags only on
host-visible types that no other host-visible type of the same heap
strictly contains. No buffer or image on this driver uses the trimmed
types (optimal images 0x1, linear images and buffers 0x41).
2026-10-26 06:18:43 +00:00
The412Banner 26a9a8ecd6 Pin the bridge rebuilt with 0013
hybris-runtime-4ed93fb9-dd7150e19d-qa (DroidDeck-Components run 40254437721).
Tested alone on the Pocket FIT through PRoot: eglinfo on Zink now reports
OpenGL 3.2 core/compatibility and OpenGL ES 3.1 on the system driver, where
the previous bridge aborted in the Vulkan loader.
2026-10-26 01:33:50 +00:00
The412Banner 7150e19db3 Answer the KHR calibrated-timestamp queries with a HAL's EXT entries
With the Android 14 dispatch fix, Steam still aborted on the Pocket FIT within
two seconds: its update window (GLX) and the browser's glxinfo check both
died. The 0.762.24 driver offers only VK_EXT_calibrated_timestamps; Zink
called vkGetPhysicalDeviceCalibrateableTimeDomainsKHR, the bridge returned
no entry for the KHR name, and the desktop loader's terminator aborted
("ICD associated with VkPhysicalDevice does not support ...KHR").

0013-calibrated-timestamps-khr-alias.patch returns the EXT entry for the
KHR name (same signature and time-domain values) for both the instance and
the device query.
2026-10-26 01:28:57 +00:00
The412Banner 5fa2fc44e7 Pin the rebuilt libhybris bridge with the Android 14 dispatch fix
hybris-runtime-4ed93fb9-dd06dd70c6-qa (DroidDeck-Components run 40252158527):
wallentx's builder at 4ed93fb9 plus hybris-patches/0012. Tested alone on the
Pocket FIT (Android 14, Adreno 750, Qualcomm 0.762.24) through PRoot with the
session's binds: the GPU fill/copy/readback probe now passes where the
previous bridge failed vkCreateInstance with -9. That driver offers no
VK_EXT_external_memory_dma_buf, so games stay on X11 SHM there.
2026-10-26 01:06:27 +00:00
The412Banner 06dd70c67e Accept Android loaders that wrap vkGetPhysicalDeviceProperties in the bridge
On the Pocket FIT (Android 14, Adreno 750, Qualcomm 0.762.24) every Qualcomm
session failed before Steam: the bridge compares one core query between
Android's libvulkan instance and its own HAL, and Android 14's loader wraps
vkGetPhysicalDeviceProperties, so the check rejected the instance
(VK_ERROR_INCOMPATIBLE_DRIVER) although vkGetPhysicalDeviceFeatures resolved
to the same vulkan.adreno.so entry from both sides.

0012-android-loader-wrapped-queries.patch (for taowen/libhybris bc8cb358 with
wallentx's patches 0001-0011) accepts the instance when any of five core
physical-device queries resolves to the HAL's own entry. The bridge is
rebuilt with it on DroidDeck-Components.
2026-10-26 01:01:03 +00:00
The412Banner d404de54c4 Only save the browser's OpenGL check when the driver file can be read
Without a readable driver file every check got the same key, so one saved
answer was reused for any driver. Now nothing is saved or read back in that
case, the cache falls back to ~/.cache when XDG_CACHE_HOME is unset, and the
browser gate test runs with its own cache and covers the saved answer.
2026-10-25 23:46:52 +00:00
The412Banner 409c871a03 Pin the Qualcomm runtime r3 build and its mirrored downloads
qualcomm-runtime-r3-4b8c7f84-qa (DroidDeck-Components run 40244231868) was
built from this branch's patch series: only the Gamescope binary and its
source archive changed; Zink and the WSI layer rebuilt byte-identical to r2.
The libhybris bridge and WSI archives now come from that release, mirrored
unchanged from wallentx/DroidDeck (same SHA-256 and size; the original URLs
stay in mirrored_from).

runtime.json now records the patch series the Gamescope was built from, and
a test fails when a Gamescope patch changes without a rebuild, so the
Qualcomm Gamescope cannot silently fall behind the regular one.
2026-10-25 23:26:12 +00:00
The412Banner 4b8c7f8415 Say in the session log which Performance mode parts reach Qualcomm games
On the X11 SHM path Gamescope's WSI layer is disabled, so its two
Performance mode parts (more swapchain images, the present-check cache)
cannot apply; the unpaced release and Wine's window-check cache still do.
With zero-copy every part applies. The log now says which case a session is in.
2026-10-25 23:17:57 +00:00
The412Banner dfce775514 Save the Qualcomm capability checks between sessions
Every Qualcomm session started the driver through libhybris twice before
Steam: droiddeck-qualcomm-caps (up to 20 s) and glxinfo for the browser's
OpenGL level (up to 15 s). Both answers only change with the driver, so
they are now saved under $XDG_CACHE_HOME/droiddeck and reused while the
driver file (SHA-256), the selected driver, the bridge build, the layers
and the check script are unchanged. Gamescope's linux-dmabuf global is
still checked every session, failed or empty results are never saved, and
the log marks a reused result.
2026-10-25 23:17:41 +00:00
The412Banner 563dff6d75 Pin Gamescope with the Steam client again outside Qualcomm sessions
The Qualcomm port stopped pinning Gamescope to the Steam client's cores for
every session. Outside Qualcomm sessions Gamescope does not copy frames
through X11 SHM, and a user who restricts the client's cores still expects
Gamescope on them, as since #152. Only Qualcomm sessions skip it now.
2026-10-25 23:14:04 +00:00
The412Banner 18735361d7 Keep the Qualcomm-only gamescope patches out of the regular gamescope
0120 (nested swapchain capability fallback) and 0124 (SDL explicit refresh)
only matter for gamescope's SDL backend, which only Qualcomm sessions use.
In tools/gamescope/patches they would go into the next regular gamescope
release for every user. They now live in tools/qualcomm/gamescope-patches;
build_gamescope.py reads both folders in name order, so the Qualcomm build
applies the same series as before.

0121 and 0123 only change anything on PowerVR (vendor 0x1010) and are dropped.
0122 is renamed 0122-dmabuf-import-memory-type: it keeps the part every
vendor uses (the imported DMA-BUF's memory type must also be allowed by
vkGetMemoryFdPropertiesKHR) and drops the PowerVR-only query retry.

The full series still applies to gamescope 8f212644 (3.16.29).
2026-10-25 23:13:44 +00:00
maxjivi05 614f2d4ec1 Stage the Qualcomm runtime before lint reads the assets
(cherry picked from commit b45e761ab1)
2026-10-25 23:09:14 +00:00
maxjivi05 c133a2fbd9 Stage the Qualcomm runtime before the build so lint sees its assets as a dependency
(cherry picked from commit d93021ad52)
2026-10-25 23:09:14 +00:00
maxjivi05 b0b2daa993 Give the glibc shader layer a minimum SDK so NDK 30 headers accept it
(cherry picked from commit 41843dedcb)
2026-10-25 23:09:14 +00:00
maxjivi05 8c5042f035 Download the pinned Qualcomm Gamescope, Zink and WSI builds when they are missing
The builds come from the DroidDeck-Components qualcomm-runtime release, built on ARM64 CI from this branch, so CI and fresh checkouts can stage the Qualcomm runtime without building it locally. The pins now match those Linux builds.

(cherry picked from commit 2ed529842d)
2026-10-25 23:09:14 +00:00
maxjivi05 479490553f Drop the Qualcomm copy of the cursor SHM patch that main already applies
(cherry picked from commit eb83fcb3e3)
2026-10-25 23:09:14 +00:00
K11MCH1 fb1b413fdd Credit wallentx and JeezDisReez in the Qualcomm backend notes
wallentx's libhybris runtime builder and patches, prebuilt bridge and WSI
releases, system-driver staging, android_wlegl buffer receiver and
Gamescope integration patches are what this backend is built on.
JeezDisReez identified turning off the image-bounds rewrite on Adreno as
the fix for the red graphics in DRAGON BALL: Sparking! ZERO.

(cherry picked from commit 09eb999a3a)
2026-10-25 23:09:14 +00:00
K11MCH1 dc78596ffe Keep the Qualcomm patch files LF in checkouts
Windows checkouts with core.autocrlf rewrote them with CRLF, which
changes their pinned hashes and can break git apply in the Linux build
roots.

(cherry picked from commit f6a2fbbe1b573b078cf9123638f32564c19b7a96)
(cherry picked from commit efc9cf49f8)
2026-10-25 23:09:14 +00:00
K11MCH1 9c987fa92e Fall back automatically on Qualcomm drivers with fewer capabilities
Older Adreno drivers such as the 8 Gen 2's 0.676.1 lack
VK_EXT_external_memory_dma_buf, DRM modifiers and calibrated timestamps.
They failed device creation in the WSI layer, failed Proton games on the
zero-copy path, and corrupted the Steam UI under GPU compositing.

- WSI patch 0005 makes the Wayland platform optional per device, so a
  device without its extensions stays usable for X11 swapchains instead
  of failing vkCreateDevice.
- droiddeck-qualcomm-caps checks DMA-BUF export and import, the swapchain
  extensions and Gamescope's linux-dmabuf once per session; Proton games
  use the zero-copy WSI path only when it passes and stay on X11 SHM
  otherwise. The session log records the verdict.
- The Steam browser uses software compositing when Zink offers less than
  OpenGL 4.0, with BL_STEAM_CEF_SOFTWARE as the manual override.

Verified on the Adreno 740 (falls back to SHM and software compositing,
UI correct) and the Adreno 840 (zero-copy and GPU compositing unchanged).

(cherry picked from commit d8d0b10cced1f21a1e9bc7dca00efd89b389adb3)
(cherry picked from commit 00775f0511)
2026-10-25 23:09:14 +00:00
K11MCH1 8abb0b8e8c Turn off the compat layer's image-bounds rewrite in Qualcomm sessions
VK_LAYER_HYBRIS_compat enables a Mali+DXVK workaround by default that
replaces the zero operand of the next OpSelect after any image sample or
fetch. On Adreno it collapses DXVK's comparison selects to constants,
which turned Sparking Zero's main-menu scene red.

(cherry picked from commit 8962b4f6f8c6d46178596dcfb02f98543135744d)
(cherry picked from commit d9c84afa8b)
2026-10-25 23:09:14 +00:00
K11MCH1 3158933489 Present Qualcomm Proton games through Gamescope's zero-copy WSI path
Games in Qualcomm sessions now hand Gamescope LINEAR DMA-BUFs exported by
the driver instead of copying frames through X11 SHM. The ARM WSI layer is
rebuilt with its Wayland backend and the private Gamescope gains a
linux-dmabuf global without a DRM device. BL_QUALCOMM_SHM=1 keeps the
shared-memory path; Turnip sessions are unchanged.

(cherry picked from commit 1bd4c04f193f48bdaf4d4aad374010abaf48765d)
(cherry picked from commit d24b824f25)
2026-10-25 23:09:14 +00:00
K11MCH1 ceb68ade64 Fail the session instead of crashing when the Qualcomm runtime driver is unavailable
(cherry picked from commit 35a4892ea7b6b0fae71b37bf3165ef5ecce3988e)
(cherry picked from commit 6c8dfe6201)
2026-10-25 23:09:14 +00:00
K11MCH1 0a29d4a054 Select automatic Zink descriptors for Qualcomm Steam browser
(cherry picked from commit cbe67da812e75ab3bcc1a684d258559971591038)
(cherry picked from commit a82a954c88)
2026-10-25 23:09:02 +00:00
K11MCH1 2dd426a803 Fix accelerated Qualcomm browser pixmaps without X11 DRI3
(cherry picked from commit b2b033d675a04d201eb07672b57a93ec1983d86f)
(cherry picked from commit 5764373060)
2026-10-25 23:09:02 +00:00
K11MCH1 85a059e76f Enable experimental Steam browser GPU path for Qualcomm drivers
(cherry picked from commit 7ecf2affb647b36d237600b037ba504f4119a313)
(cherry picked from commit 0de60b7ce9)
2026-10-25 23:09:02 +00:00
K11MCH1 2413835dfe Avoid single-core contention in Qualcomm software Steam sessions
(cherry picked from commit d183da807090bbf2793589c605a2f7f9a5fcbdfe)
(cherry picked from commit eb71f719cc)
2026-10-25 23:09:02 +00:00
K11MCH1 472ed4096d Document Qualcomm driver integration and device validation
(cherry picked from commit c32dfb6aee136074b63b1c5083996287b3182299)
(cherry picked from commit 0d4cafb23e)
2026-10-25 23:09:02 +00:00
K11MCH1 cf0ba191da Support older Qualcomm drivers without DMA-BUF or maintenance5
(cherry picked from commit 10939e6bc31e50dcf18ce0fcad4b48d5874b4af6)
(cherry picked from commit 7873adcb23)
2026-10-25 23:09:02 +00:00
K11MCH1 3dfe06b05a Add system and imported Qualcomm drivers as Linux runtime choices
(cherry picked from commit 08fbd19f74561231e6a3adc2069686af111bd0ad)
(cherry picked from commit dd6a86a187)
2026-10-25 23:09:02 +00:00
K11MCH1 6339d00a7a Stage pinned Qualcomm bridge and constant-index shader compatibility
(cherry picked from commit 03ca7778eff0a1216a57c7e7933297c49ea14532)
(cherry picked from commit ca9f416118)
2026-10-25 23:08:48 +00:00
K11MCH1 5f949856b0 Handle nested swapchain capabilities and preserve SDL refresh rates
(cherry picked from commit d38ce896a349a8c9b56c0b40b5fac6dbd14db2b5)
(cherry picked from commit 9924578685)
2026-10-25 23:08:48 +00:00
K11MCH1 0b21822e07 Present Android hardware buffers through the Vulkan compositor
(cherry picked from commit 8a538f9669b0624e823004d896b5e4c7c5bef574)
(cherry picked from commit 8dbf511315)
2026-10-25 23:08:48 +00:00
K11MCH1 0f9fb41961 Require full runtime assets and verify every packaged APK
(cherry picked from commit 75c62ddd92000e31a96d9acbd9599cb07c7041ed)
(cherry picked from commit a2fa72eb74)
2026-10-25 23:07:59 +00:00
K11MCH1 5cf6e503c3 Keep display and runtime driver controls visible in mix mode
(cherry picked from commit 0422eb44193cdcebf7a9f22dfff367b1441dc40e)
(cherry picked from commit c334ef309b)
2026-10-25 23:07:59 +00:00
113 changed files with 6540 additions and 68 deletions

No files matched your search

+2
View File
@@ -10,3 +10,5 @@ tools/mangoapp/mangoapp text eol=lf
app/src/main/assets/desktop-removal/*.json text eol=lf
app/src/main/assets/desktop-removal/*.txt text eol=lf
*.pdf binary
# Patches are applied by the Linux build roots and pinned by hash.
tools/qualcomm/**/*.patch text eol=lf
+1
View File
@@ -1,3 +1,4 @@
# Rules
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
- Always compile APKs with the prepared Linux runtime assets and valid add-on pack checksums so a fresh installation on another phone can install the runtime. Never use `reuseInstalledRuntime` or rely on runtime files already installed on a connected device. Run APK runtime-input verification before sharing a build.
+61 -1
View File
@@ -79,6 +79,12 @@ def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getO
?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: ''
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
if (project.hasProperty('reuseInstalledRuntime')) throw new GradleException('All APKs require prepared Linux runtime packages; runtime reuse is not allowed')
def qualcommRuntime = new groovy.json.JsonSlurper().parse(rootProject.file('tools/qualcomm/runtime.json'))
def qualcommSources = fileTree(rootProject.file('tools/qualcomm')) { include '*.py', '*.c', '*.json', '*.sh', '**/*.patch' }
def qualcommDigest = java.security.MessageDigest.getInstance('SHA-256')
qualcommSources.files.sort { it.name }.each { qualcommDigest.update(it.bytes) }
def qualcommRevision = qualcommDigest.digest().encodeHex().toString()
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' }
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
@@ -128,6 +134,9 @@ android {
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
buildConfigField "String", "QUALCOMM_BRIDGE_SHA256", "\"${qualcommRuntime.sha256}\""
buildConfigField "String", "QUALCOMM_GAMESCOPE_SHA256", "\"${qualcommRuntime.gamescope.member_sha256}\""
buildConfigField "String", "QUALCOMM_FIXES_REVISION", "\"${qualcommRevision}\""
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
@@ -254,6 +263,16 @@ def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
from(rootProject.file('tools/linuxfs/overlay')) {
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
}
from(rootProject.file('tools/linuxfs/desktop')) {
include 'droiddeck-gpu', 'droiddeck-desktop', 'droiddeck-desktop-gpu', 'kwin_wayland_wrapper'
into 'usr/local/bin'
}
from(rootProject.file('tools/linuxfs/desktop/firefox-droiddeck.js')) {
into 'usr/lib/firefox/defaults/pref'
rename { 'droiddeck.js' }
}
from(rootProject.file('tools/linuxfs/desktop/droiddeck-clipboard.desktop')) { into 'etc/xdg/autostart' }
from(rootProject.file('tools/mangoapp/mangoapp')) { into 'usr/local/bin' }
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
}
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
@@ -267,6 +286,35 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
into(runtimeAssetsDir)
}
android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir])
def fetchQualcommBuilds = tasks.register('fetchQualcommBuilds', Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/qualcomm/fetch_runtime.py', '--builds-only',
'--cache', rootProject.file('build/qualcomm-cache').absolutePath
}
def stageQualcommRuntime = tasks.register('stageQualcommRuntime', Exec) {
dependsOn fetchQualcommBuilds
workingDir rootProject.projectDir
inputs.files(qualcommSources)
if (qualcommRuntime.gamescope.build) {
inputs.file(rootProject.file(qualcommRuntime.gamescope.build.binary))
inputs.file(rootProject.file(qualcommRuntime.gamescope.build.source))
}
if (qualcommRuntime.mesa) {
inputs.dir(rootProject.file(qualcommRuntime.mesa.directory))
}
if (qualcommRuntime.wsi?.build) {
inputs.dir(rootProject.file(qualcommRuntime.wsi.build.directory))
}
inputs.property('ndkVersion', android.ndkVersion)
outputs.dir(layout.buildDirectory.dir('qualcommAssets'))
commandLine pythonExecutable, 'tools/qualcomm/fetch_runtime.py',
'--output', layout.buildDirectory.dir('qualcommAssets/qualcomm').get().asFile.absolutePath,
'--cache', rootProject.file('build/qualcomm-cache').absolutePath,
'--ndk', android.ndkDirectory.absolutePath
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('qualcommAssets'))
tasks.named('preBuild').configure { dependsOn(stageQualcommRuntime) }
tasks.matching { it.name.toLowerCase(Locale.ROOT).contains('lint') }.configureEach { dependsOn(stageQualcommRuntime) }
if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets'))
if (uvcDir) {
def stageUvcNotices = tasks.register('stageUvcNotices', Copy) {
@@ -284,7 +332,19 @@ def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'
}
tasks.configureEach { task ->
if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
if (task.name == 'packageRelease') {
task.dependsOn(verifyRuntimeInputs)
}
if (task.name == 'packageDebug') task.dependsOn(verifyRuntimeInputs)
}
['Debug', 'Release'].each { variant ->
def verifyApk = tasks.register("verify${variant}PackagedRuntime", Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'apk',
layout.buildDirectory.file("outputs/apk/${variant.toLowerCase()}/app-${variant.toLowerCase()}.apk").get().asFile.absolutePath
}
tasks.matching { it.name == "assemble${variant}" }.configureEach { finalizedBy(verifyApk) }
}
def rustCrateDir = layout.projectDirectory.dir('src/main/rust/stores')
+2
View File
@@ -75,11 +75,13 @@ Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz
VkPhysicalDeviceDriverProperties driver = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES };
VkPhysicalDeviceProperties2 p2 = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &driver };
vkGetPhysicalDeviceProperties2(device, &p2);
LINE("driver_id=%u\n", driver.driverID);
LINE("driver_name=%s\n", driver.driverName);
LINE("driver_info=%s\n", driver.driverInfo);
LINE("conformance=%u.%u.%u.%u\n", driver.conformanceVersion.major, driver.conformanceVersion.minor,
driver.conformanceVersion.subminor, driver.conformanceVersion.patch);
}
LINE("driver_version_raw=%u\n", p.driverVersion);
LINE("extension_count=%u\n", extCount);
for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) {
int has = 0;
@@ -10,6 +10,8 @@ add_library(droiddeckwayland SHARED
src/waylandcomp_jni.c
src/gpu_clock_pin.c
src/droiddeck_ext.c
src/wl_android_buffer.c
generated/wayland-android-protocol.c
src/wl_dmabuf.c
src/wl_clipboard.c
src/wl_text_input.c
@@ -0,0 +1,104 @@
/* Generated by wayland-scanner 1.26.0 */
/*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface android_wlegl_handle_interface;
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
extern const struct wl_interface wl_buffer_interface;
static const struct wl_interface *android_types[] = {
NULL,
NULL,
&android_wlegl_handle_interface,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
NULL,
NULL,
NULL,
&android_wlegl_handle_interface,
&android_wlegl_server_buffer_handle_interface,
NULL,
NULL,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
};
static const struct wl_message android_wlegl_requests[] = {
{ "create_handle", "nia", android_types + 2 },
{ "create_buffer", "niiiiio", android_types + 5 },
{ "get_server_buffer_handle", "2niiii", android_types + 12 },
};
WL_PRIVATE const struct wl_interface android_wlegl_interface = {
"android_wlegl", 3,
3, android_wlegl_requests,
0, NULL,
};
static const struct wl_message android_wlegl_handle_requests[] = {
{ "add_fd", "h", android_types + 0 },
{ "destroy", "", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
"android_wlegl_handle", 1,
2, android_wlegl_handle_requests,
0, NULL,
};
static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
{ "buffer_fd", "h", android_types + 0 },
{ "buffer_ints", "a", android_types + 0 },
{ "buffer", "nii", android_types + 17 },
{ "linear_layout", "3uu", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
"android_wlegl_server_buffer_handle", 3,
0, NULL,
4, android_wlegl_server_buffer_handle_events,
};
@@ -0,0 +1,341 @@
/* Generated by wayland-scanner 1.26.0 */
#ifndef ANDROID_SERVER_PROTOCOL_H
#define ANDROID_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wl_client;
struct wl_resource;
/**
* @page page_android The android protocol
* @section page_ifaces_android Interfaces
* - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
* - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
* - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
* @section page_copyright_android Copyright
* <pre>
*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
* </pre>
*/
struct android_wlegl;
struct android_wlegl_handle;
struct android_wlegl_server_buffer_handle;
struct wl_buffer;
#ifndef ANDROID_WLEGL_INTERFACE
#define ANDROID_WLEGL_INTERFACE
/**
* @page page_iface_android_wlegl android_wlegl
* @section page_iface_android_wlegl_desc Description
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
* @section page_iface_android_wlegl_api API
* See @ref iface_android_wlegl.
*/
/**
* @defgroup iface_android_wlegl The android_wlegl interface
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
*/
extern const struct wl_interface android_wlegl_interface;
#endif
#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
#define ANDROID_WLEGL_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_handle android_wlegl_handle
* @section page_iface_android_wlegl_handle_desc Description
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
* @section page_iface_android_wlegl_handle_api API
* See @ref iface_android_wlegl_handle.
*/
/**
* @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
*/
extern const struct wl_interface android_wlegl_handle_interface;
#endif
#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
* @section page_iface_android_wlegl_server_buffer_handle_desc Description
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
* @section page_iface_android_wlegl_server_buffer_handle_api API
* See @ref iface_android_wlegl_server_buffer_handle.
*/
/**
* @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
*/
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
#endif
#ifndef ANDROID_WLEGL_ERROR_ENUM
#define ANDROID_WLEGL_ERROR_ENUM
enum android_wlegl_error {
ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
};
#endif /* ANDROID_WLEGL_ERROR_ENUM */
#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl
* Validate a android_wlegl error value.
*
* @return true on success, false on error.
* @ref android_wlegl_error
*/
static inline bool
android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_ERROR_BAD_HANDLE:
return version >= 1;
case ANDROID_WLEGL_ERROR_BAD_VALUE:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl
* @struct android_wlegl_interface
*/
struct android_wlegl_interface {
/**
* Create an Android native_handle_t object
*
* This creator method initialises the native_handle_t object
* with everything except the file descriptors, which have to be
* submitted separately.
* @param ints an array of int32_t
*/
void (*create_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t num_fds,
struct wl_array *ints);
/**
* Create a wl_buffer from the native handle
*
* Pass the Android native_handle_t to the server and attach it
* to the new wl_buffer object.
*
* The android_wlegl_handle object must be destroyed immediately
* after this request.
*/
void (*create_buffer)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t stride,
int32_t format,
int32_t usage,
struct wl_resource *native_handle);
/**
* @since 2
*/
void (*get_server_buffer_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t format,
int32_t usage);
};
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
enum android_wlegl_handle_error {
ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
};
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl_handle
* Validate a android_wlegl_handle error value.
*
* @return true on success, false on error.
* @ref android_wlegl_handle_error
*/
static inline bool
android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl_handle
* @struct android_wlegl_handle_interface
*/
struct android_wlegl_handle_interface {
/**
*/
void (*add_fd)(struct wl_client *client,
struct wl_resource *resource,
int32_t fd);
/**
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
};
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_fd event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_ints event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an linear_layout event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
}
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="android">
<copyright>
Copyright © 2012 Collabora, Ltd.
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<interface name="android_wlegl" version="3">
<description summary="Android EGL graphics buffer support">
Interface used in the Android wrapper libEGL to share
graphics buffers between the server and the client.
</description>
<enum name="error">
<entry name="bad_handle" value="0" />
<entry name="bad_value" value="1" />
</enum>
<request name="create_handle">
<description summary="Create an Android native_handle_t object">
This creator method initialises the native_handle_t object
with everything except the file descriptors, which have to be
submitted separately.
</description>
<arg name="id" type="new_id" interface="android_wlegl_handle" />
<arg name="num_fds" type="int" />
<arg name="ints" type="array" summary="an array of int32_t" />
</request>
<request name="create_buffer">
<description summary="Create a wl_buffer from the native handle">
Pass the Android native_handle_t to the server and attach it
to the new wl_buffer object.
The android_wlegl_handle object must be destroyed immediately
after this request.
</description>
<arg name="id" type="new_id" interface="wl_buffer" />
<arg name="width" type="int" />
<arg name="height" type="int" />
<arg name="stride" type="int" />
<arg name="format" type="int" />
<arg name="usage" type="int" />
<arg name="native_handle" type="object" interface="android_wlegl_handle" />
</request>
<request name="get_server_buffer_handle" since="2">
<arg name="id" type="new_id" interface="android_wlegl_server_buffer_handle"/>
<arg name="width" type="int"/>
<arg name="height" type="int"/>
<arg name="format" type="int"/>
<arg name="usage" type="int"/>
</request>
</interface>
<interface name="android_wlegl_handle" version="1">
<description summary="An Android native_handle_t object">
The Android native_handle_t is a semi-opaque object, that
contains an EGL implementation specific number of int32
values and file descriptors.
We cannot send a variable size array of file descriptors
over the Wayland protocol, so we send them one by one.
</description>
<enum name="error">
<entry name="too_many_fds" value="0" />
</enum>
<request name="add_fd">
<arg name="fd" type="fd" />
</request>
<request name="destroy" type="destructor" />
</interface>
<interface name="android_wlegl_server_buffer_handle" version="3">
<description summary="a server allocated buffer">
On creation a server_side_buffer object will immediately send
the "buffer_fd" and "buffer_ints" events needed by the client to
reference the gralloc buffer, followed by the "buffer" event carrying
the wl_buffer object.
</description>
<event name="buffer_fd">
<arg name="fd" type="fd"/>
</event>
<event name="buffer_ints">
<arg name="ints" type="array"/>
</event>
<event name="buffer">
<description summary="the wl_buffer">
This event will be sent after the ints and all the fds have been sent
</description>
<arg name="buffer" type="new_id" interface="wl_buffer"/>
<arg name="format" type="int"/>
<arg name="stride" type="int"/>
</event>
<event name="linear_layout" since="3">
<description summary="verified single-plane linear allocation">
Optional metadata sent before the buffer event. The first buffer_fd
contains one uncompressed 32-bit RGB plane at byte offset zero.
drm_format is its DRM FourCC and stride is its row pitch in bytes.
The server has verified the layout and allocation bounds using
Android mapper metadata, not inferred them from opaque handle ints.
Absence of this event means the layout is unspecified.
</description>
<arg name="drm_format" type="uint"/>
<arg name="stride" type="uint"/>
</event>
</interface>
</protocol>
@@ -3390,7 +3390,9 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
if (vkp_dmabuf_supported())
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
droiddeck_android_wlegl_init(display);
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
@@ -61,3 +61,6 @@ extern volatile int g_no_render_node;
COMPOSITOR_INTERNAL extern dev_t g_main_device;
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
/* ---- wl_android_buffer.c */
COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
@@ -0,0 +1,47 @@
#ifndef VK_EXTERNAL_IMAGE_SYNC_H
#define VK_EXTERNAL_IMAGE_SYNC_H
#include <vulkan/vulkan.h>
struct vkp_external_client_barrier_pair {
VkImageMemoryBarrier acquire;
VkImageMemoryBarrier release;
};
static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
return dmabuf && !blit_dst;
}
/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
* FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
* acquire/release lifecycle and must never take this source-image path. */
static inline int vkp_external_client_barrier_pair(
VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
struct vkp_external_client_barrier_pair *pair) {
if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
pair->acquire = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = queue_family,
.image = image,
.subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
};
pair->release = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = queue_family,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.image = image,
.subresourceRange = range,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
};
return 1;
}
#endif
+161 -39
View File
@@ -1,6 +1,7 @@
#define _POSIX_C_SOURCE 200809L
#include "vk_present.h"
#include "vk_loader.h"
#include "vk_external_image_sync.h"
#include "sc_layer.h"
#include "effects_chain.h"
#include "cardboard.h"
@@ -37,6 +38,7 @@ struct vkp_image {
int in_general;
VkFormat fmt;
int sampled;
AHardwareBuffer *android_buffer;
};
static ANativeWindow *g_window;
@@ -47,6 +49,7 @@ static VkInstance g_inst;
static VkPhysicalDevice g_pd;
static VkDevice g_dev;
static VkQueue g_queue;
static int g_dmabuf_supported;
static uint32_t g_qfam;
static VkCommandPool g_pool;
#define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS)
@@ -463,16 +466,23 @@ static int dev_init(void) {
static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
const char *dev_exts[10] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
uint32_t n_dev_exts = 1;
uint32_t ne = 0;
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
if (!exts) { g_dev_state = -1; return -1; }
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player never needs. */
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player and
* android_wlegl clients never need. */
g_dmabuf_supported = 1;
for (unsigned i = 0; i < 4; i++) {
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
if (has_ext(exts, ne, import_exts[i])) {
dev_exts[n_dev_exts++] = import_exts[i];
} else {
LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
if (i < 3) g_dmabuf_supported = 0;
}
}
int want_hdr_md = 0;
if (droiddeck_color_requested()) {
@@ -481,7 +491,8 @@ static int dev_init(void) {
}
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
/* The cloud player's decoded frames arrive as AHardwareBuffers (vkp_image_from_ahb). */
/* The cloud player's decoded frames (vkp_image_from_ahb) and android_wlegl clients
* (vkp_image_from_android_buffer) arrive as AHardwareBuffers. */
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
if (g_ahb_import) {
@@ -917,12 +928,107 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
}
int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
/* Return client sources to FOREIGN after their final read. The consuming paths
* wait for our fence before Wayland can release an ordinary dma-buf or an
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
* these image-layout and ownership transfers. */
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
struct vkp_external_client_barrier_pair pair;
if (!img || !vkp_external_client_barrier_pair(
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
return;
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
}
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
for (int i = 0; i < count; i++) {
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
if (!seen) release_external_client_image(cmd, draws[i].img);
}
}
int vkp_image_is_dmabuf(const struct vkp_image *img) {
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
}
int vkp_android_buffer_supported(void) {
return dev_init() == 0 && g_ahb_import && g_vk.GetAndroidHardwareBufferPropertiesANDROID != NULL;
}
int vkp_dmabuf_supported(void) {
return dev_init() == 0 && g_dmabuf_supported;
}
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
if (!buffer || !vkp_android_buffer_supported()) return NULL;
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(buffer, &desc);
if (!desc.width || !desc.height || desc.layers != 1 ||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID props = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
VkResult result = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, buffer, &props);
if (result != VK_SUCCESS ||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
!props.memoryTypeBits ||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
vk_result_name(result), format.format);
return NULL;
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)desc.width; img->h = (int)desc.height;
img->fmt = format.format; img->dmabuf = 1;
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
img->sampled = (format.formatFeatures & sampled) == sampled;
VkExternalMemoryImageCreateInfo external = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo create = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
if (result != VK_SUCCESS) goto fail;
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
uint32_t memory_type = 0;
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
VkImportAndroidHardwareBufferInfoANDROID import = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
VkMemoryDedicatedAllocateInfo dedicated = {
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &import, .image = img->image};
VkMemoryAllocateInfo allocate = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
if (result != VK_SUCCESS) goto fail;
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
if (result != VK_SUCCESS) goto fail;
AHardwareBuffer_acquire(buffer);
img->android_buffer = buffer;
return img;
fail:
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
vkp_image_destroy(img);
return NULL;
}
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
uint32_t stride, uint32_t offset, int as_blit_dst) {
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
if (dev_init() != 0) return NULL;
if (dev_init() != 0 || !g_dmabuf_supported) return NULL;
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
@@ -1125,6 +1231,7 @@ void vkp_image_destroy(struct vkp_image *img) {
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
}
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img);
}
@@ -1169,11 +1276,14 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
const struct vkp_image *im = d->img;
const int external_client = vkp_image_is_dmabuf(im);
if (d->blend && im->sampled &&
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
target, target_fmt, target_w, target_h,
blit) == 0)
return;
g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
g_vk.CmdBlitImage(cmd, im->image,
external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
}
@@ -1612,13 +1722,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
if (im->dmabuf) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1675,6 +1783,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
drawn++;
}
release_external_client_draws(cmd, draws, n);
int ngen = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img;
@@ -1877,7 +1986,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -1890,17 +1999,21 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
if (!src->dmabuf) {
if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
@@ -1914,8 +2027,9 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image,
src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
@@ -1950,7 +2064,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb;
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
g_dev_state == -2 || dev_init() != 0)
return -1;
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
@@ -1991,11 +2105,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
@@ -2013,15 +2131,20 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}};
uint32_t done_count = 1;
if (!src_external) {
done[done_count++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
}
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 2, done);
0, 0, NULL, 0, NULL, done_count, done);
release_external_client_image(cmd, src);
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
@@ -2093,13 +2216,11 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
if (im->dmabuf) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -2138,6 +2259,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
}
release_external_client_draws(cmd, draws, n);
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
g_pass.rw = scene_w; g_pass.rh = scene_h;
g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h,
@@ -2,6 +2,7 @@
#define VK_PRESENT_H
#include <stdint.h>
#include <android/native_window.h>
#include <android/hardware_buffer.h>
void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir);
@@ -20,6 +21,10 @@ void vkp_output_size(int *w, int *h);
struct vkp_image;
int vkp_android_buffer_supported(void);
int vkp_dmabuf_supported(void);
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
#define VKP_MOD_LINEAR 0x0000000000000000ULL
#define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL
#define VKP_MOD_INVALID 0x00ffffffffffffffULL
@@ -0,0 +1,216 @@
/* android_wlegl buffer import for the existing libhybris Wayland WSI.
* Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
* Native handles are cloned through Android; opaque vendor integers are never interpreted. */
#include "compositor_internal.h"
#include "droiddeck_ext.h"
#include "wayland-android-server-protocol.h"
#include <android/hardware_buffer.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Stable native_handle_t ABI, unavailable in the public NDK. */
struct android_native_handle {
int version, num_fds, num_ints;
int data[];
};
struct wire_handle {
struct android_native_handle *handle;
int received;
};
enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
* vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
* Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
enum { CREATE_FROM_HANDLE_CLONE = 3 };
static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
int32_t, AHardwareBuffer **);
static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
(format == 1 || format == 2 || format == 5);
}
static void handle_resource_destroy(struct wl_resource *resource) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (!wire) return;
for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
free(wire->handle);
free(wire);
}
static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (wire->received >= wire->handle->num_fds) {
close(fd);
wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
"more native handle descriptors than declared");
return;
}
wire->handle->data[wire->received++] = fd;
}
static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
wl_resource_destroy(resource);
}
static const struct android_wlegl_handle_interface handle_impl = {
.add_fd = handle_add_fd, .destroy = handle_destroy,
};
static void create_handle(struct wl_client *client, struct wl_resource *resource,
uint32_t id, int32_t fds, struct wl_array *ints) {
if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
return;
}
struct wire_handle *wire = calloc(1, sizeof(*wire));
if (!wire) { wl_client_post_no_memory(client); return; }
wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
wire->handle->version = sizeof(*wire->handle);
wire->handle->num_fds = fds;
wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
if (!handle) {
free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
}
wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
}
static void buffer_resource_destroy(struct wl_resource *resource) {
dmabuf_buffer_unref(wl_resource_get_user_data(resource));
}
static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
AHardwareBuffer *hardware) {
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(hardware, &desc);
struct vkp_image *image = vkp_image_from_android_buffer(hardware);
if (!image) return NULL;
struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
buffer->refs = 1;
buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
buffer->img = image;
for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
struct client_info *info = client_info_of(client);
if (info) info->dmabuf_buffers++;
return result;
}
static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t stride, int32_t format,
int32_t usage, struct wl_resource *handle_resource) {
/* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
* must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
if (!valid_description(width, height, stride ? stride : width, format) ||
!wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
width, height, stride, format, (uint32_t)usage);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
return;
}
struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
if (wire->received != wire->handle->num_fds || !wire->received) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
AHardwareBuffer *hardware = NULL;
int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
if (status != 0 || !hardware) {
droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
status, width, height, stride, format, (uint32_t)usage,
wire->handle->num_fds, wire->handle->num_ints);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
"Android rejected the native handle (status %d)", status);
return;
}
struct wl_resource *buffer = create_android_buffer(client, id, hardware);
AHardwareBuffer_release(hardware);
if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
}
static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t format, int32_t usage) {
if (!format) format = 1;
if (!valid_description(width, height, width, format)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format,
.usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
AHardwareBuffer *hardware = NULL;
if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
return;
}
AHardwareBuffer_describe(hardware, &desc);
const struct android_native_handle *handle = native_handle(hardware);
if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
return;
}
struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
if (!buffer) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
return;
}
struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
wl_resource_get_version(resource), id);
if (!reply) {
wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
wl_client_post_no_memory(client); return;
}
struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
.alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
for (int i = 0; i < handle->num_fds; i++)
android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
/* No linear_layout event: Android's opaque allocation need not be linear. */
android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
wl_resource_destroy(reply);
AHardwareBuffer_release(hardware);
}
static const struct android_wlegl_interface wlegl_impl = {
.create_handle = create_handle, .create_buffer = create_buffer,
.get_server_buffer_handle = get_server_buffer,
};
static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
version < 3 ? version : 3, id);
if (!resource) { wl_client_post_no_memory(client); return; }
wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
}
void droiddeck_android_wlegl_init(struct wl_display *display) {
if (!vkp_android_buffer_supported()) return;
void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
if (!library) return;
import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
if (!import_handle || !native_handle) { dlclose(library); return; }
/* Keep the platform entry points valid for the compositor's lifetime. */
if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
droiddeck_log("display", "android_wlegl v3: Android buffer import available");
}
@@ -19,6 +19,8 @@ import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.QualcommSystemDriver
import com.droiddeck.launcher.gpu.QualcommDriverPackage
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionPrefs
@@ -143,6 +145,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
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)
else if (id == QualcommSystemDriver.ID) DriverRow(id, "System Qualcomm driver", QualcommSystemDriver.label(), false)
else if (QualcommDriverPackage.isRuntimeId(id)) DriverRow(id,
QualcommDriverPackage.label(activity, id), listOf(QualcommDriverPackage.version(activity, id),
activity.getString(R.string.drivers_qualcomm_runtime_display)).filter { it.isNotEmpty() }.joinToString(" · "), false, DriverRow.IMPORTED)
else bundleRow(id, linux = true) ?: DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
@@ -157,6 +163,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val td = TurnipDriver(activity)
val auto = td.autoId()
androidRows = buildList {
if (QualcommSystemDriver.detected()) add(DriverRow(TurnipDriver.SYSTEM,
"System Qualcomm driver", QualcommSystemDriver.label(), false))
add(DriverRow(
TurnipDriver.AUTO, activity.getString(R.string.gpu_auto_by_gpu),
if (auto == "system") activity.getString(R.string.drivers_system_vulkan) else activity.getString(R.string.drivers_bundled, td.displayName(auto)),
@@ -431,7 +439,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val bundle = DriverBundle.containing(activity, id, linux)
when {
bundle != null -> useBundle(bundle)
linux -> SessionPrefs.setLinuxDriver(activity, id)
linux -> {
SessionPrefs.setLinuxDriver(activity, id)
if (QualcommSystemDriver.handles(id)) SessionPrefs.setAndroidDriver(activity, TurnipDriver.SYSTEM)
}
else -> SessionPrefs.setAndroidDriver(activity, id)
}
pairModeOpen = false
@@ -2081,8 +2081,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return
}
val driverHint = runtimeDriverHint()
Thread({
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
val hint = driverHint ?: runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint)
@@ -2138,6 +2139,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private class EndHint(val text: String, val evenOnSuccess: Boolean = false, val repair: Boolean = false)
private fun runtimeDriverHint(): EndHint? {
if (SessionState.failureCode != SessionService.FAILURE_RUNTIME_DRIVER) return null
val message = getString(R.string.session_end_runtime_driver, getString(R.string.gpu_mode_mix), getString(R.string.gpu_change_runtime))
return EndHint(listOfNotNull(message, SessionState.failureMessage?.takeIf { it.isNotBlank() }).joinToString("\n"))
}
private fun runtimeDamageHint(): EndHint? {
val broken = runCatching { com.droiddeck.launcher.runtime.RuntimeHealth.brokenLibraryLinks(this) }.getOrDefault(emptyList())
if (broken.isEmpty()) return null
@@ -222,7 +222,10 @@ object DeviceReport {
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 == com.droiddeck.launcher.gpu.QualcommSystemDriver.ID) com.droiddeck.launcher.gpu.QualcommSystemDriver.label()
else if (com.droiddeck.launcher.gpu.QualcommDriverPackage.isRuntimeId(id))
"${com.droiddeck.launcher.gpu.QualcommDriverPackage.label(context, id)} ${com.droiddeck.launcher.gpu.QualcommDriverPackage.version(context, id)}"
else if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
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]"
@@ -149,7 +149,9 @@ object DeviceInfo {
add("Display driver", "${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 == QualcommSystemDriver.ID) QualcommSystemDriver.label()
else if (QualcommDriverPackage.isRuntimeId(id)) "${QualcommDriverPackage.label(context, id)} ${QualcommDriverPackage.version(context, id)}"
else if (id.isEmpty()) "the runtime's own Turnip" 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")
})
}
@@ -12,8 +12,8 @@ public final class LinuxVulkanDriver {
public static final String HELP_TEXT =
"The driver the Steam client, the games it launches and the desktop's programs render on, "
+ "inside the Linux runtime. Imported \"-Linux\" Turnip zips only: these are Linux processes "
+ "and cannot load an Android or Wayland driver. Frames still reach the screen through the "
+ "inside the Linux runtime. Import \"-Linux\" Turnip zips, or select the experimental system "
+ "Qualcomm bridge or a Qualcomm package already imported as an AdrenoTools zip. Frames reach the screen through the "
+ "display driver below. Takes effect at the next session start.";
private LinuxVulkanDriver() {}
@@ -21,12 +21,18 @@ public final class LinuxVulkanDriver {
public static List<String> optionValues(Context context) {
ArrayList<String> values = new ArrayList<>();
values.add("");
if (QualcommSystemDriver.detected()) {
values.add(QualcommSystemDriver.ID);
values.addAll(QualcommDriverPackage.available(context));
}
values.addAll(new LinuxVulkanDriverManager(context).enumerateInstalledDrivers());
return values;
}
public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
if (QualcommSystemDriver.ID.equals(value)) return QualcommSystemDriver.label();
if (QualcommDriverPackage.isRuntimeId(value)) return QualcommDriverPackage.label(context, value);
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
String ver = m.getDriverVersion(value);
@@ -35,6 +41,11 @@ public final class LinuxVulkanDriver {
public static String resolveIcdPath(Context context, String value) {
if (value == null || value.isEmpty()) return null;
if (QualcommSystemDriver.handles(value)) {
if (QualcommDriverPackage.isRuntimeId(value) && !QualcommDriverPackage.isInstalled(context, value))
throw new QualcommSystemDriver.Unavailable("The selected Qualcomm AdrenoTools package is missing or incompatible");
return QualcommSystemDriver.prepare(context).getAbsolutePath();
}
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
String icd = m.getIcdPath(value);
if (icd == null) {
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.core.FileUtils
import org.json.JSONObject
import java.io.File
object QualcommDriverPackage {
private const val PREFIX = "qualcomm-adrenotools:"
@JvmStatic fun runtimeId(importedId: String): String {
require(validName(importedId)) { "Invalid imported driver ID" }
return PREFIX + importedId
}
@JvmStatic fun importedId(runtimeId: String?): String? = runtimeId
?.takeIf { it.startsWith(PREFIX) }?.removePrefix(PREFIX)?.takeIf(::validName)
@JvmStatic fun isRuntimeId(id: String?): Boolean = id?.startsWith(PREFIX) == true
private fun validName(name: String): Boolean = name.isNotBlank() && name != "." && !name.contains("..") &&
name.none { it == '/' || it == '\\' || it == ':' || it == '\u0000' }
private fun metadata(context: Context, id: String): JSONObject? {
if (!validName(id)) return null
return runCatching { JSONObject(FileUtils.readString(File(TurnipDriver(context).driverPath(id), "meta.json"))) }.getOrNull()
}
@JvmStatic fun available(context: Context): List<String> = TurnipDriver(context).enumerateImported()
.filter { isInstalled(context, runtimeId(it)) }.map(::runtimeId)
@JvmStatic fun isInstalled(context: Context, runtimeId: String): Boolean {
val id = importedId(runtimeId) ?: return false
val meta = metadata(context, id) ?: return false
val vendor = meta.optString("vendor")
val description = listOf(meta.optString("name"), meta.optString("description"), meta.optString("libraryName")).joinToString(" ")
if (!vendor.equals("Qualcomm", true) || description.contains("turnip", true) || description.contains("mesa", true)) return false
if (meta.optInt("minApi", 0) > Build.VERSION.SDK_INT) return false
val library = meta.optString("libraryName")
return validName(library) && library.endsWith(".so") && TurnipDriver(context).isInstalled(id) &&
LinuxVulkanDriverManager.isAarch64Elf(File(TurnipDriver(context).driverPath(id), library))
}
@JvmStatic fun label(context: Context, runtimeId: String): String {
val id = importedId(runtimeId) ?: return "Invalid Qualcomm package"
val driver = TurnipDriver(context)
return "${driver.displayName(id)} · Qualcomm (AdrenoTools, experimental)" +
if (isInstalled(context, runtimeId)) "" else " [missing or incompatible]"
}
@JvmStatic fun version(context: Context, runtimeId: String): String = importedId(runtimeId)
?.let { TurnipDriver(context).driverVersion(it) }.orEmpty()
@JvmStatic fun mounts(context: Context, runtimeId: String): List<String> {
ensureAvailable(isInstalled(context, runtimeId)) { "The selected Qualcomm AdrenoTools package is missing or incompatible" }
val id = importedId(runtimeId)!!
val driver = TurnipDriver(context)
val directory = File(driver.driverPath(id))
val primary = driver.libraryName(id)!!
val mounts = arrayListOf("${File(directory, primary).path}:${QualcommSystemDriver.HAL}")
for (library in directory.listFiles().orEmpty().sortedBy { it.name }) {
val name = library.name
if (name == primary || !name.endsWith(".so") || !validName(name) ||
name in setOf("libc.so", "libdl.so", "libm.so", "liblog.so", "libvulkan.so") ||
!LinuxVulkanDriverManager.isAarch64Elf(library)) continue
mounts.add("${library.path}:/vendor/lib64/$name")
// The SP-HAL namespace resolves libc++ from system before vendor.
if (name == "libc++.so") mounts.add("${library.path}:/system/lib64/$name")
}
return mounts
}
}
@@ -0,0 +1,125 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.TarZst
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.File
internal inline fun ensureAvailable(condition: Boolean, message: () -> String) {
if (!condition) throw QualcommSystemDriver.Unavailable(message())
}
object QualcommSystemDriver {
class Unavailable(message: String) : IllegalStateException(message)
const val ID = "system-qualcomm"
const val HAL = "/vendor/lib64/hw/vulkan.adreno.so"
private val required = listOf("lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1", "lib/libhybris/linker/q.so",
"bin/gamescope", "shaders/qualcomm-shaders.so", "wsi/libVkLayer_window_system_integration.so",
"mesa/libgallium-26.2.3.so", "mesa/dri/zink_dri.so", "mesa/libGLX_droiddeck_qualcomm.so.0",
"mesa/libEGL_droiddeck_qualcomm.so.0", "mesa/libgbm.so.1", "mesa/gbm/dri_gbm.so",
"mesa/egl-vendor.json", "mesa/qualcomm-gl.sh")
@JvmStatic fun detected(): Boolean {
if (Build.VERSION.SDK_INT < 29 || !File(HAL).canRead()) return false
val vk = VulkanInfo.query()
return isQualcomm(vk)
}
internal fun isQualcomm(vk: Map<String, String>): Boolean =
vk["vendor_id"] == "0x5143" && (vk["driver_id"] == "8" ||
(vk["driver_id"] == null && vk["driver_name"]?.contains("Qualcomm", ignoreCase = true) == true))
@JvmStatic fun handles(id: String?) = id == ID || QualcommDriverPackage.isRuntimeId(id)
@JvmStatic fun selected(context: Context) = handles(SessionPrefs.linuxDriver(context))
@JvmStatic fun mounts(context: Context, id: String): List<String> = androidPaths() +
if (QualcommDriverPackage.isRuntimeId(id)) QualcommDriverPackage.mounts(context, id) else emptyList()
@JvmStatic fun label(): String {
val vk = VulkanInfo.query()
val version = vk["driver_version_raw"]?.toULongOrNull()?.let { "${(it shr 22) and 0x7fu}.${(it shr 12) and 0x3ffu}.${it and 0xfffu}" }
?: vk["driver_version"] ?: "unknown version"
return "System Qualcomm · ${vk["device"] ?: "Adreno"} · $version (experimental)"
}
@JvmStatic @Synchronized fun prepare(context: Context): File {
ensureAvailable(detected()) { "The installed Vulkan driver is not a supported Qualcomm Android driver" }
val sha = BuildConfig.QUALCOMM_BRIDGE_SHA256 + "-" + BuildConfig.QUALCOMM_FIXES_REVISION.take(16)
val root = File(context.filesDir, "qualcomm-system")
val dir = File(root, sha)
if (!File(dir, ".complete").isFile || required.any { !File(dir, it).isFile }) {
val staging = File(root, "$sha.partial")
FileUtils.delete(staging)
ensureAvailable(TarZst.extractAsset(context, "qualcomm/runtime.tzst", staging)) { "Cannot extract the Qualcomm Vulkan bridge" }
val gamescope = File(staging, "bin/gamescope")
gamescope.parentFile!!.mkdirs()
ensureAvailable(FileUtils.copyAsset(context, "qualcomm/gamescope", gamescope)) { "Cannot prepare Qualcomm Gamescope" }
ensureAvailable(gamescope.setExecutable(true, false)) { "Cannot prepare Qualcomm Gamescope" }
copyAssets(context, "qualcomm/wsi", File(staging, "wsi"))
copyAssets(context, "qualcomm/shaders", File(staging, "shaders"))
copyAssets(context, "qualcomm/licenses", File(staging, "licenses"))
copyAssets(context, "qualcomm/mesa", File(staging, "mesa"))
ensureAvailable(required.all { File(staging, it).isFile }) { "The Qualcomm Vulkan bridge is incomplete" }
File(staging, ".complete").writeText(sha)
FileUtils.delete(dir)
ensureAvailable(staging.renameTo(dir)) { "Cannot install the Qualcomm Vulkan bridge" }
}
val manifest = JSONObject().put("file_format_version", "1.0.0").put("ICD", JSONObject()
.put("library_path", File(dir, "lib/libhybris-vulkan-icd.so.0").path)
.put("api_version", VulkanInfo.query()["api"] ?: "1.1.0"))
val icd = File(dir, "icd.json")
if (!icd.isFile || icd.readText() != manifest.toString()) icd.writeText(manifest.toString())
return icd
}
@JvmStatic @JvmOverloads fun addEnvironment(context: Context, environment: MutableList<String>, id: String = SessionPrefs.linuxDriver(context)) {
if (QualcommDriverPackage.isRuntimeId(id)) ensureAvailable(QualcommDriverPackage.isInstalled(context, id)) {
"The selected Qualcomm AdrenoTools package is missing or incompatible"
}
val icd = prepare(context)
val source = if (id == ID) label() else QualcommDriverPackage.label(context, id)
android.util.Log.i("QualcommSystemDriver", "$source; Android mounts: ${mounts(context, id).joinToString()}")
environment.addAll(sessionEnvironment(icd, id))
}
internal fun sessionEnvironment(icd: File, id: String): List<String> {
val dir = icd.parentFile!!
return listOf(
"VK_DRIVER_FILES=${icd.path}", "VK_ICD_FILENAMES=${icd.path}",
"HYBRIS_ANDROID_SDK_VERSION=${Build.VERSION.SDK_INT}", "HYBRIS_VULKAN_HAL=$HAL",
"HYBRIS_LINKER_DIR=${File(dir, "lib/libhybris/linker").path}",
"HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64",
// The compat layer's Mali-only image-bounds pass rewrites unrelated OpSelects; DXVK comparisons become constants on Adreno.
"HYBRIS_VULKAN_COMPAT_IMAGE_BOUNDS=0",
"DROIDDECK_SYSTEM_QUALCOMM=1", "BL_GAMESCOPE_BACKEND=sdl",
"DROIDDECK_QUALCOMM_DRIVER=$id",
"BL_GAMESCOPE_BINARY=${File(dir, "bin/gamescope").path}",
"DROIDDECK_QUALCOMM_ROOT=${dir.path}",
"DROIDDECK_QUALCOMM_SHADERS=${File(dir, "shaders").path}",
"VK_LAYER_PATH=${File(dir, "shaders").path}",
"VK_INSTANCE_LAYERS=VK_LAYER_DROIDDECK_qualcomm_shaders",
"PATH=${File(dir, "bin").path}:/usr/local/bin:/usr/bin:/bin",
)
}
private fun copyAssets(context: Context, path: String, destination: File) {
val children = context.assets.list(path) ?: emptyArray()
if (children.isEmpty()) {
ensureAvailable(FileUtils.copyAsset(context, path, destination)) { "Cannot prepare $path" }
} else {
ensureAvailable(destination.isDirectory || destination.mkdirs()) { "Cannot prepare $path" }
for (child in children) copyAssets(context, "$path/$child", File(destination, child))
}
}
@JvmStatic fun androidPaths(): List<String> = listOf(
"/system", "/vendor", "/odm", "/system_ext", "/product", "/apex", "/linkerconfig",
"/dev/__properties__"
).filter { File(it).exists() }
}
@@ -37,6 +37,7 @@ public final class TurnipDriver {
private static final String PREFS = "graphics_driver";
private static final String KEY_HIDDEN = "hiddenBundled";
public static final String AUTO = "";
public static final String SYSTEM = "system";
public static final String HELP_TEXT =
"The driver the app's compositor puts frames on the screen with - the last step of every "
@@ -139,6 +140,8 @@ public final class TurnipDriver {
Log.d(TAG, "removing imported driver " + driverId);
FileUtils.delete(new File(contentDir, driverId));
if (driverId.equals(SessionPrefs.androidDriver(context))) SessionPrefs.setAndroidDriver(context, AUTO);
if (driverId.equals(QualcommDriverPackage.importedId(SessionPrefs.INSTANCE.linuxDriver(context))))
SessionPrefs.INSTANCE.setLinuxDriver(context, "");
}
public String installFromZip(Uri zipUri, String displayName) throws IOException {
@@ -257,6 +260,7 @@ public final class TurnipDriver {
private String choose() {
String chosen = SessionPrefs.androidDriver(context);
if (SYSTEM.equals(chosen)) return null;
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
@@ -179,6 +179,15 @@ object BwrapSpawner {
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
val runtimeDriver = com.droiddeck.launcher.session.SessionState.runtimeDriver
if (com.droiddeck.launcher.gpu.QualcommSystemDriver.handles(runtimeDriver)) {
val driver = com.droiddeck.launcher.gpu.QualcommSystemDriver
val variables = ArrayList<String>()
driver.addEnvironment(context, variables, runtimeDriver!!)
for (entry in variables) env.putIfAbsent(entry.substringBefore('='), entry.substringAfter('='))
for (path in driver.mounts(context, runtimeDriver) + File(context.filesDir, "qualcomm-system").path)
addBind(Bind.parse(path))
}
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
preload(session, rootfs, env).forEach { addBind(it) }
zypakShims(binds, root, dir).forEach { addBind(it) }
@@ -160,6 +160,10 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
if (com.droiddeck.launcher.gpu.QualcommSystemDriver.selected(context)) {
for (String path : com.droiddeck.launcher.gpu.QualcommSystemDriver.mounts(context,
SessionPrefs.INSTANCE.linuxDriver(context))) bind(cmd, path);
}
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin");
@@ -56,6 +56,9 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/bin/droiddeck-steam-taskset",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
"usr/local/bin/droiddeck-qualcomm-caps" to "usr/local/bin/droiddeck-qualcomm-caps",
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
@@ -378,7 +378,15 @@ class SessionService : Service() {
Thread({
OrphanReaper.reap("session starting")
ProtonExtras.awaitReplacement(120_000)
runSession(gen)
try {
runSession(gen)
} catch (e: com.droiddeck.launcher.gpu.QualcommSystemDriver.Unavailable) {
Log.e(TAG, "runtime driver unavailable", e)
if (gen == sessionGen) {
SessionEvents.fail(FAILURE_RUNTIME_DRIVER, e.message.orEmpty())
stopSession(-1)
}
}
}, "session-start").start()
return START_NOT_STICKY
}
@@ -719,8 +727,10 @@ 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 linuxDriverId = SessionPrefs.linuxDriver(this)
val systemQualcomm = com.droiddeck.launcher.gpu.QualcommSystemDriver.handles(linuxDriverId)
if (systemQualcomm) com.droiddeck.launcher.gpu.QualcommSystemDriver.addEnvironment(this, guest)
else LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
SessionState.runtimeDriver = linuxDriverId
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
this,
@@ -730,9 +740,9 @@ class SessionService : Service() {
)
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
val tuOverride = tuDebugOverride()
val tuOverride = if (systemQualcomm) null else tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (!systemQualcomm) (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")
@@ -740,7 +750,9 @@ class SessionService : Service() {
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
guest.add("MESA_DISK_CACHE_DATABASE=1")
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
// Steam loads libhybris after other TLS users; its Bionic TLS bridge requires static storage.
val staticTls = if (systemQualcomm) ":glibc.rtld.optional_static_tls=16384" else ""
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216$staticTls")
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
SessionState.steamClientArch?.let { arch ->
@@ -2077,6 +2089,7 @@ class SessionService : Service() {
const val MODE_STEAM = "steam"
const val MODE_DESKTOP = "lxqt"
const val MODE_RUN = "run"
const val FAILURE_RUNTIME_DRIVER = "RUNTIME_DRIVER_UNAVAILABLE"
const val EXTRA_PROGRAM = "program"
private const val RUN_STATUS = "run-status"
const val EXTRA_PROGRAM_ARGS = "programArgs"
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.boundsInRoot
@@ -19,6 +21,7 @@ import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
@@ -209,7 +212,7 @@ private fun DeviceInfoSection(section: DeviceInfo.Section) {
private const val STALE_MS = 6 * 3_600_000L
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun GpuDriversBody(
gpu: GpuDriversState,
@@ -224,6 +227,13 @@ internal fun GpuDriversBody(
}
val scroll = rememberScrollState()
val scope = rememberCoroutineScope()
val driverControls = remember { BringIntoViewRequester() }
LaunchedEffect(gpu.mode) {
if (gpu.mode == GPU_MODE_MIX) {
withFrameNanos { }
driverControls.bringIntoView()
}
}
val placed = remember { arrayOfNulls<LayoutCoordinates>(2) }
// Focusing the top mode shows as much of the in-use card above it as fits, without hiding the mode itself.
val revealCard = {
@@ -251,7 +261,10 @@ internal fun GpuDriversBody(
stringResource(title), stringResource(detail), gpu.mode == id,
modifier = mod.then(if (gpu.mode == id) Modifier.focusRequester(first) else Modifier)
.then(if (i == 0) Modifier.onGloballyPositioned { placed[1] = it }.onFocusChanged { if (it.isFocused) revealCard() } else Modifier),
onClick = { if (gpu.mode != id) actions.onMode(id) },
onClick = {
if (gpu.mode != id) actions.onMode(id)
else if (id == GPU_MODE_MIX) scope.launch { driverControls.bringIntoView() }
},
)
}
if (single) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { modes.indices.forEach { choice(it, Modifier) } }
@@ -261,7 +274,7 @@ internal fun GpuDriversBody(
when (gpu.mode) {
GPU_MODE_AUTO -> AutoBody(gpu)
GPU_MODE_PAIR -> PairBody(gpu, actions)
else -> MixBody(single, actions, slotFocus, onOpenSlot)
else -> MixBody(single, actions, slotFocus, onOpenSlot, Modifier.bringIntoViewRequester(driverControls))
}
gpu.tpUbwcMode?.let { selected ->
var advanced by rememberSaveable { mutableStateOf(false) }
@@ -395,7 +408,7 @@ private fun PairBody(gpu: GpuDriversState, actions: GpuDriversActions) {
}
@Composable
private fun MixBody(single: Boolean, actions: GpuDriversActions, slotFocus: Map<String, FocusRequester>, onOpenSlot: (String, Rect) -> Unit) {
private fun MixBody(single: Boolean, actions: GpuDriversActions, slotFocus: Map<String, FocusRequester>, onOpenSlot: (String, Rect) -> Unit, controlsModifier: Modifier) {
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
PanelTitle(stringResource(R.string.gpu_mix_title), stringResource(R.string.gpu_mix_hint))
@@ -410,8 +423,8 @@ private fun MixBody(single: Boolean, actions: GpuDriversActions, slotFocus: Map<
slotButton(SLOT_DISPLAY, R.string.gpu_change_display, mod)
slotButton(SLOT_RUNTIME, R.string.gpu_change_runtime, mod)
}
if (single) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { buttons(Modifier.fillMaxWidth()) }
else Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { buttons(Modifier.weight(1f)) }
if (single) Column(controlsModifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { buttons(Modifier.fillMaxWidth()) }
else Row(controlsModifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { buttons(Modifier.weight(1f)) }
FocusText(stringResource(R.string.comp_import_zip), pal.signal, onClick = actions.onImportZip)
}
}
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">هذا البرنامج</string>
<string name="session_end_steam_download">تعذّر تنزيل عميل Steam. قد تكون شبكتك أو VPN تحظر خوادم Steam؛ تحقّق من الاتصال وحاول مرة أخرى.</string>
<string name="session_end_steam_setup">تعذّر إعداد عميل Steam. تحقّق من الاتصال والمساحة الفارغة، ثم حاول مرة أخرى.</string>
<string name="session_end_runtime_driver">برنامج تشغيل بيئة Linux المحدد غير موجود أو لا يمكن استخدامه على هذا الهاتف. اختر برنامجًا آخر من %1$s › %2$s، ثم ابدأ من جديد.</string>
<string name="session_end_fex_missing">%1$s مبني لأجهزة كمبيوتر x86 ويعمل عبر FEX، الذي لم يتم تثبيته بعد. شغّل Steam مرة واحدة أثناء تسجيل الدخول ودعه يُنزّل FEX وSteam Linux Runtime، ثم شغّل هذا البرنامج مجددًا.</string>
<string name="add_app_flatpak_hint">معرّف تطبيق على Flathub أو صفحته على Flathub. يُعَدّ Flatpak أولًا إن لم يكن مُعدًّا بعد.</string>
<string name="add_app_file">الملف</string>
@@ -178,6 +178,7 @@
<string name="session_end_program">Este programa</string>
<string name="session_end_steam_download">No se pudo descargar el cliente de Steam. Es posible que tu red o VPN esté bloqueando los servidores de Steam; revisa la conexión e inténtalo de nuevo.</string>
<string name="session_end_steam_setup">No se pudo configurar el cliente de Steam. Revisa la conexión y el espacio libre, y vuelve a intentarlo.</string>
<string name="session_end_runtime_driver">El controlador de runtime de Linux seleccionado no está disponible o no se puede usar en este teléfono. Elige otro en %1$s › %2$s y vuelve a iniciar.</string>
<string name="session_end_fex_missing">%1$s está hecho para PC x86 y se ejecuta con FEX, que aún no está instalado. Abre Steam una vez con tu sesión iniciada y deja que descargue FEX y el Steam Linux Runtime; después vuelve a iniciarlo.</string>
<string name="add_app_flatpak_hint">Un ID de app de Flathub o su página en Flathub. Flatpak se configura primero si aún no lo está.</string>
<string name="add_app_file">Archivo</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Тази програма</string>
<string name="session_end_steam_download">Клиентът на Steam не можа да бъде изтеглен. Мрежата или VPN връзката ви може да блокира сървърите на Steam; проверете връзката и опитайте отново.</string>
<string name="session_end_steam_setup">Клиентът на Steam не можа да бъде настроен. Проверете връзката и свободното място, след което опитайте отново.</string>
<string name="session_end_runtime_driver">Избраният драйвер за средата на Linux липсва или не може да се използва на този телефон. Изберете друг от %1$s › %2$s и стартирайте отново.</string>
<string name="session_end_fex_missing">%1$s е компилирана за x86 компютри и се стартира през FEX, който още не е инсталиран. Стартирайте Steam веднъж, докато сте влезли, и го оставете да изтегли FEX и Steam Linux Runtime, след което стартирайте отново.</string>
<string name="add_app_flatpak_hint">ID на приложение в Flathub или страницата му в Flathub. Flatpak се настройва първо, ако още не е.</string>
<string name="add_app_file">Файл</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Tento program</string>
<string name="session_end_steam_download">Klienta Steam se nepodařilo stáhnout. Vaše síť nebo VPN možná blokuje servery Steamu; zkontrolujte připojení a zkuste to znovu.</string>
<string name="session_end_steam_setup">Klienta Steam se nepodařilo nastavit. Zkontrolujte připojení a volné místo a zkuste to znovu.</string>
<string name="session_end_runtime_driver">Vybraný ovladač runtime Linuxu chybí nebo jej v tomto telefonu nelze použít. Vyberte jiný v %1$s › %2$s a spusťte znovu.</string>
<string name="session_end_fex_missing">%1$s je sestaven pro PC x86 a běží přes FEX, který ještě není nainstalován. Jednou spusťte přihlášený Steam a nechte ho stáhnout FEX a Steam Linux Runtime, pak to spusťte znovu.</string>
<string name="add_app_flatpak_hint">ID aplikace Flathub nebo její stránka na Flathub. Flatpak se nejprve nastaví, pokud ještě není.</string>
<string name="add_app_file">Soubor</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Dette program</string>
<string name="session_end_steam_download">Steam-klienten kunne ikke downloades. Dit netværk eller din VPN blokerer muligvis Steams servere; tjek forbindelsen, og prøv igen.</string>
<string name="session_end_steam_setup">Steam-klienten kunne ikke konfigureres. Tjek forbindelsen og den ledige lagerplads, og prøv igen.</string>
<string name="session_end_runtime_driver">Den valgte Linux-runtime-driver mangler eller kan ikke bruges på denne telefon. Vælg en anden under %1$s › %2$s, og start igen.</string>
<string name="session_end_fex_missing">%1$s er bygget til x86-pc’er og køres via FEX, som ikke er installeret endnu. Start Steam én gang, mens du er logget ind, og lad det downloade FEX og Steam Linux Runtime, og start så dette igen.</string>
<string name="add_app_flatpak_hint">Et Flathub-app-id eller dens Flathub-side. Flatpak sættes op først, hvis det ikke allerede er.</string>
<string name="add_app_file">Fil</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Dieses Programm</string>
<string name="session_end_steam_download">Der Steam-Client konnte nicht heruntergeladen werden. Dein Netzwerk oder VPN blockiert möglicherweise die Server von Steam; prüfe die Verbindung und versuche es erneut.</string>
<string name="session_end_steam_setup">Der Steam-Client konnte nicht eingerichtet werden. Prüfe die Verbindung und den freien Speicher und versuche es erneut.</string>
<string name="session_end_runtime_driver">Der ausgewählte Linux-Laufzeittreiber fehlt oder kann auf diesem Telefon nicht verwendet werden. Wähle unter %1$s › %2$s einen anderen und starte erneut.</string>
<string name="session_end_fex_missing">%1$s ist für x86-PCs gebaut und läuft über FEX, das noch nicht installiert ist. Starte Steam einmal, während du angemeldet bist, und lass es FEX und die Steam Linux Runtime herunterladen. Starte es danach erneut.</string>
<string name="add_app_flatpak_hint">Eine Flathub-App-ID oder ihre Flathub-Seite. Flatpak wird zuerst eingerichtet, falls noch nicht geschehen.</string>
<string name="add_app_file">Datei</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Αυτό το πρόγραμμα</string>
<string name="session_end_steam_download">Δεν ήταν δυνατή η λήψη του πελάτη Steam. Το δίκτυο ή το VPN σας ίσως αποκλείει τους διακομιστές του Steam· ελέγξτε τη σύνδεση και δοκιμάστε ξανά.</string>
<string name="session_end_steam_setup">Δεν ήταν δυνατή η ρύθμιση του πελάτη Steam. Ελέγξτε τη σύνδεση και τον ελεύθερο χώρο αποθήκευσης και δοκιμάστε ξανά.</string>
<string name="session_end_runtime_driver">Το επιλεγμένο πρόγραμμα οδήγησης runtime Linux λείπει ή δεν μπορεί να χρησιμοποιηθεί σε αυτό το τηλέφωνο. Επιλέξτε άλλο από %1$s › %2$s και ξεκινήστε ξανά.</string>
<string name="session_end_fex_missing">Το %1$s είναι χτισμένο για υπολογιστές x86 και εκτελείται μέσω FEX, το οποίο δεν έχει εγκατασταθεί ακόμα. Εκκινήστε το Steam μία φορά ενώ είστε συνδεδεμένοι και αφήστε το να κάνει λήψη του FEX και του Steam Linux Runtime, μετά εκκινήστε αυτό ξανά.</string>
<string name="add_app_flatpak_hint">Ένα ID εφαρμογής Flathub ή η σελίδα της στο Flathub. Το Flatpak ρυθμίζεται πρώτα, αν δεν έχει ρυθμιστεί ακόμα.</string>
<string name="add_app_file">Αρχείο</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Este programa</string>
<string name="session_end_steam_download">No se ha podido descargar el cliente de Steam. Puede que tu red o VPN esté bloqueando los servidores de Steam; comprueba la conexión y vuelve a intentarlo.</string>
<string name="session_end_steam_setup">No se ha podido configurar el cliente de Steam. Comprueba la conexión y el espacio libre y vuelve a intentarlo.</string>
<string name="session_end_runtime_driver">El controlador de runtime de Linux seleccionado no está disponible o no se puede usar en este teléfono. Elige otro en %1$s › %2$s y vuelve a iniciar.</string>
<string name="session_end_fex_missing">%1$s está hecho para PC x86 y se ejecuta con FEX, que aún no está instalado. Abre Steam una vez con tu sesión iniciada y deja que descargue FEX y el Steam Linux Runtime; después vuelve a iniciarlo.</string>
<string name="add_app_flatpak_hint">Un ID de app de Flathub o su página en Flathub. Flatpak se configura primero si aún no lo está.</string>
<string name="add_app_file">Archivo</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Tämä ohjelma</string>
<string name="session_end_steam_download">Steam-asiakasohjelmaa ei voitu ladata. Verkkosi tai VPN saattaa estää Steamin palvelimet; tarkista yhteys ja yritä uudelleen.</string>
<string name="session_end_steam_setup">Steam-asiakasohjelmaa ei voitu ottaa käyttöön. Tarkista yhteys ja vapaa tallennustila ja yritä uudelleen.</string>
<string name="session_end_runtime_driver">Valittu Linux-ajoympäristön ajuri puuttuu tai sitä ei voi käyttää tässä puhelimessa. Valitse toinen kohdasta %1$s › %2$s ja käynnistä uudelleen.</string>
<string name="session_end_fex_missing">%1$s on tehty x86-tietokoneille ja käynnistyy FEXin kautta, jota ei ole vielä asennettu. Käynnistä Steam kerran kirjautuneena ja anna sen ladata FEX ja Steam Linux Runtime, sitten käynnistä tämä uudelleen.</string>
<string name="add_app_flatpak_hint">Flathub-sovellustunnus tai sen Flathub-sivu. Flatpak otetaan käyttöön ensin, jos sitä ei ole vielä otettu.</string>
<string name="add_app_file">Tiedosto</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Ce programme</string>
<string name="session_end_steam_download">Impossible de télécharger le client Steam. Votre réseau ou votre VPN bloque peut-être les serveurs de Steam ; vérifiez la connexion et réessayez.</string>
<string name="session_end_steam_setup">Impossible de configurer le client Steam. Vérifiez la connexion et l\'espace libre, puis réessayez.</string>
<string name="session_end_runtime_driver">Le pilote d\'exécution Linux sélectionné est introuvable ou inutilisable sur ce téléphone. Choisissez-en un autre dans %1$s › %2$s, puis relancez.</string>
<string name="session_end_fex_missing">%1$s est conçu pour les PC x86 et s\'exécute via FEX, qui n\'est pas encore installé. Lancez Steam une fois en étant connecté et laissez-le télécharger FEX et le Steam Linux Runtime, puis relancez ce programme.</string>
<string name="add_app_flatpak_hint">ID d\'application Flathub ou sa page Flathub. Si Flatpak n\'est pas encore configuré, il le sera d\'abord.</string>
<string name="add_app_file">Fichier</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">यह प्रोग्राम</string>
<string name="session_end_steam_download">Steam क्लाइंट डाउनलोड नहीं हो सका। हो सकता है आपका नेटवर्क या VPN Steam के सर्वर ब्लॉक कर रहा हो; कनेक्शन जांचें और फिर से कोशिश करें।</string>
<string name="session_end_steam_setup">Steam क्लाइंट सेट अप नहीं हो सका। कनेक्शन और खाली स्टोरेज जांचें, फिर से कोशिश करें।</string>
<string name="session_end_runtime_driver">चुना गया Linux रनटाइम ड्राइवर मौजूद नहीं है या इस फ़ोन पर इस्तेमाल नहीं हो सकता। %1$s › %2$s में कोई दूसरा चुनें, फिर से शुरू करें।</string>
<string name="session_end_fex_missing">%1$s x86 पीसी के लिए बना है और FEX के ज़रिए चलता है, जो अभी इंस्टॉल नहीं है। साइन इन रहते हुए Steam एक बार शुरू करें और इसे FEX और Steam Linux Runtime डाउनलोड करने दें, फिर इसे फिर से शुरू करें।</string>
<string name="add_app_flatpak_hint">एक Flathub ऐप ID या उसका Flathub पेज। अगर Flatpak अभी सेट नहीं है, तो पहले वह सेट होगा।</string>
<string name="add_app_file">फ़ाइल</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Ez a program</string>
<string name="session_end_steam_download">A Steam-klienst nem sikerült letölteni. Lehet, hogy a hálózat vagy a VPN blokkolja a Steam szervereit; ellenőrizd a kapcsolatot, és próbáld újra.</string>
<string name="session_end_steam_setup">A Steam-klienst nem sikerült beállítani. Ellenőrizd a kapcsolatot és a szabad tárhelyet, majd próbáld újra.</string>
<string name="session_end_runtime_driver">A kiválasztott Linux futtatókörnyezet-illesztőprogram hiányzik, vagy nem használható ezen a telefonon. Válassz másikat itt: %1$s › %2$s, majd indítsd újra.</string>
<string name="session_end_fex_missing">A %1$s x86 PC-khez készült, és a FEX-en keresztül fut, amely még nincs telepítve. Indítsa el egyszer a Steamet bejelentkezve, és hagyja letölteni a FEX-et és a Steam Linux Runtime-ot, majd indítsa el ezt újra.</string>
<string name="add_app_flatpak_hint">Egy Flathub-alkalmazásazonosító vagy a Flathub-oldala. A Flatpak előbb beállításra kerül, ha még nincs beállítva.</string>
<string name="add_app_file">Fájl</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Program ini</string>
<string name="session_end_steam_download">Tidak dapat mengunduh klien Steam. Jaringan atau VPN Anda mungkin memblokir server Steam; periksa koneksi lalu coba lagi.</string>
<string name="session_end_steam_setup">Tidak dapat menyiapkan klien Steam. Periksa koneksi dan ruang penyimpanan kosong, lalu coba lagi.</string>
<string name="session_end_runtime_driver">Driver runtime Linux yang dipilih tidak ada atau tidak dapat digunakan di ponsel ini. Pilih driver lain di %1$s › %2$s, lalu mulai lagi.</string>
<string name="session_end_fex_missing">%1$s dibuat untuk PC x86 dan berjalan melalui FEX, yang belum terinstal. Mulai Steam sekali saat masuk dan biarkan FEX serta Steam Linux Runtime diunduh, lalu mulai lagi.</string>
<string name="add_app_flatpak_hint">ID aplikasi Flathub atau halaman Flathub-nya. Flatpak disiapkan dahulu jika belum.</string>
<string name="add_app_file">File</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Questo programma</string>
<string name="session_end_steam_download">Impossibile scaricare il client Steam. La rete o la VPN potrebbe bloccare i server di Steam; controlla la connessione e riprova.</string>
<string name="session_end_steam_setup">Impossibile configurare il client Steam. Controlla la connessione e lo spazio libero, poi riprova.</string>
<string name="session_end_runtime_driver">Il driver del runtime Linux selezionato manca o non può essere usato su questo telefono. Scegline un altro in %1$s › %2$s, poi riavvia.</string>
<string name="session_end_fex_missing">%1$s è compilato per PC x86 e viene eseguito tramite FEX, che non è ancora installato. Avvia Steam una volta dopo aver eseguito l\'accesso e lascia che scarichi FEX e lo Steam Linux Runtime, poi riavvia il programma.</string>
<string name="add_app_flatpak_hint">Un ID app di Flathub o la sua pagina su Flathub. Se manca, Flatpak viene prima configurato.</string>
<string name="add_app_file">File</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">このプログラム</string>
<string name="session_end_steam_download">Steamクライアントをダウンロードできませんでした。ネットワークまたはVPNがSteamのサーバーをブロックしている可能性があります。接続を確認して、もう一度お試しください。</string>
<string name="session_end_steam_setup">Steamクライアントをセットアップできませんでした。接続と空き容量を確認して、もう一度お試しください。</string>
<string name="session_end_runtime_driver">選択したLinuxランタイムドライバーが見つからないか、この端末では使用できません。%1$s › %2$sで別のドライバーを選んでから、もう一度開始してください。</string>
<string name="session_end_fex_missing">%1$sはx86 PC向けにビルドされており、FEX経由で実行されますが、FEXはまだインストールされていません。ログインした状態で一度Steamを起動し、FEXとSteam Linux Runtimeをダウンロードしてから、もう一度起動してください。</string>
<string name="add_app_flatpak_hint">FlathubアプリIDまたはそのFlathubページ。Flatpakがまだセットアップされていない場合は、先にセットアップします。</string>
<string name="add_app_file">ファイル</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">이 프로그램</string>
<string name="session_end_steam_download">Steam 클라이언트를 다운로드할 수 없습니다. 네트워크나 VPN이 Steam 서버를 차단하고 있을 수 있습니다. 연결을 확인하고 다시 시도하세요.</string>
<string name="session_end_steam_setup">Steam 클라이언트를 설정할 수 없습니다. 연결과 남은 저장 공간을 확인한 뒤 다시 시도하세요.</string>
<string name="session_end_runtime_driver">선택한 Linux 런타임 드라이버가 없거나 이 휴대폰에서 사용할 수 없습니다. %1$s › %2$s에서 다른 드라이버를 선택한 뒤 다시 시작하세요.</string>
<string name="session_end_fex_missing">%1$s은(는) x86 PC용으로 빌드되어 FEX를 통해 실행되지만, FEX가 아직 설치되지 않았습니다. 로그인한 상태로 Steam을 한 번 시작하여 FEX와 Steam Linux Runtime을 다운로드한 후 다시 시작하세요.</string>
<string name="add_app_flatpak_hint">Flathub 앱 ID 또는 해당 Flathub 페이지입니다. Flatpak이 아직 설정되지 않은 경우 먼저 설정합니다.</string>
<string name="add_app_file">파일</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Program ini</string>
<string name="session_end_steam_download">Tidak dapat memuat turun klien Steam. Rangkaian atau VPN anda mungkin menyekat pelayan Steam; semak sambungan dan cuba lagi.</string>
<string name="session_end_steam_setup">Tidak dapat menyediakan klien Steam. Semak sambungan dan ruang storan kosong, kemudian cuba lagi.</string>
<string name="session_end_runtime_driver">Pemacu masa jalan Linux yang dipilih tiada atau tidak boleh digunakan pada telefon ini. Pilih yang lain di %1$s › %2$s, kemudian mulakan semula.</string>
<string name="session_end_fex_missing">%1$s dibina untuk PC x86 dan berjalan melalui FEX, yang belum dipasang lagi. Mulakan Steam sekali semasa anda log masuk dan biarkan ia memuat turun FEX dan Steam Linux Runtime, kemudian mulakan ini semula.</string>
<string name="add_app_flatpak_hint">ID apl Flathub atau halaman Flathubnya. Flatpak akan disediakan dahulu jika belum lagi.</string>
<string name="add_app_file">Fail</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Dette programmet</string>
<string name="session_end_steam_download">Kunne ikke laste ned Steam-klienten. Nettverket eller VPN-en din blokkerer kanskje Steams servere; sjekk tilkoblingen og prøv igjen.</string>
<string name="session_end_steam_setup">Kunne ikke sette opp Steam-klienten. Sjekk tilkoblingen og ledig lagringsplass, og prøv igjen.</string>
<string name="session_end_runtime_driver">Den valgte Linux-kjøretidsdriveren mangler eller kan ikke brukes på denne telefonen. Velg en annen under %1$s › %2$s, og start på nytt.</string>
<string name="session_end_fex_missing">%1$s er bygget for x86-PC-er og kjører via FEX, som ikke er installert ennå. Start Steam én gang mens du er innlogget, og la den laste ned FEX og Steam Linux Runtime, og start dette på nytt.</string>
<string name="add_app_flatpak_hint">En Flathub-app-ID eller dens Flathub-side. Flatpak settes opp først hvis det ikke allerede er gjort.</string>
<string name="add_app_file">Fil</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Dit programma</string>
<string name="session_end_steam_download">De Steam-client kon niet worden gedownload. Je netwerk of VPN blokkeert mogelijk de servers van Steam; controleer de verbinding en probeer het opnieuw.</string>
<string name="session_end_steam_setup">De Steam-client kon niet worden ingesteld. Controleer de verbinding en de vrije opslag en probeer het opnieuw.</string>
<string name="session_end_runtime_driver">De gekozen Linux-runtimedriver ontbreekt of kan niet worden gebruikt op deze telefoon. Kies een andere onder %1$s › %2$s en start opnieuw.</string>
<string name="session_end_fex_missing">%1$s is gemaakt voor x86-pc’s en draait via FEX, dat nog niet is geïnstalleerd. Start Steam één keer terwijl je bent ingelogd en laat het FEX en de Steam Linux Runtime downloaden. Start dit daarna opnieuw.</string>
<string name="add_app_flatpak_hint">Een Flathub-app-ID of de Flathub-pagina ervan. Flatpak wordt eerst ingesteld als dat nog niet is gebeurd.</string>
<string name="add_app_file">Bestand</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Ten program</string>
<string name="session_end_steam_download">Nie udało się pobrać klienta Steam. Twoja sieć lub VPN może blokować serwery Steam; sprawdź połączenie i spróbuj ponownie.</string>
<string name="session_end_steam_setup">Nie udało się skonfigurować klienta Steam. Sprawdź połączenie i wolne miejsce, a potem spróbuj ponownie.</string>
<string name="session_end_runtime_driver">Wybrany sterownik środowiska Linux nie istnieje lub nie może być używany na tym telefonie. Wybierz inny w %1$s › %2$s, a potem uruchom ponownie.</string>
<string name="session_end_fex_missing">%1$s jest zbudowany dla komputerów x86 i działa przez FEX, który nie jest jeszcze zainstalowany. Uruchom raz Steam po zalogowaniu i pozwól mu pobrać FEX oraz Steam Linux Runtime, a potem uruchom program ponownie.</string>
<string name="add_app_flatpak_hint">ID aplikacji z Flathub lub jej strona na Flathub. Jeśli Flatpak nie jest jeszcze skonfigurowany, zostanie skonfigurowany najpierw.</string>
<string name="add_app_file">Plik</string>
@@ -178,6 +178,7 @@
<string name="session_end_program">Este programa</string>
<string name="session_end_steam_download">Não foi possível transferir o cliente Steam. A sua rede ou VPN pode estar a bloquear os servidores da Steam; verifique a ligação e tente novamente.</string>
<string name="session_end_steam_setup">Não foi possível configurar o cliente Steam. Verifique a ligação e o espaço livre e tente novamente.</string>
<string name="session_end_runtime_driver">O controlador do runtime Linux selecionado está em falta ou não pode ser usado neste telefone. Escolha outro em %1$s › %2$s e inicie novamente.</string>
<string name="session_end_fex_missing">%1$s foi compilado para PCs x86 e é executado através do FEX, que ainda não está instalado. Abra o Steam uma vez com a sessão iniciada e deixe-o transferir o FEX e o Steam Linux Runtime; depois, volte a iniciá-lo.</string>
<string name="add_app_flatpak_hint">Um ID de app do Flathub ou a respetiva página no Flathub. O Flatpak é configurado primeiro, se ainda não estiver.</string>
<string name="add_app_file">Ficheiro</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Este programa</string>
<string name="session_end_steam_download">Não foi possível baixar o cliente Steam. Sua rede ou VPN pode estar bloqueando os servidores da Steam; verifique a conexão e tente novamente.</string>
<string name="session_end_steam_setup">Não foi possível configurar o cliente Steam. Verifique a conexão e o espaço livre e tente novamente.</string>
<string name="session_end_runtime_driver">O driver do runtime Linux selecionado está ausente ou não pode ser usado neste celular. Escolha outro em %1$s › %2$s e inicie novamente.</string>
<string name="session_end_fex_missing">%1$s é feito para PCs x86 e roda pelo FEX, que ainda não está instalado. Abra a Steam uma vez com a sessão iniciada e deixe-a baixar o FEX e o Steam Linux Runtime; depois, abra isto de novo.</string>
<string name="add_app_flatpak_hint">Um ID de app do Flathub ou a página dele no Flathub. O Flatpak é configurado antes, se ainda não estiver.</string>
<string name="add_app_file">Arquivo</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Acest program</string>
<string name="session_end_steam_download">Clientul Steam nu a putut fi descărcat. Rețeaua sau VPN-ul tău poate bloca serverele Steam; verifică conexiunea și încearcă din nou.</string>
<string name="session_end_steam_setup">Clientul Steam nu a putut fi configurat. Verifică conexiunea și spațiul liber, apoi încearcă din nou.</string>
<string name="session_end_runtime_driver">Driverul selectat pentru mediul de execuție Linux lipsește sau nu poate fi folosit pe acest telefon. Alege altul din %1$s › %2$s, apoi pornește din nou.</string>
<string name="session_end_fex_missing">%1$s este compilat pentru PC-uri x86 și rulează prin FEX, care nu este încă instalat. Pornește Steam o dată, fiind autentificat, și lasă-l să descarce FEX și Steam Linux Runtime, apoi pornește din nou acesta.</string>
<string name="add_app_flatpak_hint">Un ID de aplicație Flathub sau pagina sa Flathub. Flatpak este configurat mai întâi, dacă nu este deja.</string>
<string name="add_app_file">Fișier</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Эта программа</string>
<string name="session_end_steam_download">Не удалось скачать клиент Steam. Возможно, ваша сеть или VPN блокирует серверы Steam; проверьте подключение и повторите попытку.</string>
<string name="session_end_steam_setup">Не удалось настроить клиент Steam. Проверьте подключение и свободное место, затем повторите попытку.</string>
<string name="session_end_runtime_driver">Выбранный драйвер среды выполнения Linux отсутствует или не может использоваться на этом телефоне. Выберите другой в разделе %1$s › %2$s и запустите снова.</string>
<string name="session_end_fex_missing">%1$s — сборка для x86-ПК, которая работает через FEX, а он еще не установлен. Запустите Steam один раз, войдя в аккаунт, и дайте ему скачать FEX и Steam Linux Runtime, затем запустите программу снова.</string>
<string name="add_app_flatpak_hint">ID приложения Flathub или ссылка на его страницу. Если Flatpak еще не настроен, сначала будет выполнена его настройка.</string>
<string name="add_app_file">Файл</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Det här programmet</string>
<string name="session_end_steam_download">Det gick inte att ladda ned Steam-klienten. Ditt nätverk eller din VPN kanske blockerar Steams servrar; kontrollera anslutningen och försök igen.</string>
<string name="session_end_steam_setup">Det gick inte att konfigurera Steam-klienten. Kontrollera anslutningen och det lediga lagringsutrymmet och försök igen.</string>
<string name="session_end_runtime_driver">Den valda drivrutinen för Linux-körmiljön saknas eller kan inte användas på den här telefonen. Välj en annan under %1$s › %2$s och starta igen.</string>
<string name="session_end_fex_missing">%1$s är byggt för x86-datorer och körs via FEX, som inte är installerat än. Starta Steam en gång medan du är inloggad och låt det ladda ned FEX och Steam Linux Runtime. Starta sedan detta igen.</string>
<string name="add_app_flatpak_hint">Ett app-ID från Flathub eller appens Flathub-sida. Flatpak konfigureras först om det inte redan är gjort.</string>
<string name="add_app_file">Fil</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">โปรแกรมนี้</string>
<string name="session_end_steam_download">ดาวน์โหลดไคลเอนต์ Steam ไม่ได้ เครือข่ายหรือ VPN ของคุณอาจบล็อกเซิร์ฟเวอร์ของ Steam ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง</string>
<string name="session_end_steam_setup">ตั้งค่าไคลเอนต์ Steam ไม่ได้ ตรวจสอบการเชื่อมต่อและพื้นที่ว่าง แล้วลองอีกครั้ง</string>
<string name="session_end_runtime_driver">ไม่พบไดรเวอร์รันไทม์ Linux ที่เลือก หรือใช้กับโทรศัพท์นี้ไม่ได้ เลือกไดรเวอร์อื่นใน %1$s › %2$s แล้วเริ่มใหม่อีกครั้ง</string>
<string name="session_end_fex_missing">%1$s สร้างมาสำหรับพีซี x86 และรันผ่าน FEX ซึ่งยังไม่ได้ติดตั้ง เริ่ม Steam สักครั้งขณะลงชื่อเข้าใช้และให้ดาวน์โหลด FEX และ Steam Linux Runtime จากนั้นเริ่มโปรแกรมนี้อีกครั้ง</string>
<string name="add_app_flatpak_hint">รหัสแอป Flathub หรือหน้า Flathub ของมัน จะตั้งค่า Flatpak ก่อนหากยังไม่ได้ตั้งค่า</string>
<string name="add_app_file">ไฟล์</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Bu program</string>
<string name="session_end_steam_download">Steam istemcisi indirilemedi. Ağınız veya VPN\'iniz Steam sunucularını engelliyor olabilir; bağlantıyı kontrol edip yeniden deneyin.</string>
<string name="session_end_steam_setup">Steam istemcisi kurulamadı. Bağlantınızı ve boş depolama alanını kontrol edip yeniden deneyin.</string>
<string name="session_end_runtime_driver">Seçilen Linux çalışma ortamı sürücüsü eksik veya bu telefonda kullanılamıyor. %1$s › %2$s bölümünden başka bir sürücü seçip yeniden başlatın.</string>
<string name="session_end_fex_missing">%1$s x86 PC\'ler için derlenmiş ve FEX ile çalışır, ancak FEX henüz yüklü değil. Oturum açmışken Steam\'i bir kez başlatıp FEX\'i ve Steam Linux Runtime\'ı indirmesini bekleyin, ardından bunu yeniden başlatın.</string>
<string name="add_app_flatpak_hint">Bir Flathub uygulama kimliği veya Flathub sayfası. Flatpak henüz kurulu değilse önce o kurulur.</string>
<string name="add_app_file">Dosya</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Ця програма</string>
<string name="session_end_steam_download">Не вдалося завантажити клієнт Steam. Можливо, ваша мережа або VPN блокує сервери Steam; перевірте з’єднання та спробуйте ще раз.</string>
<string name="session_end_steam_setup">Не вдалося налаштувати клієнт Steam. Перевірте з’єднання та вільне місце, потім спробуйте ще раз.</string>
<string name="session_end_runtime_driver">Вибраний драйвер середовища виконання Linux відсутній або не може використовуватися на цьому телефоні. Виберіть інший у розділі %1$s › %2$s і запустіть знову.</string>
<string name="session_end_fex_missing">%1$s зібрано для ПК x86; для запуску потрібен FEX, який ще не встановлено. Один раз запустіть Steam, увійшовши в обліковий запис, дайте йому завантажити FEX і Steam Linux Runtime, а потім запустіть це знову.</string>
<string name="add_app_flatpak_hint">ID додатка Flathub або його сторінка на Flathub. Якщо Flatpak ще не налаштовано, його буде налаштовано спочатку.</string>
<string name="add_app_file">Файл</string>
+1
View File
@@ -178,6 +178,7 @@
<string name="session_end_program">Chương trình này</string>
<string name="session_end_steam_download">Không thể tải xuống client Steam. Mạng hoặc VPN của bạn có thể đang chặn máy chủ Steam; hãy kiểm tra kết nối rồi thử lại.</string>
<string name="session_end_steam_setup">Không thể thiết lập client Steam. Hãy kiểm tra kết nối và dung lượng trống rồi thử lại.</string>
<string name="session_end_runtime_driver">Driver runtime Linux đã chọn bị thiếu hoặc không dùng được trên điện thoại này. Hãy chọn driver khác trong %1$s › %2$s rồi khởi động lại.</string>
<string name="session_end_fex_missing">%1$s được build cho PC x86 và chạy qua FEX, hiện chưa được cài. Khởi động Steam một lần khi đã đăng nhập và để nó tải FEX cùng Steam Linux Runtime, sau đó khởi động lại ứng dụng này.</string>
<string name="add_app_flatpak_hint">Một app ID Flathub hoặc trang Flathub của nó. Flatpak sẽ được thiết lập trước nếu chưa có.</string>
<string name="add_app_file">Tệp</string>
@@ -178,6 +178,7 @@
<string name="session_end_program">此程序</string>
<string name="session_end_steam_download">无法下载 Steam 客户端。你的网络或 VPN 可能屏蔽了 Steam 的服务器;请检查网络连接后重试。</string>
<string name="session_end_steam_setup">无法设置 Steam 客户端。请检查网络连接和可用存储空间,然后重试。</string>
<string name="session_end_runtime_driver">所选的 Linux 运行时驱动缺失或无法在此手机上使用。请在 %1$s › %2$s 中选择其他驱动,然后重新启动。</string>
<string name="session_end_fex_missing">%1$s 面向 x86 PC 构建,需经由 FEX 运行,而 FEX 尚未安装。请在登录状态下启动一次 Steam,让其下载 FEX 与 Steam Linux Runtime,然后重新启动。</string>
<string name="add_app_flatpak_hint">一个 Flathub 应用 ID 或其 Flathub 页面。若尚未配置 Flatpak 会先进行配置。</string>
<string name="add_app_file">文件</string>
@@ -178,6 +178,7 @@
<string name="session_end_program">此程式</string>
<string name="session_end_steam_download">無法下載 Steam 用戶端。你的網絡或 VPN 可能封鎖了 Steam 的伺服器;請檢查連線後再試。</string>
<string name="session_end_steam_setup">無法設定 Steam 用戶端。請檢查連線和可用儲存空間,然後再試。</string>
<string name="session_end_runtime_driver">所選的 Linux 運行環境驅動程式缺失或無法在此手機上使用。請在 %1$s › %2$s 中選擇其他驅動程式,然後重新啟動。</string>
<string name="session_end_fex_missing">%1$s 是為 x86 電腦而設,需透過 FEX 執行,但 FEX 尚未安裝。請在登入狀態下啟動一次 Steam,讓它下載 FEX 和 Steam Linux Runtime,然後再啟動此程式。</string>
<string name="add_app_flatpak_hint">Flathub 應用程式 ID 或其 Flathub 頁面。如尚未設定 Flatpak,會先進行設定。</string>
<string name="add_app_file">檔案</string>
@@ -178,6 +178,7 @@
<string name="session_end_program">此程式</string>
<string name="session_end_steam_download">無法下載 Steam 用戶端。你的網路或 VPN 可能封鎖了 Steam 的伺服器;請檢查連線後再試一次。</string>
<string name="session_end_steam_setup">無法設定 Steam 用戶端。請檢查連線和可用儲存空間,然後再試一次。</string>
<string name="session_end_runtime_driver">所選的 Linux 執行環境驅動程式遺失或無法在這支手機上使用。請在 %1$s › %2$s 中選擇其他驅動程式,然後重新啟動。</string>
<string name="session_end_fex_missing">%1$s 是為 x86 電腦組建的,需透過 FEX 執行,但 FEX 尚未安裝。請在登入狀態下啟動一次 Steam,讓它下載 FEX 和 Steam Linux Runtime,然後再重新啟動此程式。</string>
<string name="add_app_flatpak_hint">Flathub 應用程式 ID 或其 Flathub 頁面。如果尚未設定 Flatpak,會先進行設定。</string>
<string name="add_app_file">檔案</string>
+2
View File
@@ -187,6 +187,7 @@
<string name="session_end_program">This program</string>
<string name="session_end_steam_download">Couldn\'t download the Steam client. Your network or VPN may be blocking Steam\'s servers; check the connection and try again.</string>
<string name="session_end_steam_setup">Couldn\'t set up the Steam client. Check your connection and free storage, then try again.</string>
<string name="session_end_runtime_driver">The selected Linux runtime driver is missing or can\'t be used on this phone. Choose another one under %1$s › %2$s, then start again.</string>
<string name="session_end_fex_missing">%1$s is built for x86 PCs and runs through FEX, which is not installed yet. Start Steam once while signed in and let it download FEX and the Steam Linux Runtime, then start this again.</string>
<string name="add_app_flatpak_hint">A Flathub app ID or its Flathub page. Flatpak is set up first if it is not yet.</string>
<string name="add_app_file">File</string>
@@ -451,6 +452,7 @@
<string name="common_size_mb">%1$.1f MB</string>
<string name="comp_runtime_driver">Runtime driver</string>
<string name="comp_runtime_driver_hint">Used by Steam, games and the desktop. Applies next session.</string>
<string name="drivers_qualcomm_runtime_display">Uses the system display driver</string>
<string name="comp_import_turnip">Import Turnip zip…</string>
<string name="comp_display_driver">Display driver</string>
<string name="comp_display_driver_hint">Draws frames to the screen in both modes. Restart the app to apply.</string>
@@ -0,0 +1,106 @@
package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class QualcommDriverPackageTest {
private val context get() = RuntimeEnvironment.getApplication()
private val id = "v891.7"
private val runtimeId get() = QualcommDriverPackage.runtimeId(id)
private val directory get() = File(TurnipDriver(context).driverPath(id))
@Before fun reset() {
File(context.filesDir, "graphics_driver").deleteRecursively()
context.getSharedPreferences("session", 0).edit().clear().commit()
}
@Test fun previouslyImportedQualcommPackagesAreAvailableWithoutReimporting() {
install()
assertEquals(listOf(runtimeId), QualcommDriverPackage.available(context))
assertTrue(QualcommSystemDriver.handles(runtimeId))
assertTrue(QualcommDriverPackage.label(context, runtimeId).contains(id))
}
@Test fun turnipAndPackagesRequiringANewerAndroidAreExcluded() {
install(vendor = "Mesa")
assertTrue(QualcommDriverPackage.available(context).isEmpty())
install(minApi = 36)
assertTrue(QualcommDriverPackage.available(context).isEmpty())
}
@Test fun mountsKeepTheAndroidLoaderAndBridgeOnTheSameImportedHal() {
install()
elf(File(directory, "libc++.so"))
elf(File(directory, "libllvm-qgl.so"))
elf(File(directory, "libc.so"))
elf(File(directory, "wrong-architecture.so"), arm64 = false)
val binds = QualcommDriverPackage.mounts(context, runtimeId)
assertTrue("${File(directory, "vulkan.ad891.so").path}:${QualcommSystemDriver.HAL}" in binds)
assertTrue("${File(directory, "libc++.so").path}:/system/lib64/libc++.so" in binds)
assertTrue("${File(directory, "libc++.so").path}:/vendor/lib64/libc++.so" in binds)
assertTrue("${File(directory, "libllvm-qgl.so").path}:/vendor/lib64/libllvm-qgl.so" in binds)
assertFalse(binds.any { "wrong-architecture" in it || it.endsWith("/libc.so") })
}
@Test fun deletingTheDisplayPackageAlsoClearsItsLinuxSelection() {
install()
SessionPrefs.setLinuxDriver(context, runtimeId)
SessionPrefs.setAndroidDriver(context, id)
TurnipDriver(context).remove(id)
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals("", SessionPrefs.androidDriver(context))
assertFalse(QualcommDriverPackage.isInstalled(context, runtimeId))
}
@Test fun invalidAndMissingPackagesCannotSilentlyUseTheSystemDriver() {
assertNull(QualcommDriverPackage.importedId("qualcomm-adrenotools:../escape"))
assertNull(QualcommDriverPackage.importedId("qualcomm-adrenotools:/absolute"))
assertNull(QualcommDriverPackage.importedId("qualcomm-adrenotools:a:b"))
assertThrows(QualcommSystemDriver.Unavailable::class.java) { QualcommDriverPackage.mounts(context, runtimeId) }
assertThrows(QualcommSystemDriver.Unavailable::class.java) { LinuxVulkanDriver.resolveIcdPath(context, runtimeId) }
val error = assertThrows(QualcommSystemDriver.Unavailable::class.java) {
QualcommSystemDriver.addEnvironment(context, ArrayList(), runtimeId)
}
assertEquals("The selected Qualcomm AdrenoTools package is missing or incompatible", error.message)
}
@Test fun qualcommSessionsTurnOffTheCompatLayerImageBoundsRewrite() {
val icd = File(context.filesDir, "qualcomm-system/bridge/icd.json")
val environment = QualcommSystemDriver.sessionEnvironment(icd, runtimeId)
assertTrue("HYBRIS_VULKAN_COMPAT_IMAGE_BOUNDS=0" in environment)
assertEquals(1, environment.count { it.startsWith("HYBRIS_VULKAN_COMPAT_IMAGE_BOUNDS=") })
assertTrue("VK_DRIVER_FILES=${icd.path}" in environment)
assertTrue("DROIDDECK_QUALCOMM_DRIVER=$runtimeId" in environment)
}
@Test fun aPhoneWithoutTheQualcommDriverReportsTheSystemDriverUnavailable() {
assertThrows(QualcommSystemDriver.Unavailable::class.java) { QualcommSystemDriver.prepare(context) }
assertThrows(QualcommSystemDriver.Unavailable::class.java) {
LinuxVulkanDriver.resolveIcdPath(context, QualcommSystemDriver.ID)
}
}
private fun install(vendor: String = "Qualcomm", minApi: Int = 28) {
directory.mkdirs()
File(directory, "meta.json").writeText(JSONObject().put("name", id).put("vendor", vendor)
.put("libraryName", "vulkan.ad891.so").put("minApi", minApi).put("driverVersion", "Vulkan 1.4.359").toString())
elf(File(directory, "vulkan.ad891.so"))
}
private fun elf(file: File, arm64: Boolean = true) {
file.writeBytes(ByteArray(20).apply {
this[0] = 0x7f; this[1] = 'E'.code.toByte(); this[2] = 'L'.code.toByte(); this[3] = 'F'.code.toByte()
this[4] = 2; this[5] = 1; this[18] = (if (arm64) 0xb7 else 0x3e).toByte()
})
}
}
@@ -0,0 +1,19 @@
package com.droiddeck.launcher.gpu
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class QualcommSystemDriverTest {
@Test fun detectsTheProprietaryDriverByIdentity() {
assertTrue(QualcommSystemDriver.isQualcomm(mapOf("vendor_id" to "0x5143", "driver_id" to "8")))
assertFalse(QualcommSystemDriver.isQualcomm(mapOf("vendor_id" to "0x5143", "driver_id" to "18", "driver_name" to "Qualcomm")))
assertFalse(QualcommSystemDriver.isQualcomm(mapOf("vendor_id" to "0x13b5", "driver_id" to "8")))
}
@Test fun olderDriverPropertiesRequireAnExplicitVendorName() {
assertTrue(QualcommSystemDriver.isQualcomm(mapOf("vendor_id" to "0x5143", "driver_name" to "Qualcomm Technologies Inc.")))
assertFalse(QualcommSystemDriver.isQualcomm(mapOf("vendor_id" to "0x5143", "driver_name" to "Mesa Turnip")))
assertFalse(QualcommSystemDriver.isQualcomm(mapOf("vendor_id" to "0x5143", "device" to "Adreno 840")))
}
}
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w960dp-h400dp-land")
class GpuDriverControlsVisibilityTest {
@get:Rule val compose = createRobolectricComposeRule()
private var openedSlot: String? = null
@Test fun openingMixedModeRevealsBothDriverButtonsOnAShortScreen() {
show(GPU_MODE_MIX)
assertControlsVisible()
compose.onNodeWithText(text(R.string.gpu_change_display)).performClick()
assertEquals(SLOT_DISPLAY, openedSlot)
}
@Test fun selectingMixedModeRevealsItsControlsBelowTheModeChoices() {
show(GPU_MODE_AUTO)
compose.onNodeWithText(text(R.string.gpu_mode_mix)).performScrollTo().performClick()
assertControlsVisible()
compose.onNodeWithText(text(R.string.gpu_change_runtime)).performClick()
assertEquals(SLOT_RUNTIME, openedSlot)
}
private fun assertControlsVisible() {
compose.onNodeWithText(text(R.string.gpu_change_display)).assertIsDisplayed()
compose.onNodeWithText(text(R.string.gpu_change_runtime)).assertIsDisplayed()
}
private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id)
private fun show(initialMode: String) {
val mode = mutableStateOf(initialMode)
val first = FocusRequester()
val slots = mapOf(SLOT_DISPLAY to FocusRequester(), SLOT_RUNTIME to FocusRequester())
compose.setContent {
DroidDeckTheme {
Box(Modifier.requiredSize(480.dp, 280.dp)) {
GpuDriversBody(
gpu = GpuDriversState(
gpuName = "Adreno 830", gpuFamily = "Adreno 8xx", mode = mode.value,
display = DriverSlot(name = "Automatic", status = "Applies after restarting DroidDeck"),
runtime = DriverSlot(name = "System Qualcomm driver", status = "Applies at the next session start"),
),
actions = GpuDriversActions(onMode = { mode.value = it }),
single = true, first = first, slotFocus = slots,
onOpenSlot = { slot, _ -> openedSlot = slot },
)
}
}
}
}
}
@@ -0,0 +1,193 @@
# Qualcomm system Vulkan driver in DroidDeck
Research date: 2026-10-23. Target: Adreno 840, Vulkan 1.4.295, as shown in the user's device screenshot. The existing `LOGS/my/2026-10-21-03-steam/device.txt` additionally describes a nubia NX809J, SM8850, Android 16/API 36, 4 KiB pages, KGSL, and `/vendor/lib64/hw/vulkan.adreno.so`. Those log details are a candidate baseline; the screenshot alone does not establish the phone model or Qualcomm driver build.
Implementation update, 2026-10-24: imported AdrenoTools Qualcomm packages are now available as Linux runtime choices. The existing v891.7 import passed a GPU transfer/readback probe and rendered Steam/Windows Isaac on the RedMagic 11 Pro; Gamescope and game process maps identify the imported HAL. Its metadata says Vulkan 1.4.359, while the device probe exposes 1.3.351 and driver 0.891.7. See `tools/qualcomm/README.md` for selection, namespace mounts, evidence and limitations.
## Decision
Implement an experimental **System Qualcomm driver** Linux backend using a glibc libhybris ICD that loads the installed Android Vulkan driver. Present through gralloc/native handles and an Android hardware buffer Wayland receiver. Keep the existing Turnip backend selectable. Add imported Qualcomm packages through an explicit driver-selection extension to this bridge after the system-driver path passes validation.
This has credible prior implementation evidence. It does not require recompiling Qualcomm's closed driver, changing the device kernel, or replacing the phone's system graphics stack. Subsequent testing on the connected RedMagic 11 Pro confirmed GPU execution and presentation; see the hardware implementation results below.
My earlier assessment understated both the existing libhybris integration work and the availability of Qualcomm Linux drivers using KGSL. A Linux Qualcomm package must be inspected for its actual kernel interface; assuming all such packages require mainline DRM is incorrect.
## Evidence and route comparison
| Route | Evidence | Remaining DroidDeck work | Priority |
| --- | --- | --- | --- |
| Installed Android Qualcomm driver through libhybris | An Adreno 840 report shows Qualcomm driver 0.842.19, Vulkan 1.4.295, vkcube/vkmark and Zink queries in unrooted Debian PRoot; resizing and GL swapchain failures were also reported | Runtime packaging, Android system-library visibility, Wayland buffer receiver, Gamescope and Proton validation | First |
| Imported Android Qualcomm driver through libhybris selection hooks | AdrenoTools already packages and loads proprietary Qualcomm drivers; bridge support for selecting the same driver throughout is additional work | Adapt namespace/loader selection, dependencies and driver identity checks | Second |
| Native glibc Qualcomm driver plus Mesa WSI wrapper | An existing wrapper reports vkcube/vkmark on Adreno 740 with driver r00026; also reports exit hangs, artifacts and GPU faults | Find an 840-compatible binary, verify KGSL ABI and allocation path, implement suitable WSI | Parallel fallback experiment |
| Android renderer process using Venus/vtest or another command transport | A DroidDeck fork reports Vulkan enumeration and Gamescope initialization on PowerVR | Transport buffer import, synchronization and compatibility, plus Android renderer service | Fallback if in-process bridge cannot load this firmware |
The Adreno report is third-party evidence, not a test on this user's firmware. Its 60 FPS vkmark result was FIFO limited and cannot establish performance relative to Turnip. See [the original device report](https://github.com/Droid-Deck/DroidDeck/issues/165#issuecomment-6086402696). The [native Qualcomm wrapper README](https://github.com/fish4terrisa-MSDSM/mesa-vulkan-wrapper/blob/9658357c332d25cd251d71a0bea440d9d7daf49b/README.md) documents its own limitations. The [Venus investigation](https://github.com/gogetwoo/DroidDeck/blob/pixel-venus/docs/pixel-venus.md) is a fallback reference, not an established Qualcomm solution.
## Recommended architecture
```text
Steam / Linux application / ARM64 Proton WineVulkan / FEX host Vulkan thunk
-> runtime's glibc Khronos Vulkan loader
-> libhybris Vulkan ICD + selected compatibility layers
-> Android system loader for instance initialization
-> selected Qualcomm Android Vulkan HAL for rendering
-> /dev/kgsl-3d0
Linux Wayland presentation
-> bridge-owned swapchain and gralloc/native buffers
-> android_wlegl native handles and file descriptors
-> DroidDeck Android hardware buffer receiver
-> compositor Vulkan import/copy initially
-> Android window / SurfaceFlinger
```
Vulkan rendering stays in the calling ARM64 Linux process. The buffer presentation exchange crosses processes; ordinary draw calls do not need an IPC round trip. TLS/ABI mediation still has overhead, and the existing PRoot overhead remains. There is no measured performance conclusion for this target.
The current [libhybris ICD implementation](https://github.com/taowen/libhybris/blob/2375acd0b5d278a0a2f745c645680545e8f80539/hybris/vulkan/icd/icd.c) loads the HAL in the SP-HAL namespace when appropriate and loads Android's Vulkan loader for instance initialization. Its [instance code](https://github.com/taowen/libhybris/blob/2375acd0b5d278a0a2f745c645680545e8f80539/hybris/vulkan/icd/instance.c) verifies that platform and HAL physical-device query functions agree. This prevents mixing objects from independently selected drivers. Preserve that invariant when adding imported drivers.
Use the normal glibc loader plus an ICD manifest. Avoid globally replacing `libvulkan.so.1` with libhybris's legacy replacement frontend: existing Linux layers, Steam runtime loaders, and FEX need the desktop loader contract. The [Khronos ICD interface](https://github.com/KhronosGroup/Vulkan-Loader/blob/main/docs/LoaderDriverInterface.md) defines negotiation and dispatch responsibilities.
## Existing DroidDeck fork to reuse
The inspected `wallentx/DroidDeck` branch `wallentx/powervr`, revision `c931c4de26339c50f92354b9b06f6fdf7043ca8f`, already contains:
- `tools/hybris/build_runtime.sh`: pinned cross-build, packaged bridge libraries, source/license bundle, manifests and hashes.
- `SystemVulkanDriver.java`: component preparation, ICD and per-process environment setup.
- `wl_android_buffer.c`: `android_wlegl` native-handle receiver using Android hardware buffer import.
- Gamescope/session integration and separate session/game compatibility policies.
Its shipped vendor profiles are PowerVR, Xclipse and Mali. Adding Adreno requires its own capability policy; copying a Mali or PowerVR profile wholesale would enable irrelevant workarounds. The fork's pinned libhybris is `bc8cb3586b79d208fd21b925fa0209b3e432e008`, whereas the independently inspected `arlinux` branch is `2375acd0b5d278a0a2f745c645680545e8f80539`. Audit the differences and choose one reproducible baseline before importing patches; the fork applies patches to its older pin.
Source references: [runtime builder](https://github.com/wallentx/DroidDeck/blob/c931c4de26339c50f92354b9b06f6fdf7043ca8f/tools/hybris/build_runtime.sh), [backend class](https://github.com/wallentx/DroidDeck/blob/c931c4de26339c50f92354b9b06f6fdf7043ca8f/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java), [buffer receiver](https://github.com/wallentx/DroidDeck/blob/c931c4de26339c50f92354b9b06f6fdf7043ca8f/app/src/main/cpp/waylandcomp/src/wl_android_buffer.c).
## Device detection and user selection
The UI should offer the following explicit choices, with probe status alongside the installed driver identity:
| Choice | Meaning |
| --- | --- |
| Auto | Existing device-tested recommendation |
| Turnip | Existing Linux and Android driver selections |
| System Qualcomm driver — experimental | Device's currently installed Qualcomm driver through the Linux bridge |
| Imported Qualcomm driver — experimental | A selected AdrenoTools Qualcomm package through the extended bridge |
Detect through the system Android Vulkan loader before loading a custom driver. Existing `deviceinfo/vkinfo.c` and `gpu/VulkanInfo.kt` already query device/vendor IDs, driver name/info, versions and selected features. Extend the structured result with `VkPhysicalDeviceDriverProperties.driverID`, device/driver UUIDs and raw driverVersion. Prefer `VK_DRIVER_ID_QUALCOMM_PROPRIETARY` where available; vendor ID `0x5143` and an Adreno name alone cannot distinguish Qualcomm's driver from Turnip.
Display the GPU, driver name, driver build, Vulkan version and test result. Do not label Vulkan 1.4.295 as the Qualcomm package version. Record the loaded HAL/library identity separately from the GPU name. Android's loader chooses the actual system driver through HAL/APEX rules; a hard-coded `/vendor` filename is only a candidate for the bridge. See [Android's driver discovery contract](https://source.android.com/docs/core/graphics/implement-vulkan).
Use a short-lived helper process for bridge probes so a native loader/compiler failure cannot kill the launcher. Distinguish **detected**, **bridge loads**, **renders**, **presents**, and **game tested**. Cache success against Android build fingerprint, driver identity, bridge build and selected package hash. An OTA or imported-driver change invalidates it. Probe under the DroidDeck app UID; `adb shell` success does not prove app access.
Persist the backend and package identity for each session. Stop/restart the Linux session to change its driver; the compositor may require its own process restart. Per-game overrides must preserve the backend's complete environment and bridge assets. Snapshot selected component paths for running sessions so updating or deleting a package cannot invalidate their loaded dependencies.
## What AdrenoTools contributes
The upstream [AdrenoTools project](https://github.com/bylaws/libadrenotools) is already vendored in DroidDeck. It loads alternate ARM64 Android drivers without root; its [package format](https://github.com/bylaws/libadrenotools/blob/8fae8ce254dfc1344527e05301e43f37dea2df80/tools/ADPKG.md) explicitly includes proprietary Qualcomm libraries and renamed dependencies. Existing `TurnipDriver.java` accepts an ARM64 Android library named by `meta.json`, rather than enforcing Mesa as its vendor.
Its [loader](https://github.com/bylaws/libadrenotools/blob/8fae8ce254dfc1344527e05301e43f37dea2df80/src/driver.cpp) creates Android namespaces and hooks the system Vulkan loader. That provides driver selection inside an Android process. It does not convert a Bionic binary into a glibc ICD or supply Linux Wayland swapchains.
For imported Qualcomm support, port or adapt its selection mechanism inside the libhybris-controlled Android loading environment. Both Android instance creation and HAL resolution must select the same imported library and dependency set. Merely setting `HYBRIS_VULKAN_HAL` to the imported package while leaving platform instance creation on the system driver violates the bridge's identity check. Removing that check is not a solution.
Keep this integration behind a separate milestone. Loading the existing Android AdrenoTools binary unchanged through libhybris is an experiment, not established compatibility: its linker hooks and namespace objects must belong to the same loader implementation used by the bridge. Alternatively, place AdrenoTools in a native Android renderer service, accepting a command-transport architecture.
DroidDeck's bundled BC enabler is not called by the compositor loader, and its driver-version gating is specific. Do not assume importing a Qualcomm package automatically supplies desktop BC texture support. Query native format support, then enable only a validated native or decoding path.
## Port map in this checkout
| Area | Required change |
| --- | --- |
| `gpu/VulkanInfo.kt`, `deviceinfo/vkinfo.c` | Driver ID, UUID/build identity, complete capability probe and persistent result |
| `gpu/LinuxVulkanDriver.java`, `LinuxVulkanDriverManager.java` | Introduce a backend descriptor distinct from a Turnip ZIP; current import expects `libvulkan_freedreno*.so` and a glibc string |
| `DriverMenus.kt`, `ui/DriverPage.kt`, `session/SessionPrefs.kt` | System/imported Qualcomm choices, status and session restart behavior |
| `runtime/LinuxRuntime.java`, `session/SessionService.kt` | Bridge component paths; Android library/config mounts; select ICD and loader environment |
| `runtime/BwrapSpawner.kt` | Propagate selected bridge and Android dependencies into Flatpak/nested runtime plans; avoid the default Turnip injection |
| `tools/linuxfs/overlay/usr/local/bin/droiddeck-session` | Backend-specific Gamescope/presentation environment and diagnostics |
| `waylandcomp` | Add native-handle receiver, AHB Vulkan import and correct ownership/release behavior |
| Component build/verification pipeline | Build, pin, hash and package bridge sources/libraries/protocols |
The Linux guest currently binds `/dev`, `/proc` and `/sys`; Android paths need an explicit audit. Expose readable host `/system`, `/vendor`, `/odm`, `/system_ext`, `/product`, `/apex`, `/linkerconfig` and property-service data as required by the selected firmware and bridge, including their resolved symlink destinations. PRoot path mappings do not grant extra Android permissions. Do not mix driver dependencies extracted from a different firmware with the installed system driver.
Keep the glibc library search path separate from Android's library search path. The bridge builder uses private RPATHs for its own dependencies; set `HYBRIS_LD_LIBRARY_PATH` for Bionic loading rather than putting Android `libc.so` into glibc `LD_LIBRARY_PATH`.
Audit preload behavior as part of the backend switch. `tools/linuxfs/preload/kgslid.c` currently rewrites reported chip ID `0x44050A21` to `0x44050A31`; a proprietary driver may need the original hardware ID. Disable that translation for the Qualcomm backend unless device evidence establishes a need. Check whether libhybris's ioctl hooks reach the glibc interposer before assuming the rewrite occurs. `LinuxRuntime.java` and `tools/linuxfs/preload/drm.c` also provide a DRM facade over KGSL. That facade is not a real DRM/MSM kernel driver and cannot satisfy arbitrary ioctls expected by a different UMD.
Use the maintained bridge's TLS and namespace fixes. Stock upstream libhybris documentation assumes Android adaptation changes; this fork contains support for unpatched firmware, Bionic static TLS and linker configuration. Validate thread creation, compiler initialization and process exit with the selected API 36 firmware. Late-loading the bridge into a process with a large existing TLS footprint is a separate acceptance case from loading it at startup.
## Buffer presentation and synchronization
The current Android compositor requests dma-buf external-memory and DRM modifier extensions. An Android Qualcomm driver may support AHB import without supporting that raw dma-buf path. A successful `dlopen` therefore does not make the current compositor path compatible.
Initially use the existing fork's `android_wlegl` receiver and AHB import. Preserve full native handles, all FDs, integer metadata, buffer dimensions/stride/format and lifetime. A raw dma-buf FD cannot reconstruct the missing gralloc metadata. DroidDeck's existing `banner_ahb_v1` protocol is another possible transport, but libhybris currently speaks `android_wlegl`; adapting one side is required.
The bridge [swapchain implementation](https://github.com/taowen/libhybris/blob/2375acd0b5d278a0a2f745c645680545e8f80539/hybris/vulkan/icd/swapchain.c) uses Android acquire/release operations. Audit producer completion and compositor release separately. The current Wayland native-handle protocol lacks a per-commit fence channel, so its implementation can wait on release FDs on the host. Begin with correct FIFO behavior. Optimize to explicit fence transport and SurfaceControl only after reuse, resize, surface destruction and GPU effects paths pass.
The screenshot's `VK_KHR_swapchain_mutable_format` is encouraging but does not prove bridge swapchains support the necessary flags and storage usage. In the inspected bridge, `hybris/vulkan/icd/swapchain.c` explicitly rejects any nonzero swapchain creation flags, including mutable format. Supporting that mode requires an actual bridge implementation, not adding an extension name. Query the bridge surface and gralloc-backed image capabilities. If Gamescope cannot write its composition output directly into those images, use an optimal composition image followed by a GPU copy into the presentation image. Validate color channels and sRGB conversion with pixel readbacks; a visible cube alone misses these failures.
## Native Linux Qualcomm route
Qualcomm publishes [Debian packaging for prebuilt Adreno libraries](https://github.com/qualcomm-linux/pkg-adreno). Its [8 Elite Gen 5 announcement](https://www.qualcomm.com/developer/blog/2025/10/same-day-snapdragon-8-elite-gen-5-upstream-linux-support) describes a Vulkan 1.4 UMD with a DRM/MSM stack. A separate [Qualcomm image recipe](https://github.com/qualcomm-linux/meta-qcom-distro/blob/main/recipes-products/images/qcom-multimedia-proprietary-image.bb) includes both qcom-adreno and KGSL. These are distinct integration contexts.
For each candidate package, inspect ELF architecture, DT_NEEDED, GLIBC symbol requirements, exported Vulkan entry points, kernel device/ioctl use, GPU IDs, gralloc/GBM dependencies and redistribution terms. Extract into a private experiment prefix. Test compute/readback before adding WSI. A matching ARM64/glibc ABI does not establish matching KGSL or 840 support.
The inspected Mesa native wrapper uses `WRAPPER_VULKAN_PATH`, defaults to `/opt/qti/usr/lib/libvulkan_adreno.so`, and adds desktop WSI. Its published 740 evidence makes this worth a controlled experiment. It is less suitable as the initial user-facing system-driver option because it substitutes a separate vendor binary rather than using the known installed Android driver.
## Execution gates
| Gate | Experiment and acceptance |
| --- | --- |
| 0. Native identity | Query installed driver in a fresh Android helper; save raw capabilities, build/UUID, feature chains and format support |
| 1. Bridge load | Same driver identity through glibc loader and libhybris; instance/device create/destroy and repeated process exits |
| 2. Rendering | Transfer and compute readbacks; sampled textures; BC formats; multithreaded shader compilation; compare actual pixel values |
| 3. Presentation | Wayland/AHB triangle with RGB and sRGB checks; resize, minimize, surface loss, buffer retirement and release-before-reuse |
| 4. Gamescope | Nested startup without a genuine DRM node; confirm buffer import, storage usage, modifiers and synchronization; copy fallback if required |
| 5. Steam | Zink context creation and Steam UI redraw/scroll/resize; check CEF/ANGLE separately; tolerate a UI-only software fallback if needed |
| 6. Games | Native ARM64 Vulkan, x86-64 through FEX, DXVK, VKD3D-Proton, then 32-bit WoW64 mapping and low-address behavior |
| 7. Product | Selection persistence, driver restart, failed probe recovery, OTA invalidation, nested runtime/Flatpak visibility and logs |
| 8. Performance | Matched resolution/settings, warm caches, repeated runs, frametime percentiles, thermal state, memory and presentation latency against Turnip |
Check DXVK/VKD3D's actual required features for the shipped versions: BC formats, robustness, transform feedback, descriptor indexing, dynamic rendering, timeline synchronization and any shader requirements. A Vulkan version string is insufficient. Apply compatibility layers only where a tested driver needs them; do not expose unimplemented features by name.
FEX's existing Vulkan thunk should reach the ARM64 host loader and bridge, but function coverage and process environment need tests. WoW64 additionally requires suitable low-address mapped memory. VR/effects and ray tracing are later acceptance cases; the screenshot's ray-tracing-maintenance extension alone does not establish complete ray tracing support.
The libhybris repository includes baseline rendering probes and a [WSI runner](https://github.com/taowen/libhybris/blob/2375acd0b5d278a0a2f745c645680545e8f80539/tests/wsi/README.md). Reuse their pixel checks and validation support after adapting the external compositor contract to DroidDeck. Their default endpoint belongs to Arlinux and their X11 path expects TAWC-DRI, so they are not turnkey DroidDeck tests.
## Reproducible research inputs
Inspected local DroidDeck revision: `2e0db5a2cd21c92fd93380478a305a20cce0c203`.
| Source | Inspected revision |
| --- | --- |
| taowen/libhybris, arlinux | `2375acd0b5d278a0a2f745c645680545e8f80539` |
| wallentx/DroidDeck, wallentx/powervr | `c931c4de26339c50f92354b9b06f6fdf7043ca8f` |
| bylaws/libadrenotools | `8fae8ce254dfc1344527e05301e43f37dea2df80` |
| fish4terrisa-MSDSM/mesa-vulkan-wrapper | `9658357c332d25cd251d71a0bea440d9d7daf49b` |
| taowen/arlinux-rootfs | `c092b069c407afa02b14706f650571cea4301f9e` |
Source checkouts and issue snapshots are retained under ignored `build/research/qualcomm/`. The donor APK was inspected as an archive to extract its checksum-pinned Gamescope executable; the donor APK itself was not installed. The modified local DroidDeck development APK was installed into `com.droiddeck.launcher.xr` for hardware tests.
## Hardware implementation results
Connected device: RedMagic 11 Pro, NX809J, Android 16, Adreno 840, installed Qualcomm 0.842.44, Vulkan 1.4.295. The regular DroidDeck application package was not replaced.
Verified on this phone:
- Android driver detection and persistent **System Qualcomm driver** selection in the runtime driver list; selecting it also selects the system display driver.
- Linux `vulkaninfo` identifies the same Qualcomm driver through the glibc libhybris ICD.
- A GPU fill/copy/readback probe verifies 4096 bytes.
- The Android compositor imports an AHardwareBuffer and verifies all 4096 pixels by GPU readback.
- Wayland `vkcube` completes 120 frames.
- An X11 `vkcube` renders visibly through Gamescope, the shared-memory X11 WSI fallback, the libhybris Wayland swapchain and the Android compositor.
- `glxinfo -B` reports accelerated Zink OpenGL 4.6 on the Qualcomm GPU, including with Steam's bundled Vulkan loader.
- Steam Big Picture reaches the app's `READY` state and displays its library. Its browser uses software compositing; Gamescope continues to render on Qualcomm Vulkan.
- The installed Windows version of The Binding of Isaac: Rebirth/Repentance launches through ARM64 Proton, receives focus as app 250900 and renders its intro and a game room. Its process maps contain `/vendor/lib64/hw/vulkan.adreno.so` and the selected libhybris ICD. This is a rendering smoke test, not a full playthrough or performance comparison.
Required integration fixes found by these tests:
1. Bind traversable Android APEX paths even when directory listing is denied. Filtering mounts with `canRead()` excluded Bionic's libc.
2. Advertise dma-buf only when the display driver supports it; use `android_wlegl`/AHB for Qualcomm instead.
3. Use Gamescope's SDL Wayland backend and an offscreen composition/copy fallback for the Android swapchain's supported usage flags.
4. Replace dynamic indexing of YUV sampler arrays with constant-index switches. Qualcomm's compiler otherwise raises SIGTRAP with `constant expression is expected for indexing YUV samplers`. A small Vulkan layer substitutes only the six known Gamescope shader fingerprints, rebuilt from pinned source and the tracked patch; it leaves other shaders alone.
5. Use the vendor-neutral WSI layer's X11 shared-memory path inside Gamescope; the bridge's native X11 backend expects TAWC-DRI, which this Xwayland does not provide.
6. Reserve additional glibc static TLS for late loading in Steam. The diagnostic log identified `libhybris-common.so.1: cannot allocate memory in static TLS block`.
7. Scope `SDL_FRAMEBUFFER_ACCELERATION=0` and the Kopper override to Steam's webhelper through the helper's `taskset` invocation. SDL's accelerated window-surface setup otherwise stalls on the X11 SHM path. This adaptation follows the inspected fork's `droiddeck-steam-taskset` integration.
Broader game coverage, FEX-specific cases, suspend/resume, HDR and performance require separate acceptance. A Gamescope shutdown SIGSEGV has also been observed after its primary child exits. The backend remains explicitly experimental. Source pins, build instructions and probe limitations are in `tools/qualcomm/README.md`; device logs and screenshots are retained under `build/research/qualcomm/`. Successful Steam/game evidence belongs to session `2026-10-23-10-steam`.
+16 -2
View File
@@ -6,7 +6,8 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
fi
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
backend=${BL_GAMESCOPE_BACKEND:-wayland}
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
@@ -20,7 +21,20 @@ unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
export APPIMAGE_EXTRACT_AND_RUN=1
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
if [ "$backend" = sdl ]; then export SDL_VIDEODRIVER=wayland; fi
child_env=(SDL_VIDEODRIVER=x11)
if [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ]; then
export VK_LAYER_PATH="$DROIDDECK_QUALCOMM_ROOT/shaders"
export VK_INSTANCE_LAYERS=VK_LAYER_DROIDDECK_qualcomm_shaders
child_env+=("VK_LAYER_PATH=$DROIDDECK_QUALCOMM_ROOT/wsi:$DROIDDECK_QUALCOMM_ROOT/lib"
VK_INSTANCE_LAYERS=VK_LAYER_window_system_integration:VK_LAYER_HYBRIS_compat WSI_X11_FORCE_SHM=1 DISABLE_GAMESCOPE_WSI=1
"LD_LIBRARY_PATH=$DROIDDECK_QUALCOMM_ROOT/mesa${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
"LIBGL_DRIVERS_PATH=$DROIDDECK_QUALCOMM_ROOT/mesa/dri"
"GBM_BACKENDS_PATH=$DROIDDECK_QUALCOMM_ROOT/mesa/gbm"
__GLX_VENDOR_LIBRARY_NAME=droiddeck_qualcomm
"__EGL_VENDOR_LIBRARY_FILENAMES=$DROIDDECK_QUALCOMM_ROOT/mesa/egl-vendor.json")
fi
"${BL_GAMESCOPE_BINARY:-gamescope}" "${args[@]}" -- /usr/bin/env "${child_env[@]}" /usr/local/bin/droiddeck-gpu-window "$@"
rc=$?
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
exit $rc
+297
View File
@@ -0,0 +1,297 @@
#!/usr/bin/env python3
"""Decide whether this Qualcomm session can present Proton games zero-copy through Gamescope's WSI layer.
Prints one line and exits 0 only when every check passes; anything else keeps games on X11 SHM.
The driver checks start the driver through libhybris, so their result is saved and reused while the driver file,
the selected driver, the bridge build, the layers and this script are unchanged. Gamescope is checked every time.
"""
import ctypes as c
import hashlib
import json
import os
import subprocess
import sys
U = c.c_uint32
H = c.c_void_p
Q = c.c_uint64
REQUIRED = ('VK_KHR_external_memory_fd', 'VK_EXT_external_memory_dma_buf', 'VK_KHR_image_format_list',
'VK_KHR_external_fence_fd')
# The WSI layer implements these at vkCreateDevice without listing them, so only device creation can confirm them.
PRESENT = ('VK_KHR_swapchain', 'VK_EXT_swapchain_maintenance1')
SURFACES = ('VK_KHR_surface', 'VK_KHR_wayland_surface', 'VK_KHR_xcb_surface', 'VK_KHR_xlib_surface',
'VK_KHR_get_surface_capabilities2', 'VK_EXT_surface_maintenance1')
DMA_BUF = 0x200
EXPORTABLE, IMPORTABLE = 0x2, 0x4
B8G8R8A8_UNORM, LINEAR, IMAGE_2D = 44, 1, 1
TRANSFER_SRC, TRANSFER_DST, SAMPLED, COLOR_ATTACHMENT = 0x1, 0x2, 0x4, 0x10
WIDTH = 256
def structure(name, fields):
return type(name, (c.Structure,), {'_fields_': fields})
Application = structure('Application', [('type', U), ('next', H), ('name', c.c_char_p), ('version', U),
('engine', c.c_char_p), ('engineVersion', U), ('api', U)])
Instance = structure('Instance', [('type', U), ('next', H), ('flags', U), ('application', c.POINTER(Application)),
('layerCount', U), ('layers', H), ('extensionCount', U),
('extensions', c.POINTER(c.c_char_p))])
Extension = structure('Extension', [('name', c.c_char * 256), ('version', U)])
Family = structure('Family', [('flags', U), ('count', U), ('timestampBits', U), ('granularity', U * 3)])
QueueCreate = structure('QueueCreate', [('type', U), ('next', H), ('flags', U), ('family', U), ('count', U),
('priorities', c.POINTER(c.c_float))])
DeviceCreate = structure('DeviceCreate', [('type', U), ('next', H), ('flags', U), ('queueCount', U),
('queues', c.POINTER(QueueCreate)), ('layerCount', U), ('layers', H),
('extensionCount', U), ('extensions', c.POINTER(c.c_char_p)),
('features', H)])
Maintenance1 = structure('Maintenance1', [('type', U), ('next', H), ('enabled', U)])
FormatInfo = structure('FormatInfo', [('type', U), ('next', H), ('format', U), ('imageType', U), ('tiling', U),
('usage', U), ('flags', U)])
ExternalInfo = structure('ExternalInfo', [('type', U), ('next', H), ('handle', U)])
ExternalProperties = structure('ExternalProperties', [('type', U), ('next', H), ('features', U), ('exportFrom', U),
('compatible', U)])
FormatProperties = structure('FormatProperties', [('type', U), ('next', H), ('extent', U * 3), ('mipLevels', U),
('arrayLayers', U), ('samples', U), ('maxSize', Q)])
ImageCreate = structure('ImageCreate', [('type', U), ('next', H), ('flags', U), ('imageType', U), ('format', U),
('extent', U * 3), ('mipLevels', U), ('arrayLayers', U), ('samples', U),
('tiling', U), ('usage', U), ('sharing', U), ('familyCount', U),
('families', H), ('layout', U)])
ExternalImage = structure('ExternalImage', [('type', U), ('next', H), ('handles', U)])
Requirements = structure('Requirements', [('size', Q), ('alignment', Q), ('types', U)])
Allocate = structure('Allocate', [('type', U), ('next', H), ('size', Q), ('index', U)])
ExportAllocate = structure('ExportAllocate', [('type', U), ('next', H), ('handles', U)])
Dedicated = structure('Dedicated', [('type', U), ('next', H), ('image', Q), ('buffer', Q)])
GetFd = structure('GetFd', [('type', U), ('next', H), ('memory', Q), ('handle', U)])
Subresource = structure('Subresource', [('aspect', U), ('mip', U), ('layer', U)])
Layout = structure('Layout', [('offset', Q), ('size', Q), ('rowPitch', Q), ('arrayPitch', Q), ('depthPitch', Q)])
def decide(caps):
"""Return (enabled, reasons) for the probed capabilities."""
if caps.get('error'):
return False, ['probe failed: ' + caps['error']]
reasons = ['missing ' + name for name in REQUIRED if name not in caps.get('extensions', ())]
if not reasons:
if not caps.get('linear_export'):
reasons.append('LINEAR DMA-BUF images are not exportable')
if not caps.get('linear_import'):
reasons.append('LINEAR DMA-BUF images are not importable')
if not caps.get('export_fd'):
reasons.append(caps.get('export_error') or 'DMA-BUF export failed')
if not caps.get('gamescope_dmabuf'):
reasons.append('Gamescope offers no linux-dmabuf')
return not reasons, reasons
CACHE_VERSION = 1
CACHE_INPUTS = ('DROIDDECK_QUALCOMM_DRIVER', 'DROIDDECK_QUALCOMM_ROOT', 'VK_ICD_FILENAMES', 'VK_LAYER_PATH',
'VK_INSTANCE_LAYERS')
def cache_path(environ=os.environ):
root = environ.get('XDG_CACHE_HOME') or os.path.join(os.path.expanduser('~'), '.cache')
return os.path.join(root, 'droiddeck', 'qualcomm-caps.json')
def cache_key(environ=os.environ, script=__file__):
"""Fingerprint of everything the driver checks depend on, or None when the driver file cannot be read."""
digest = hashlib.sha256(str(CACHE_VERSION).encode())
try:
for path in (environ.get('HYBRIS_VULKAN_HAL', '/vendor/lib64/hw/vulkan.adreno.so'), script):
with open(path, 'rb') as data:
digest.update(hashlib.sha256(data.read()).digest())
except OSError:
return None
for name in CACHE_INPUTS:
digest.update(b'\0' + environ.get(name, '').encode())
return digest.hexdigest()
def cached_probe(path, key):
"""Return (caps, saved): the saved driver checks for this key, or a new probe saved for the next session."""
if key:
try:
with open(path) as data:
stored = json.load(data)
if stored.get('key') == key:
caps = dict(stored['caps'])
caps['extensions'] = set(caps.get('extensions', ()))
return caps, True
except (OSError, ValueError, KeyError, TypeError, AttributeError):
pass
try:
caps = probe()
except Exception as error:
return {'error': str(error)}, False
if key:
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
temporary = f'{path}.{os.getpid()}'
with open(temporary, 'w') as data:
json.dump({'key': key, 'caps': dict(caps, extensions=sorted(caps.get('extensions', ())))}, data)
os.replace(temporary, path)
except OSError:
pass
return caps, False
def gamescope_dmabuf():
if not os.environ.get('WAYLAND_DISPLAY'):
return False
try:
info = subprocess.run(['wayland-info'], capture_output=True, text=True, timeout=5)
except (OSError, subprocess.TimeoutExpired):
return False
return 'zwp_linux_dmabuf_v1' in info.stdout
def probe():
vk = c.CDLL('libvulkan.so.1')
def function(name, arguments, result=c.c_int):
f = getattr(vk, name)
f.argtypes, f.restype = arguments, result
return f
def check(result, operation):
if result != 0:
raise RuntimeError(f'{operation} returned {result}')
def names(values):
return (c.c_char_p * len(values))(*[value.encode() for value in values])
caps = {}
count = U()
enumerate_instance = function('vkEnumerateInstanceExtensionProperties', [c.c_char_p, c.POINTER(U), H])
check(enumerate_instance(None, c.byref(count), None), 'vkEnumerateInstanceExtensionProperties')
available = (Extension * count.value)()
check(enumerate_instance(None, c.byref(count), available), 'vkEnumerateInstanceExtensionProperties')
surfaces = [name for name in SURFACES if name in {e.name.decode() for e in available}]
application = Application(0, None, b'droiddeck-qualcomm-caps', 1, b'droiddeck', 1, (1 << 22) | (1 << 12))
instance_names = names(surfaces)
instance_info = Instance(1, None, 0, c.pointer(application), 0, None, len(surfaces), instance_names)
instance = H()
check(function('vkCreateInstance', [c.POINTER(Instance), H, c.POINTER(H)])(
c.byref(instance_info), None, c.byref(instance)), 'vkCreateInstance')
try:
devices = (H * 1)()
count = U(1)
result = function('vkEnumeratePhysicalDevices', [H, c.POINTER(U), H])(instance, c.byref(count), devices)
if result not in (0, 5) or count.value == 0:
raise RuntimeError(f'vkEnumeratePhysicalDevices returned {result}')
physical = devices[0]
properties = (c.c_uint8 * 1024)()
function('vkGetPhysicalDeviceProperties', [H, H], None)(physical, properties)
driver = int.from_bytes(bytes(properties[4:8]), 'little')
caps['device'] = bytes(properties[20:276]).split(b'\0')[0].decode(errors='replace')
caps['driver'] = f'{(driver >> 22) & 0x7f}.{(driver >> 12) & 0x3ff}.{driver & 0xfff}'
enumerate_device = function('vkEnumerateDeviceExtensionProperties', [H, c.c_char_p, c.POINTER(U), H])
count = U()
check(enumerate_device(physical, None, c.byref(count), None), 'vkEnumerateDeviceExtensionProperties')
extensions = (Extension * count.value)()
check(enumerate_device(physical, None, c.byref(count), extensions), 'vkEnumerateDeviceExtensionProperties')
caps['extensions'] = {e.name.decode() for e in extensions}
if any(name not in caps['extensions'] for name in REQUIRED):
return caps
format_properties = function('vkGetPhysicalDeviceImageFormatProperties2',
[H, c.POINTER(FormatInfo), c.POINTER(FormatProperties)])
def external_features(usage):
external = ExternalInfo(1000071000, None, DMA_BUF)
info = FormatInfo(1000059004, c.cast(c.pointer(external), H), B8G8R8A8_UNORM, IMAGE_2D, LINEAR, usage, 0)
result = ExternalProperties(1000071001, None, 0, 0, 0)
output = FormatProperties(1000059003, c.cast(c.pointer(result), H))
return result.features if format_properties(physical, c.byref(info), c.byref(output)) == 0 else 0
caps['linear_export'] = bool(external_features(COLOR_ATTACHMENT | TRANSFER_SRC | TRANSFER_DST) & EXPORTABLE)
caps['linear_import'] = bool(external_features(SAMPLED | TRANSFER_SRC) & IMPORTABLE)
families = (Family * 16)()
count = U(16)
function('vkGetPhysicalDeviceQueueFamilyProperties', [H, c.POINTER(U), H], None)(
physical, c.byref(count), families)
family = next((i for i in range(count.value) if families[i].flags & 1), 0)
priority = c.c_float(1.0)
queue = QueueCreate(2, None, 0, family, 1, c.pointer(priority))
maintenance1 = Maintenance1(1000275000, None, 1)
device_names = names(REQUIRED + PRESENT)
device_info = DeviceCreate(3, c.cast(c.pointer(maintenance1), H), 0, 1, c.pointer(queue), 0, None,
len(REQUIRED + PRESENT), device_names, None)
device = H()
result = function('vkCreateDevice', [H, c.POINTER(DeviceCreate), H, c.POINTER(H)])(
physical, c.byref(device_info), None, c.byref(device))
if result != 0:
caps['export_error'] = f'device with the zero-copy extensions failed ({result})'
return caps
try:
caps['export_fd'], caps['export_error'] = export_linear_image(function, device)
finally:
function('vkDestroyDevice', [H, H], None)(device, None)
finally:
function('vkDestroyInstance', [H, H], None)(instance, None)
return caps
def export_linear_image(function, device):
external = ExternalImage(1000072001, None, DMA_BUF)
info = ImageCreate(14, c.cast(c.pointer(external), H), 0, IMAGE_2D, B8G8R8A8_UNORM, (U * 3)(WIDTH, WIDTH, 1),
1, 1, 1, LINEAR, COLOR_ATTACHMENT | TRANSFER_SRC | TRANSFER_DST, 0, 0, None, 0)
image = Q()
result = function('vkCreateImage', [H, c.POINTER(ImageCreate), H, c.POINTER(Q)])(
device, c.byref(info), None, c.byref(image))
if result != 0:
return False, f'LINEAR exportable image creation failed ({result})'
memory = Q()
try:
requirements = Requirements()
function('vkGetImageMemoryRequirements', [H, Q, c.POINTER(Requirements)], None)(
device, image, c.byref(requirements))
if not requirements.types:
return False, 'no memory type for the exportable image'
dedicated = Dedicated(1000127001, None, image.value, 0)
export = ExportAllocate(1000072002, c.cast(c.pointer(dedicated), H), DMA_BUF)
index = (requirements.types & -requirements.types).bit_length() - 1
allocate = Allocate(5, c.cast(c.pointer(export), H), requirements.size, index)
result = function('vkAllocateMemory', [H, c.POINTER(Allocate), H, c.POINTER(Q)])(
device, c.byref(allocate), None, c.byref(memory))
if result != 0:
return False, f'exportable dedicated allocation failed ({result})'
result = function('vkBindImageMemory', [H, Q, Q, Q])(device, image, memory, 0)
if result != 0:
return False, f'binding the exportable image failed ({result})'
layout = Layout()
function('vkGetImageSubresourceLayout', [H, Q, c.POINTER(Subresource), c.POINTER(Layout)], None)(
device, image, c.byref(Subresource(1, 0, 0)), c.byref(layout))
if layout.rowPitch < WIDTH * 4:
return False, f'LINEAR row pitch {layout.rowPitch} is too small'
address = function('vkGetDeviceProcAddr', [H, c.c_char_p], H)(device, b'vkGetMemoryFdKHR')
if not address:
return False, 'vkGetMemoryFdKHR is unavailable'
get_fd = c.CFUNCTYPE(c.c_int, H, c.POINTER(GetFd), c.POINTER(c.c_int))(address)
fd = c.c_int(-1)
result = get_fd(device, c.byref(GetFd(1000074002, None, memory.value, DMA_BUF)), c.byref(fd))
if result != 0 or fd.value < 0:
return False, f'vkGetMemoryFdKHR failed ({result})'
os.close(fd.value)
return True, None
finally:
if memory.value:
function('vkFreeMemory', [H, Q, H], None)(device, memory, None)
function('vkDestroyImage', [H, Q, H], None)(device, image, None)
def main():
caps, saved = cached_probe(cache_path(), cache_key())
caps['gamescope_dmabuf'] = gamescope_dmabuf()
enabled, reasons = decide(caps)
where = f" ({caps['device']}, driver {caps['driver']}{'; driver checks saved earlier' if saved else ''})" \
if caps.get('device') else ''
print(('zero-copy on' if enabled else 'zero-copy off: ' + '; '.join(reasons)) + where)
return 0 if enabled else 1
if __name__ == '__main__':
sys.exit(main())
@@ -75,7 +75,7 @@ run_gamescope() (
status_file=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steam-exit.XXXXXX") || exit 73
trap 'rm -f "$status_file"' EXIT
# Gamescope can return success when its primary child crashed.
BL_STEAM_EXIT_FILE="$status_file" gamescope "$@"
BL_STEAM_EXIT_FILE="$status_file" "${BL_GAMESCOPE_BINARY:-gamescope}" "$@"
compositor_status=$?
if read -r child_status < "$status_file" && [[ $child_status =~ ^[0-9]{1,3}$ ]] \
&& [ "$child_status" -gt 0 ] && [ "$child_status" -le 255 ]; then
@@ -98,6 +98,9 @@ collect_steam_logs() {
fi
}
trap 'collect_steam_logs 2>/dev/null || true' TERM INT HUP
if [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ]; then
echo "== Qualcomm driver source: ${DROIDDECK_QUALCOMM_DRIVER:-system-qualcomm}"
fi
if [ -n "${BL_VK_DRIVER:-}" ]; then
bl_icd_lib=$(sed -n 's/.*"library_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$BL_VK_DRIVER" 2>/dev/null | head -1)
bl_icd_lib=$(printf '%s' "$bl_icd_lib" | sed 's|\\/|/|g')
@@ -231,7 +234,10 @@ if [ -z "${BL_INSIDE:-}" ]; then
if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then
export gamescope_cursor_composite=2
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
backend=${BL_GAMESCOPE_BACKEND:-wayland}
case "$backend" in wayland|sdl) ;; *) echo "Invalid Gamescope backend: $backend"; exit 1 ;; esac
[ "$backend" != sdl ] || export SDL_VIDEODRIVER=wayland
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
args+=(-S stretch)
export BL_STRETCHED=1
@@ -269,7 +275,7 @@ if [ -z "${BL_INSIDE:-}" ]; then
/usr/local/bin/droiddeck-pipewire stop
exit $_bl_status
fi
exec gamescope "${args[@]}" -- "$0" "$mode" "$@"
exec "${BL_GAMESCOPE_BINARY:-gamescope}" "${args[@]}" -- "$0" "$mode" "$@"
fi
bl_displays() {
@@ -285,6 +291,51 @@ bl_xprop_set_all() {
[ "$ok" = 1 ]
}
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
if [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ]; then
export VK_LAYER_PATH="$DROIDDECK_QUALCOMM_ROOT/wsi:$DROIDDECK_QUALCOMM_ROOT/lib"
# The placed-memory layer acts only for devices that ask for VK_EXT_map_memory_placed:
# Wine does for 32-bit games, whose mapped GPU memory must sit below 4 GiB.
export VK_INSTANCE_LAYERS=VK_LAYER_window_system_integration:VK_LAYER_HYBRIS_compat:VK_LAYER_DROIDDECK_placed_memory
export DROIDDECK_EXPERIMENTAL_PLACED_MEMORY=1
export VK_LOADER_DEBUG=error
export WSI_X11_FORCE_SHM=1 DISABLE_GAMESCOPE_WSI=1
. "$DROIDDECK_QUALCOMM_ROOT/mesa/qualcomm-gl.sh"
DROIDDECK_QUALCOMM_ZERO_COPY=0
bl_caps=$(timeout 20 /usr/local/bin/droiddeck-qualcomm-caps 2>/dev/null) && DROIDDECK_QUALCOMM_ZERO_COPY=1
echo "== qualcomm: ${bl_caps:-zero-copy off: the capability probe gave no answer}"
export DROIDDECK_QUALCOMM_ZERO_COPY
unset bl_caps
if [ "${DROIDDECK_WSI_BYPASS_CHECK_MS:-0}" != 0 ]; then
if [ "$DROIDDECK_QUALCOMM_ZERO_COPY" = 1 ]; then
echo "== qualcomm: performance mode: games present through Gamescope's WSI layer, so it applies as in other sessions"
else
echo "== qualcomm: performance mode: only the unpaced release (no frame limit) and Wine's window-check cache;" \
"games present through X11 SHM, so Gamescope's WSI parts (more swapchain images, present-check cache) do not apply"
fi
fi
fi
# Chromium's GPU compositor corrupts the Steam UI on Qualcomm drivers where Zink stops below OpenGL 4.0.
# An explicit BL_STEAM_CEF_SOFTWARE decides instead.
# glxinfo starts the driver through libhybris (up to 15 s), so the version is saved per driver file and bridge build.
bl_qualcomm_browser_gpu() {
[ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ] && [ -z "${BL_STEAM_CEF_SOFTWARE+x}" ] || return 0
local gl hal key= saved_key saved= cache=${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck/qualcomm-gl
# No key, no saved answer: an unreadable driver file is checked every time.
hal=$(sha256sum "${HYBRIS_VULKAN_HAL:-/vendor/lib64/hw/vulkan.adreno.so}" 2>/dev/null) &&
key=$(printf '%s\n' "${hal%% *}" "${DROIDDECK_QUALCOMM_DRIVER:-}" "${DROIDDECK_QUALCOMM_ROOT:-}" | sha256sum | cut -c1-32)
if [ -n "$key" ] && read -r saved_key gl 2>/dev/null < "$cache" && [ "$saved_key" = "$key" ] && [ -n "$gl" ]; then
saved="; saved earlier"
else
gl=$(timeout 15 glxinfo -B 2>/dev/null | sed -n 's/^ *Max core profile version: *\([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1)
[ -z "$gl" ] || [ -z "$key" ] || { mkdir -p "${cache%/*}" && printf '%s %s\n' "$key" "$gl" > "$cache"; } 2>/dev/null
fi
if [ "${gl%%.*}" -ge 4 ] 2>/dev/null; then
echo "== steam: browser GPU compositing on (Zink OpenGL $gl$saved)"
return 0
fi
echo "== steam: browser software compositing (Zink offers OpenGL ${gl:-unknown}$saved; GPU compositing needs 4.0)"
return 1
}
reap_orphans() {
local round p stat pid left
for round in 1 2 3 4 5; do
@@ -382,6 +433,8 @@ case $mode in
steam_x64=0
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
steam_cef_gpu=1
[ "${BL_STEAM_CEF_SOFTWARE:-0}" != 1 ] || steam_cef_gpu=0
bl_qualcomm_browser_gpu || steam_cef_gpu=0
if [ "$steam_x64" = 1 ]; then
step "checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)"
# droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients.
@@ -856,6 +909,11 @@ BUSCONF
# A containerized client re-executes itself through pressure-vessel-wrap (bwrap) unless told it is already inside.
export STEAM_STEAMRT_RECURSION_GUARD=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
bl_steam_path=$PATH
bl_steam_helper=$XDG_DATA_HOME/Steam/steamrtarm64/steamwebhelper
if [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ]; then
bl_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
fi
export SDL_VIDEO_X11_DGAMOUSE=0
decky_loader=$HOME/homebrew/services/PluginLoader
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
@@ -1175,7 +1233,12 @@ BUSCONF
for _d in /proc/[0-9]*; do
{ IFS= read -r -d '' _c && { IFS= read -r -d '' _c1 || _c1=; }; } < "$_d/cmdline" 2>/dev/null || continue
case $_c in FEX|*/FEX|FEXInterpreter|*/FEXInterpreter) _c=$_c1 ;; esac
case $_c in *steamwebhelper*|*steamrtarm64/steam|*steamrt64/steam|*gamescope*) ;; *) continue ;; esac
case $_c in
*steamwebhelper*|*steamrtarm64/steam|*steamrt64/steam) ;;
# Qualcomm sessions copy every frame through X11 SHM inside Gamescope; the client's cores starve it.
*gamescope*) [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" != 1 ] || continue ;;
*) continue ;;
esac
_t=("$_d"/task/*)
_p=${_d#/proc/}
[ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$BL_CLIENT_CPUS" "${_t[@]}" && continue
@@ -1267,6 +1330,7 @@ BUSCONF
desktop_ui_pid=$!
fi
steam_started=$SECONDS
PATH="$bl_steam_path" BL_STEAM_WEBHELPER="$bl_steam_helper" \
"${steam_client[@]}" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
rc=$?
@@ -0,0 +1,18 @@
#!/bin/bash
set -u
if [ "$#" -ge 2 ] && [[ "$1" =~ ^(0[xX])?[0-9a-fA-F]+$ ]] &&
[ -n "${BL_STEAM_WEBHELPER:-}" ] && [ "$2" -ef "$BL_STEAM_WEBHELPER" ]; then
mask=$1
shift
/usr/bin/taskset -p "$mask" "$$" >/dev/null 2>&1 || true
if [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ]; then
# SDL's accelerated window-surface setup stalls on this X11 SHM presentation path.
export SDL_FRAMEBUFFER_ACCELERATION=0
# Valve's helper disables Kopper; Zink needs it to reach the managed X11 WSI layer.
unset LIBGL_KOPPER_DISABLE
# Forced lazy descriptors corrupt CEF render targets on Qualcomm v891.7.
export ZINK_DESCRIPTORS=auto
fi
exec -- "$@"
fi
exec /usr/bin/taskset "$@"
@@ -201,6 +201,16 @@ bl_libpath() {
}
"""
# Qualcomm sessions copy the Steam client's frames through X11 SHM. Games hand Gamescope LINEAR DMA-BUFs only when
# the session's capability probe found DMA-BUF export, so drivers without it keep games on SHM too.
BL_PRESENT_SETUP = """
bl_present() {
[ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ] && [ "${DROIDDECK_QUALCOMM_ZERO_COPY:-0}" = 1 ] &&
[ "${BL_QUALCOMM_SHM:-0}" != 1 ] || return 0
unset DISABLE_GAMESCOPE_WSI WSI_X11_FORCE_SHM
}
"""
BL_IDTECH3_SETUP = """
bl_idtech3() {
BL_EXTRA_ARGS=()
@@ -367,6 +377,7 @@ if [ -n "$depot" ]; then
bl_idtech3 "$@"
bl_vacdiag "$@"
bl_libpath
bl_present
BL_STORE_PROTON="$depot/proton"; export BL_STORE_PROTON
bl_store_launch "$@"
BL_STORE_ARGS=("$@")
@@ -381,7 +392,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_PRESENT_SETUP + BL_STORE_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -422,6 +433,7 @@ bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
bl_libpath
bl_present
BL_STORE_PROTON="$here/%s"; export BL_STORE_PROTON
bl_store_launch "$@"
BL_STORE_ARGS=("$@")
@@ -653,7 +665,7 @@ def adopt_extras(tools):
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_PRESENT_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
+6
View File
@@ -1,5 +1,11 @@
#!/bin/sh
export XDG_SESSION_TYPE=x11
if [ "${DROIDDECK_SYSTEM_QUALCOMM:-0}" = 1 ]; then
export VK_LAYER_PATH="$DROIDDECK_QUALCOMM_ROOT/wsi:$DROIDDECK_QUALCOMM_ROOT/lib"
export VK_INSTANCE_LAYERS=VK_LAYER_window_system_integration:VK_LAYER_HYBRIS_compat
export WSI_X11_FORCE_SHM=1 DISABLE_GAMESCOPE_WSI=1
. "$DROIDDECK_QUALCOMM_ROOT/mesa/qualcomm-gl.sh"
fi
starts=/tmp/droiddeck-mangoapp-starts
now=$(date +%s)
recent=$(awk -v now="$now" '$1 > now - 60' "$starts" 2>/dev/null)
+144
View File
@@ -0,0 +1,144 @@
# Experimental Qualcomm backends
The Linux backend uses the installed Qualcomm Vulkan HAL through a pinned libhybris ICD. The Android compositor imports gralloc buffers through `android_wlegl`. Choosing **System Qualcomm driver** in the runtime driver list also selects the system display driver. Restart the app after changing an already loaded display driver.
## Bridge patch for Android 14 loaders
The bridge creates the Vulkan instance through Android's `libvulkan.so` and then checks that this instance dispatches to the same HAL it loaded itself. Upstream compares only `vkGetPhysicalDeviceProperties`. Android 14's loader wraps that query (seen on an AYANEO Pocket FIT, Adreno 750, Qualcomm 0.762.24, SDK 34): it resolved into `libvulkan.so` while `vkGetPhysicalDeviceFeatures` resolved to the same `vulkan.adreno.so` entry from both sides, so every session failed with `Android instance and configured HAL use different dispatch implementations` and `vkCreateInstance` -9. `hybris-patches/0012-android-loader-wrapped-queries.patch` accepts the instance when any of five core physical-device queries resolves to the HAL's own entry; another driver matches none. `0013-calibrated-timestamps-khr-alias.patch` answers `vkGetPhysicalDeviceCalibrateableTimeDomainsKHR` and `vkGetCalibratedTimestampsKHR` with the HAL's EXT entries when it has only those (same signatures and time-domain values). The same Pocket FIT driver offers only `VK_EXT_calibrated_timestamps`; Zink called the KHR name, the desktop loader found no ICD entry and aborted (`ICD associated with VkPhysicalDevice does not support GetPhysicalDeviceCalibrateableTimeDomainsKHR`), which took down every OpenGL program, including Steam's update window and the browser's `glxinfo` check. `0015-placed-memory-dedicated-export.patch` gives the placed-memory layer a mode for drivers that report OPAQUE_FD export as dedicated-only (Qualcomm). There, external buffers and images bind only to dedicated exported memory and cannot use the cached host-visible type, so the layer's export of every eligible resource broke DXVK (`Failed to bind image memory: VK_ERROR_INVALID_EXTERNAL_HANDLE`). In the new mode resources stay native and each host-visible allocation that is not dedicated already is dedicated to a hidden buffer of its size and exported; the driver binds other resources to it, and the dma-buf mapped at Wine's placed address is coherent with the GPU (tested on the Pocket FIT). Without placed mapping, 32-bit DXVK games failed every map (`Failed to map Vulkan memory: VK_ERROR_OUT_OF_HOST_MEMORY`) because the driver maps above 4 GiB. Qualcomm sessions load the layer with `DROIDDECK_EXPERIMENTAL_PLACED_MEMORY=1`; it acts only for devices that request `VK_EXT_map_memory_placed`. `0014-trim-covered-host-memory-types.patch` stops reporting host-visible flags on memory types that another host-visible type of the same heap strictly contains (Pocket FIT: types 3-5 next to cached coherent type 6). No buffer or image there may use types 3-5 (buffers report 0x41, optimal images 0x1, linear 0x41), but DXVK 2.4 picks the first type with the requested flags and skipped type 6, so every DXVK title failed its first upload allocation (`DxvkMemoryAllocator: Memory allocation failed ... Mem types: 0,6`, then a null read in d3d11.dll). Indices and heaps are unchanged; `HYBRIS_VULKAN_KEEP_MEMORY_TYPES=1` reports the driver's flags. The bridge is rebuilt with wallentx's builder (`tools/hybris` at `4ed93fb9`, patches 0001-0011) plus these patches on DroidDeck-Components.
## Imported AdrenoTools Qualcomm packages
Import a Qualcomm Android driver with **Change display driver → Import an AdrenoTools zip…**. In **Mix and match → Change runtime driver**, select its **Qualcomm (AdrenoTools, experimental)** entry. Previously imported packages appear without reimporting. This selects the package for Linux applications and the system driver for Android presentation. The runtime change applies to the next session; restart DroidDeck if its display driver was already loaded. Changing only the display selection does not change the Linux runtime driver.
Candidates must have `vendor: Qualcomm` metadata, an installed ARM64 library, and a `minApi` no newer than the phone. Mesa/Turnip packages are excluded. The runtime setting uses `qualcomm-adrenotools:<imported-id>`. Deleting the source package clears a matching runtime selection. A selected package that disappears or becomes incompatible outside that removal flow causes an explicit startup error rather than switching drivers silently.
PRoot privately overlays the package HAL at `/vendor/lib64/hw/vulkan.adreno.so` and its ARM64 companion libraries under `/vendor/lib64`. Packaged `libc++.so` is also overlaid at `/system/lib64/libc++.so`: Android's SP-HAL namespace resolves that dependency from system first. These mounts are repeated in nested application sandboxes and use the running session's selection. Android's instance loader and the bridge must resolve the same HAL; passing only an imported path to `HYBRIS_VULKAN_HAL` is insufficient. Android core libraries and its Vulkan loader are not replaced. No device system file is modified.
RedMagic 11 Pro hardware verification on 2026-10-24 used the existing `v891.7` import. Its HAL SHA-256 is `b2c6e92a05d4e6388250f5ec6f94408f2e693cb7fd26274382913ddcb6586108`. Vulkan reports **Qualcomm 0.891.7**, and the GPU fill/copy/readback probe passes. Steam Big Picture reached its library and the installed Windows Isaac rendered through ARM64 Proton. Both Gamescope and the game mapped `graphics_driver/v891.7/vulkan.ad891.so`, its compiler/dependencies and the bridge ICD. The system HAL SHA-256 remained `16acf005480a071af9452f13d8e9bb9930971488d889ea276f87d73616cfd6f5`.
The import's metadata advertises Vulkan **1.4.359**, but this device's Linux Vulkan probe actually reports physical-device API **1.3.351**, including with implicit layers disabled. The package label is not proof of its exposed API on a particular GPU. Driver identity and API support are separate results. Broader compatibility is untested. Evidence is in `build/research/qualcomm/packaged-*`, session `2026-10-24-02-steam`.
## Steam browser hardware-rendering investigation
Games, Gamescope and Android presentation use Vulkan hardware acceleration. Experimental builds also use Steam's regular GPU-enabled browser launch path for both system and imported Qualcomm drivers. This is a shared backend default with no GPU-model allowlist. The helper's `SDL_FRAMEBUFFER_ACCELERATION=0` workaround remains scoped to its SDL window surface; it does not disable Chromium GPU compositing. The Adreno 840 browser verification and remaining limits are described below.
Earlier RedMagic 11 Pro/v891.7 trials on 2026-10-24 failed to produce a stable hardware-rendered Steam UI. They tried ANGLE Vulkan and OpenGL/Zink, explicit Chromium backend switches, removing the in-process GPU switch, and removing the SDL workaround. The browser restarted or exited; logs include command-buffer creation and X11 connection errors. Those trials preceded the private Mesa integration. Evidence remains in ignored `build/research/qualcomm/cef-gpu-*` and `cef-trial-*`, device sessions `2026-10-24-04-steam` through `2026-10-24-08-steam`. Chromium/ANGLE switches are documented in [ANGLE debugging tips](https://github.com/google/angle/blob/main/doc/DebuggingTips.md).
On Adreno 740/Qualcomm 0.676.1, session `2026-10-24-13-steam` enabled the regular browser GPU path with the private Mesa integration and retained the SDL workaround. Steam reached its visible library and the user confirmed faster interaction, then reported UI corruption. Captures show persistent black rectangles obscuring portions of the library. The browser command line lacked `--disable-gpu` and `--disable-gpu-compositing`; its process mapped the Qualcomm HAL, libhybris ICD, private Zink library and Steam's ANGLE libraries, held an open `/dev/kgsl-3d0` descriptor, and did not map SwiftShader. Disabling partial swap in session `2026-10-24-14-steam` did not remove the visible corruption; that flag is not packaged. Investigation was paused at the user's request to prepare an Adreno 840 test APK. This path is experimental and has not passed rendering acceptance. An explicit `BL_STEAM_CEF_SOFTWARE=1` session environment override remains available for diagnosis or fallback.
The GPU path is gated on Zink's OpenGL level. Before Steam starts, `droiddeck-session` reads Zink's maximum core profile version with `glxinfo -B`; below 4.0, or when the version cannot be read, the browser starts with `-cef-disable-gpu` and the log says why, for example `== steam: browser software compositing (Zink offers OpenGL 3.2; GPU compositing needs 4.0)`. Setting `BL_STEAM_CEF_SOFTWARE` to `0` or `1` skips the gate. On the vivo V2243A (Adreno 740, system driver 0.676.1) Zink reaches OpenGL 3.2 and GPU compositing left the library without its background, tabs and parts of covers, with stale regions while moving between items. Software compositing rendered it correctly. Disabling the compat layer's shader rewrites, Zink's render-pass tracking, compact descriptors, threaded GL, Mesa's no-error mode or command reordering, or forcing synchronous Zink flushes, did not change the corruption, and the runtime from before the zero-copy work showed it too. The Adreno 840 with v891.7 reaches OpenGL 4.6 and keeps GPU compositing.
Qualcomm sessions also leave the Steam client CPU affinity unrestricted by default, preserving explicitly saved overrides. The previous SM8550 default pinned Steam, its browser and Gamescope to one core. In Qualcomm sessions the affinity loop applies client masks only to Steam and its browser; other sessions still pin Gamescope with them. A startup recording after that fix showed the complete six-second DroidDeck animation followed by the library; a brief initial white window remained before playback.
### Pixmap binding without DRI3
The subsequent Adreno 840/v891.7 test APK failed during browser startup. Tracing isolated `xcb_dri3_buffer_from_pixmap` from Mesa's Kopper texture-from-pixmap path: the GPU supports DMA-BUF, but the nested X11 server does not advertise DRI3. XCB closed that connection with `XCB_CONN_CLOSED_EXT_NOTSUPPORTED`, causing the later `Fatal IO error 11` in `XGetWindowAttributes`. Gamescope faulted after Steam exited. Disabling GL threading did not help. Forcing ANGLE Vulkan instead failed with `EGL_BAD_CONFIG`.
`zink-pixmap-without-dri3.patch` checks both GPU DMA-BUF capability and the server's DRI3 extension before pixmap import. When import is unavailable, it allocates a normal GPU texture and uses Mesa's existing pixmap pixel-copy update path. Other GPU rendering remains accelerated. No X11 extension or Vulkan capability is fabricated. The check is shared across GPU models and both Qualcomm driver sources.
Verification on RedMagic 11 Pro/Adreno 840 with the imported v891.7 driver:
- `pixmap_probe.c` binds a 17×9 X11 pixmap to a GPU texture, checks two different image contents and verifies all 306 GPU readback pixels on a server without DRI3. The original libraries returned black pixels; the patched libraries pass. Build it with `cc -O2 pixmap_probe.c -o pixmap-probe -lGL -lX11`, then run inside the selected Qualcomm session.
- Steam reaches its visible library, opens its main menu and survives a session restart. Device sessions are `2026-10-24-29-pixmap-probe`, `2026-10-24-30-steam` and `2026-10-24-31-steam`.
- Chromium `SystemInfo.getInfo` reports GPU compositing and rasterization enabled. Its renderer is `ANGLE (Mesa, zink Vulkan 1.3(Adreno (TM) 840 (QUALCOMM_PROPRIETARY)), OpenGL 4.6 (Core Profile) Mesa 26.2.3)`; WebGL independently reports the same hardware path. No software-browser override or tracing preload is used.
Evidence is retained under ignored `build/research/qualcomm/adreno840`. The earlier Adreno 740 corruption requires retesting with this patch; this result does not validate every Adreno model, driver version or game.
### Browser descriptor selection
Opening a game's details and gear menu exposed another Adreno 840/v891.7 failure after startup was fixed: controls were displaced and the menu's backdrop covered only part of the window. Chromium's offscreen screenshot was correct, but the X11 pixmap and displayed frame were corrupt. Apitrace captured both correct and corrupt frames. Disabling GL threading, partial swaps, pipeline optimization or renderpass tracking did not fix it.
The controlled descriptor-mode test reproduced corruption with `ZINK_DESCRIPTORS=lazy` and rendered the same page and menu correctly with `ZINK_DESCRIPTORS=auto` alone (session `2026-10-24-57-steam`). The Qualcomm webhelper branch in `droiddeck-steam-taskset` now selects `auto`. Zink chooses descriptor buffers when its capability checks permit them and otherwise retains its supported fallback. This applies to system and imported Qualcomm sessions without a GPU-model list. It does not establish that drivers which fall back to lazy descriptors are fixed.
The packaged APK was installed and checked without agent environment overrides or tracing preloads in session `2026-10-24-59-steam`. The game page, gear menu and Properties page rendered correctly. The browser's actual process environment contained `ZINK_DESCRIPTORS=auto`; its maps contained the imported v891.7 HAL and private Zink. Chromium reported GPU compositing and rasterization enabled on Adreno 840. Evidence is under `build/research/qualcomm/adreno840`, including `descriptors-auto*`, `nogeneral*` (a failing control), and `packaged-*`. Adreno 740 requires retesting; the underlying lazy-descriptor failure has not been reduced to a standalone Mesa test.
`runtime.json` pins the downloaded bridge and WSI archives, the locally built private Gamescope binary and corresponding source archive, and every private Mesa runtime file. `fetch_runtime.py` checks these pins before Gradle stages them. Missing or mismatched build outputs are downloaded from the pinned `builds` archive, which DroidDeck-Components builds from this tree on ARM64 CI (`tools/qualcomm-runtime`, Arch Linux ARM) and publishes as a `qualcomm-runtime` release. Qualcomm's proprietary device libraries are loaded from the phone and are not included in these archives. The WSI archive is wallentx's release, mirrored unchanged into the same Components release after its SHA-256 and size are checked; `mirrored_from` in `runtime.json` keeps the original URL. The libhybris bridge is rebuilt on DroidDeck-Components (`build-hybris-runtime.yml`) with wallentx's builder at the same revision plus `hybris-patches`; `provenance.previous_build` keeps wallentx's original build. `gamescope.patches` records the patch series the pinned Gamescope was built from, and `tools/tests/test_qualcomm_gamescope_sync.py` fails when a patch in `gamescope-patches` or `tools/gamescope/patches` changes without a rebuild. The bridge archive includes its licenses, source snapshot and patches.
The same lock pins a vendor-neutral X11 WSI layer and upstream Gamescope shader source. `build_shaders.py` applies `constant-yuv-samplers.patch` and builds six replacement SPIR-V modules with the configured NDK's `glslc`. It builds a small ARM64 glibc Vulkan layer using the NDK compiler without Android runtime linkage. The layer matches the six original Gamescope module fingerprints before substituting a shader; ordinary applications use the WSI/compatibility layers instead. Source archives, patches and licenses are packaged with the runtime. The patch can also be applied during a full Gamescope source build.
Qualcomm 0.842.44 traps in its LLVM shader compiler when Gamescope dynamically indexes YUV sampler arrays. The constant-index switch preserves the eight-layer selection. The inner X11 WSI layer uses shared-memory copies; this is a compatibility path with additional CPU and memory-bandwidth cost. Steam additionally needs a larger `glibc.rtld.optional_static_tls` reserve because it loads the Bionic TLS bridge late.
The private Gamescope is built from Valve revision `8f212644c46460549035971ab914421180f61a7c` with the regular DroidDeck patches, the additional patches in `gamescope-patches` (nested SDL swapchain and refresh handling, DMA-BUF import memory types, SHM/cursor presentation), the constant YUV sampler patch, and `gamescope-no-dmabuf.patch`. The additional integration patches were taken from `wallentx/DroidDeck` revision `c931c4de26339c50f92354b9b06f6fdf7043ca8f`. The corresponding source is packaged in the APK. Upstream integration references:
- [DroidDeck fork at the producer revision](https://github.com/wallentx/DroidDeck/tree/af320dd86c7de5738ff16cfeeefbcf42581c199e/tools/gamescope)
- [libhybris runtime builder and patches](https://github.com/wallentx/DroidDeck/tree/4ed93fb9ee6e2a0b24ff087196f2e93d247fd985/tools/hybris)
The Wayland receiver and external-image ownership handling were adapted from `wallentx/DroidDeck` revision `c931c4de26339c50f92354b9b06f6fdf7043ca8f`. The protocol retains its Collabora/libhybris license in `app/src/main/cpp/waylandcomp/protocols/wayland-android.xml`.
## Older Qualcomm capabilities
The connected vivo V2243A/SM8550 reports Adreno 740, proprietary Qualcomm 0.676.1, and physical Vulkan API 1.3.128. It lacks `VK_EXT_external_memory_dma_buf` and `VK_KHR_maintenance5`. The original private Gamescope refused to create a device. The new Gamescope permits missing DMA-BUF only for Vulkan swapchain backends, disables DMA-BUF format advertisement and imports/exports, and uses synchronous SHM uploads. Non-swapchain backends retain their requirement. GPU composition and Android hardware-buffer presentation remain Vulkan operations.
Mesa 26.2.3 made maintenance5 mandatory for Zink. `zink-optional-maintenance5.patch` restores the earlier optional extension check, preserves point-size shader stores without that feature, and omits the maintenance5 buffer-view usage structure when unsupported. The private build uses the same Mesa release as the installed runtime, exposes a distinct GLVND vendor, and includes only Zink as its Gallium driver. `qualcomm-gl.sh` selects its libraries for applications and Mangoapp in Qualcomm sessions. It does not change the Vulkan device's reported features or enable software rendering. This does not establish full OpenGL conformance or game compatibility.
Hardware verification on 2026-10-24 installed the full-runtime development APK and reached the visible Steam Big Picture library on this Adreno 740. Steam and Gamescope mapped `/vendor/lib64/hw/vulkan.adreno.so` through the bridge; Steam also mapped the private GLX vendor and `libgallium-26.2.3.so`. `egl_probe.c` reported **OpenGL 3.2 Compatibility Profile**, rendered a triangle through `zink Vulkan 1.3(Adreno (TM) 740 (QUALCOMM_PROPRIETARY))`, and verified all 256 readback pixels. Evidence is under ignored `build/research/qualcomm/adreno740`, initially device session `2026-10-24-05-steam`, followed by the browser GPU trial described above. Games have not been verified on this phone. The later DRI3 pixmap fix has been verified on Adreno 840 as described above, but not yet on this Adreno 740.
Build the private components on ARM64 Linux with their normal development dependencies (GCC/C++, Meson, Ninja, pkg-config, Wayland/X11/SDL2 headers, Vulkan headers, glslang, and Mesa's Python Mako/packaging/PyYAML, Flex and Bison requirements):
```sh
python3 tools/qualcomm/build_gamescope.py
python3 tools/qualcomm/build_zink.py
python3 tools/qualcomm/build_wsi.py
```
The recipes pin upstream source revisions and retain local outputs under `build/qualcomm-gamescope`, `build/qualcomm-zink/runtime` and `build/qualcomm-wsi`. `build_wsi.py` takes the WSI source from the pinned WSI archive in `build/qualcomm-cache`, so stage it once with `fetch_runtime.py` first. Update `runtime.json` from the produced `build.json` hashes after deliberately rebuilding a component. The APK check verifies the pinned Gamescope, its source archive, WSI files, and private Mesa files alongside the full Linux runtime and all add-on packs. Native build outputs are prerequisites, just like the other prepared runtime components.
## Zero-copy game presentation
Proton games in Qualcomm sessions present through Gamescope's WSI layer instead of X11 shared memory when the driver can export LINEAR DMA-BUFs. The Steam client, its browser and other session programs keep `WSI_X11_FORCE_SHM=1` and `DISABLE_GAMESCOPE_WSI=1`; the Proton wrapper's `bl_present` drops both for the game only when `DROIDDECK_QUALCOMM_ZERO_COPY=1`. Set `BL_QUALCOMM_SHM=1` in the session environment to keep games on the shared-memory path regardless.
`droiddeck-session` sets `DROIDDECK_QUALCOMM_ZERO_COPY` from `droiddeck-qualcomm-caps`, which runs once per session through the bridge ICD and the session's layers, so an imported AdrenoTools driver is judged rather than the system one. Its driver checks are saved in `$XDG_CACHE_HOME/droiddeck/qualcomm-caps.json` and reused while the driver file (by SHA-256), the selected driver, the bridge build, the layers and the script are unchanged; Gamescope's `zwp_linux_dmabuf_v1` is checked every session, and failed probes are never saved. The Steam browser's OpenGL check (`glxinfo -B`) is saved the same way in `qualcomm-gl`. Zero-copy is enabled only when all of these hold:
- The driver offers `VK_KHR_external_memory_fd`, `VK_EXT_external_memory_dma_buf`, `VK_KHR_image_format_list` and `VK_KHR_external_fence_fd`.
- LINEAR `B8G8R8A8_UNORM` images are exportable as DMA-BUF colour attachments and importable as sampled images.
- A device with those extensions, `VK_KHR_swapchain` and `VK_EXT_swapchain_maintenance1` with its feature (which Gamescope's WSI layer forces on) is created through the session's layers, and a LINEAR image's dedicated memory is exported with `vkGetMemoryFdKHR`. The WSI layer implements the swapchain extensions without listing them, so only device creation confirms them.
- Gamescope's Wayland display offers `zwp_linux_dmabuf_v1`.
Any failure, timeout or crash leaves games on SHM. With Performance mode on, the session log also says which of its parts reach games: on SHM only the unpaced release and Wine's window-check cache apply, because Gamescope's WSI layer is not used. The session log records the result, for example `== qualcomm: zero-copy off: missing VK_EXT_external_memory_dma_buf; Gamescope offers no linux-dmabuf (Adreno (TM) 740, driver 0.676.1)`.
The Qualcomm HAL used for development has DMA-BUF export but no `VK_EXT_image_drm_format_modifier`, and Android has no DRM device. The WSI layer is therefore rebuilt with its Wayland backend and `wsi-patches`:
- `0001` allocates swapchain images in the driver as LINEAR images with exportable dedicated memory, exports them with `vkGetMemoryFdKHR`, takes offset and stride from `vkGetImageSubresourceLayout`, and sends them as LINEAR `zwp_linux_dmabuf_v1` buffers. The modifier extension is no longer required at `vkCreateDevice`. X11 DRI3 keeps its previous behavior.
- `0002` removes the `__STDC_VERSION__` workaround that GCC 16 rejects.
- `0003` opens `/dev/dma_heap/system` read-only, the only access Android grants apps.
- `0004` exposes `vkAcquireNextImage2KHR` on Vulkan 1.0 devices; Gamescope's WSI layer acquires every image through it.
- `0005` keeps devices without the Wayland backend's extensions usable. Upstream fails `vkCreateDevice` for any instance that enables `VK_KHR_wayland_surface` (Zink always does) when an extension is missing. Calibrated timestamps are now optional because only present timing uses them. When the remaining requirements are missing, the device is created without them, Wayland surfaces report no presentation support, and swapchain creation on them fails. Other platforms keep the upstream behaviour.
`gamescope-linear-dmabuf.patch` makes the private Gamescope create a version 3 `linux-dmabuf` global without a DRM device (wlroots otherwise creates none), advertise LINEAR beside the implicit layout, and import LINEAR buffers as LINEAR images. Without modifiers the stride cannot be imposed, so an import is refused when the buffer's offset or stride differs from the driver's own LINEAR layout.
Verification on 2026-10-24 used the RedMagic 11 Pro, Adreno 840 and the imported v891.7 driver at 1590x720. `vkcube` (600 frames, uncapped mailbox) went from 131.5 to 198.0 fps; its own CPU time fell from 1.15 s to 0.23 s, Xwayland from 1.64 s to 0.69 s and Gamescope from 6.88 s to 4.00 s. DRAGON BALL: Sparking! ZERO at 60 fps was launched from the same installed APK after a 60-second Steam settle, with only `BL_QUALCOMM_SHM` toggled, and sampled over the same 12-second startup window: Gamescope used 0.35 cores against 0.43 and 0.44 over two shared-memory runs, Xwayland 0.14 against 0.20, and the game 1.28 against 1.21 and 1.22. Average GPU load ranged from 5% to 13% across these runs and does not separate the paths at this phase. The startup logos rendered correctly and the performance overlay hooked DXVK directly. Gamescope's remaining extra cost comes from its SDL backend, the nested-swapchain copy and bridged Vulkan calls. `vkcube` in FIFO mode presented 169.5 fps against a 144 Hz output, so FIFO pacing through this path still needs checking. Native Linux games are not covered by the Proton wrapper.
## Compat-layer image-bounds rewrite
Qualcomm sessions set `HYBRIS_VULKAN_COMPAT_IMAGE_BOUNDS=0`. The bridge's `VK_LAYER_HYBRIS_compat` enables this pass by default, although it ports a Mali+DXVK workaround (Vortek's `removeImageBoundCheck`). After any `OpSampledImage` or `OpImageFetch`, it replaces the zero false operand of the next `OpSelect` with its true operand without checking that the select uses the image result. DXVK writes HLSL comparisons and `step()` as `select(cond, 1.0, 0.0)`, so those collapse to the constant `1.0`.
On RedMagic 11 Pro/Adreno 840 with v891.7, DRAGON BALL: Sparking! ZERO rendered its main-menu scene with a red cast. Replaying the pass over the 479 shaders DXVK compiled up to that menu rewrote 112 of them at 205 selects; 148 of those selects do not depend on any image read. The same scene rendered correctly with only this switch set to `0`, and with every compat shader rewrite disabled. Other compat passes keep their defaults. Evidence is under ignored `build/research/sparking-zero/red2-*`.
## APK packaging
Prepare the normal Linux runtime inputs and all five published add-on packs before compiling. Every APK must support a fresh installation; installed-device runtime reuse is prohibited by `AGENTS.md` and rejected by Gradle.
```powershell
./gradlew.bat -PskipRust=true :app:assembleDebug
```
The build verifies prepared inputs before packaging, then verifies the APK and the add-on pack contents after assembly. Published packs are downloaded on first use using their pinned checksums, as in the normal DroidDeck build. The base Linux root filesystem is downloaded during setup. The package follows `droiddeck.debugApplicationIdSuffix` in `local.properties`.
## Device probes
`probe.py` runs inside the Linux runtime with the bridge ICD selected. It submits a GPU fill and copy, then checks 4 KiB of host-visible readback. It requires Python 3 and the runtime's normal glibc Vulkan loader.
`ahb_probe.c` is an Android NDK program. Pass the newly built `libdroiddeckwayland.so` as its argument, with that library's dependencies on `LD_LIBRARY_PATH`. It allocates and writes an Android hardware buffer, imports it through the compositor's system Qualcomm Vulkan path, and verifies all 4096 converted BGRA pixels by GPU readback.
The two standalone probes do not establish presentation or game compatibility. Additional RedMagic 11 Pro tests confirmed Wayland vkcube presentation, a visible X11 cube through Gamescope, accelerated Zink OpenGL 4.6, Steam Big Picture startup and rendering in the installed Windows version of The Binding of Isaac through ARM64 Proton. Qualcomm 0.842.44, Adreno 840 and Vulkan 1.4.295 were identified under the development app's UID; the game's process maps also contain the Qualcomm HAL and the selected bridge ICD. Steam's browser uses software compositing and its SDL window-surface workaround is scoped to the webhelper. Broader game compatibility and performance remain untested. A Gamescope shutdown SIGSEGV after child exit is still under investigation. Device evidence is retained in `build/research/qualcomm/`, including `isaac-driver-maps.txt`, `isaac-qualcomm.png` and `isaac-menu-qualcomm.png`.
## Credits
- **wallentx** ([wallentx/DroidDeck](https://github.com/wallentx/DroidDeck)) did the libhybris groundwork this backend is built on:
- the libhybris runtime builder and its DroidDeck patches (`tools/hybris` at `4ed93fb9`), and the prebuilt bridge runtime release and component CI that `runtime.json` pins (mirrored unchanged on DroidDeck-Components);
- the prebuilt ARM WSI layer release (`wsi-abe5861.zip`) that the rebuilt layer starts from;
- the system-driver staging approach of `SystemVulkanDriver` (component preparation, ICD manifest and per-process environment) on `wallentx/powervr` at `c931c4de`;
- the `android_wlegl` hardware-buffer receiver and external-image ownership handling;
- the Gamescope and session integration patches (revisions `c931c4de` and `af320dd8`).
- **JeezDisReez** identified the fix for the red graphics in DRAGON BALL: Sparking! ZERO: turning off the compat layer's image-bounds rewrite on Adreno.
- The bridge builds on [libhybris](https://github.com/libhybris/libhybris) and [taowen/libhybris](https://github.com/taowen/libhybris); imported drivers use the AdrenoTools package format from [bylaws/libadrenotools](https://github.com/bylaws/libadrenotools).
+47
View File
@@ -0,0 +1,47 @@
#include <android/hardware_buffer.h>
#include <dlfcn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc != 2) return 2;
void *library = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);
if (!library) { fprintf(stderr, "%s\n", dlerror()); return 3; }
int (*supported)(void) = dlsym(library, "vkp_android_buffer_supported");
void *(*import_buffer)(AHardwareBuffer *) = dlsym(library, "vkp_image_from_android_buffer");
int (*readback)(void *, uint32_t *, int) = dlsym(library, "vkp_image_readback");
void (*destroy)(void *) = dlsym(library, "vkp_image_destroy");
if (!supported || !import_buffer || !readback || !destroy || !supported()) return 4;
AHardwareBuffer_Desc desc = {
.width = 64, .height = 64, .layers = 1, .format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
.usage = AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT,
};
AHardwareBuffer *buffer = NULL;
if (AHardwareBuffer_allocate(&desc, &buffer)) return 5;
AHardwareBuffer_describe(buffer, &desc);
void *pixels = NULL;
if (AHardwareBuffer_lock(buffer, AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY, -1, NULL, &pixels)) return 6;
for (uint32_t y = 0; y < desc.height; y++)
for (uint32_t x = 0; x < desc.width; x++)
((uint32_t *)pixels)[y * desc.stride + x] = 0xff224466u;
if (AHardwareBuffer_unlock(buffer, NULL)) return 7;
void *image = import_buffer(buffer);
if (!image) return 8;
uint32_t result[64 * 64];
int status = readback(image, result, 64 * 64);
if (status < 0) { fprintf(stderr, "Readback failed: %d\n", status); return 9; }
/* vkp_image_readback converts its input to B8G8R8A8_UNORM. */
const uint32_t expected = 0xff664422u;
for (int i = 0; i < 64 * 64; i++) {
if (result[i] != expected) {
fprintf(stderr, "Pixel %d: %#x expected %#x\n", i, result[i], expected);
return 10;
}
}
destroy(image);
AHardwareBuffer_release(buffer);
puts("PASS: Android hardware buffer imported and 4096 pixels read back through the compositor");
return 0;
}
+84
View File
@@ -0,0 +1,84 @@
"""Build the private Qualcomm Gamescope on ARM64 Linux and retain its source."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tarfile
ROOT = Path(__file__).resolve().parents[2]
HERE = Path(__file__).resolve().parent
REVISION = '8f212644c46460549035971ab914421180f61a7c'
OPTIONS = ['-Dbuildtype=release', '-Denable_openvr_support=false',
'-Denable_gamescope_wsi_layer=false', '-Denable_tests=false',
'-Ddrm_backend=enabled', '-Dsdl2_backend=enabled', '-Dpipewire=disabled',
'-Davif_screenshots=disabled', '-Dinput_emulation=disabled', '-Dbenchmark=disabled']
def run(args, cwd=None):
subprocess.run([str(arg) for arg in args], cwd=cwd, check=True)
def patches():
base = ROOT / 'tools/gamescope/patches'
extra = HERE / 'gamescope-patches'
return sorted([*base.glob('*.patch'), *extra.glob('*.patch')], key=lambda p: p.name) + [
HERE / 'constant-yuv-samplers.patch', HERE / 'gamescope-no-dmabuf.patch', HERE / 'gamescope-linear-dmabuf.patch']
def prepare(source):
if source.exists():
raise ValueError('Source directory already exists; use a new directory or --prepared-source')
source.mkdir(parents=True)
run(['git', 'init', source])
run(['git', 'remote', 'add', 'origin', 'https://github.com/ValveSoftware/gamescope.git'], source)
run(['git', 'fetch', '--depth', '1', 'origin', REVISION], source)
run(['git', 'checkout', '--detach', 'FETCH_HEAD'], source)
run(['git', 'submodule', 'update', '--init', '--depth', '1', 'src/reshade',
'subprojects/libliftoff', 'subprojects/vkroots', 'subprojects/wlroots',
'thirdparty/SPIRV-Headers'], source)
for patch in patches():
run(['git', 'apply', '--ignore-whitespace', patch], source)
def archive_source(source, destination):
with destination.open('wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode='w', format=tarfile.PAX_FORMAT) as package:
for path in sorted(source.rglob('*')):
relative = path.relative_to(source)
if any(part in {'.git', 'build', '__pycache__'} for part in relative.parts) or not path.is_file():
continue
info = package.gettarinfo(str(path), arcname='gamescope/' + relative.as_posix())
info.uid = info.gid = info.mtime = 0
info.uname = info.gname = ''
info.mode = 0o755 if path.suffix == '.sh' else 0o644
info.pax_headers = {}
with path.open('rb') as data:
package.addfile(info, data)
def package(source, output, strip_tool='strip'):
output.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / 'build/src/gamescope', output / 'gamescope')
run([strip_tool, '--strip-unneeded', output / 'gamescope'])
archive_source(source, output / 'source.tar.gz')
manifest = {'source_commit': REVISION, 'options': OPTIONS,
'patches': {str(p.relative_to(ROOT)).replace('\\', '/'): hashlib.sha256(p.read_bytes()).hexdigest() for p in patches()},
'files': {name: {'sha256': hashlib.sha256((output / name).read_bytes()).hexdigest(),
'size': (output / name).stat().st_size} for name in ['gamescope', 'source.tar.gz']}}
(output / 'build.json').write_text(json.dumps(manifest, indent=2) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, default=ROOT / 'build/qualcomm-gamescope/source')
parser.add_argument('--output', type=Path, default=ROOT / 'build/qualcomm-gamescope')
parser.add_argument('--prepared-source', action='store_true')
parser.add_argument('--prepare-only', action='store_true')
parser.add_argument('--package-only', action='store_true')
parser.add_argument('--strip', default='strip')
parser.add_argument('--jobs', type=int, default=4)
args = parser.parse_args()
if not args.prepared_source and not args.package_only:
prepare(args.source)
if not args.prepare_only:
if not args.package_only:
run(['meson', 'setup', 'build', *OPTIONS], args.source)
run(['ninja', '-C', 'build', '-j' + str(args.jobs), 'src/gamescope'], args.source)
package(args.source, args.output, args.strip)
+52
View File
@@ -0,0 +1,52 @@
"""Build the Gamescope shader workaround and its ARM64 glibc Vulkan layer."""
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import subprocess
import tarfile
import tempfile
def build(output, archive, lock, ndk):
host = 'windows-x86_64' if os.name == 'nt' else 'darwin-x86_64' if os.uname().sysname == 'Darwin' else 'linux-x86_64'
suffix = '.exe' if os.name == 'nt' else ''
toolchain = ndk / 'toolchains/llvm/prebuilt' / host
compiler = toolchain / ('bin/clang' + suffix)
shader_compiler = ndk / 'shader-tools' / host / ('glslc' + suffix)
here = Path(__file__).resolve().parent
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='qualcomm-shaders-') as temporary:
source = Path(temporary)
with tarfile.open(archive, 'r:gz') as package:
for member in package:
path = PurePosixPath(member.name)
relative = PurePosixPath(*path.parts[1:])
if not member.isfile() or '..' in relative.parts:
continue
if not str(relative).startswith('src/shaders/') and str(relative) != 'LICENSE':
continue
target = source / str(relative)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(package.extractfile(member).read())
patch = here / 'constant-yuv-samplers.patch'
subprocess.run(['git', 'apply', '--check', str(patch)], cwd=source, check=True)
subprocess.run(['git', 'apply', str(patch)], cwd=source, check=True)
for fingerprint, name in lock['replacements'].items():
subprocess.run([str(shader_compiler), str(source / 'src/shaders' / (name + '.comp')),
'-o', str(output / (fingerprint + '.spv'))], check=True)
licenses = output / 'licenses'
licenses.mkdir(exist_ok=True)
shutil.copyfile(source / 'LICENSE', licenses / 'Gamescope-LICENSE')
shutil.copyfile(archive, licenses / 'gamescope-source.tar.gz')
shutil.copyfile(patch, licenses / patch.name)
# Only Vulkan types and opaque libc pointers cross this glibc ABI boundary.
subprocess.run([str(compiler), '--target=aarch64-linux-gnu', '--sysroot=' + str(toolchain / 'sysroot'),
'-I' + str(toolchain / 'sysroot/usr/include/aarch64-linux-android'), '-D__ANDROID_MIN_SDK_VERSION__=26',
'-fuse-ld=lld', '-nostdlib', '-shared', '-fPIC', '-O2', '-fno-stack-protector',
'-Wl,-z,max-page-size=16384', '-Wall', '-Wextra', '-Werror',
str(here / 'shader_layer.c'), '-o', str(output / 'qualcomm-shaders.so')], check=True)
manifest = dict(file_format_version='1.2.0', layer=dict(
name='VK_LAYER_DROIDDECK_qualcomm_shaders', type='GLOBAL', library_path='./qualcomm-shaders.so',
api_version='1.4.0', implementation_version='1', description='Gamescope constant YUV sampler indices for Qualcomm'))
(output / 'VkLayer_DROIDDECK_qualcomm_shaders.json').write_text(json.dumps(manifest) + '\n', encoding='utf-8')
+84
View File
@@ -0,0 +1,84 @@
"""Build the Qualcomm Vulkan WSI layer with Wayland presentation on ARM64 Linux."""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tarfile
import zipfile
ROOT = Path(__file__).resolve().parents[2]
HERE = Path(__file__).resolve().parent
OPTIONS = ['-DCMAKE_BUILD_TYPE=Release', '-DBUILD_WSI_WAYLAND=ON', '-DBUILD_WSI_X11=ON', '-DBUILD_WSI_HEADLESS=OFF',
'-DBUILD_WSI_DISPLAY=OFF', '-DSELECT_EXTERNAL_ALLOCATOR=dma_buf_heaps', '-DWSIALLOC_MEMORY_HEAP_NAME=system']
OUTPUTS = ['libVkLayer_window_system_integration.so', 'VkLayer_window_system_integration.json']
def run(args, cwd=None):
subprocess.run([str(arg) for arg in args], cwd=cwd, check=True)
def patches():
return sorted((HERE / 'wsi-patches').glob('*.patch'), key=lambda p: p.name)
def pinned_archive(cache):
lock = json.loads((HERE / 'runtime.json').read_text())['wsi']
archive = cache / (lock['sha256'] + '.tzst')
if not archive.is_file() or hashlib.sha256(archive.read_bytes()).hexdigest() != lock['sha256']:
raise ValueError('Stage the pinned WSI archive first (tools/qualcomm/fetch_runtime.py): ' + str(archive))
return archive
def prepare(source, cache, zstd):
if source.exists():
raise ValueError('Source directory already exists; use a new directory or --prepared-source')
source.mkdir(parents=True)
with zipfile.ZipFile(pinned_archive(cache)) as package:
packed = package.read('source.tar.zst')
unpacked = subprocess.run([zstd, '-dc'], input=packed, capture_output=True, check=True).stdout
tar_path = source.parent / (source.name + '.tar')
tar_path.write_bytes(unpacked)
try:
with tarfile.open(tar_path) as archive:
archive.extractall(source, filter='data')
finally:
tar_path.unlink()
for patch in patches():
run(['git', '-c', 'core.autocrlf=false', 'apply', '--ignore-whitespace', patch], source)
def package(source, output, strip_tool='strip'):
output.mkdir(parents=True, exist_ok=True)
for name in OUTPUTS:
shutil.copyfile(source / 'build' / name, output / name)
run([strip_tool, '--strip-unneeded', output / OUTPUTS[0]])
for patch in patches():
shutil.copyfile(patch, output / patch.name)
names = OUTPUTS + [patch.name for patch in patches()]
manifest = {'options': OPTIONS,
'files': {name: {'sha256': hashlib.sha256((output / name).read_bytes()).hexdigest(),
'size': (output / name).stat().st_size} for name in names}}
(output / 'build.json').write_text(json.dumps(manifest, indent=2) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, default=ROOT / 'build/qualcomm-wsi/source')
parser.add_argument('--output', type=Path, default=ROOT / 'build/qualcomm-wsi')
parser.add_argument('--cache', type=Path, default=ROOT / 'build/qualcomm-cache')
parser.add_argument('--zstd', default='zstd')
parser.add_argument('--prepared-source', action='store_true')
parser.add_argument('--prepare-only', action='store_true')
parser.add_argument('--package-only', action='store_true')
parser.add_argument('--strip', default='strip')
parser.add_argument('--jobs', type=int, default=4)
args = parser.parse_args()
if not args.prepared_source and not args.package_only:
prepare(args.source, args.cache, args.zstd)
if not args.prepare_only:
if not args.package_only:
run(['cmake', '-S', '.', '-B', 'build', '-G', 'Ninja', *OPTIONS], args.source)
run(['ninja', '-C', 'build', '-j' + str(args.jobs)], args.source)
package(args.source, args.output, args.strip)
+80
View File
@@ -0,0 +1,80 @@
"""Build private ARM64 Zink libraries with Qualcomm and X11 compatibility fixes."""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
ROOT = Path(__file__).resolve().parents[2]
HERE = Path(__file__).resolve().parent
REVISION = '31e9a6b2e95e30d84bf3177d1f497d063e59b6b2'
PATCHES = ('zink-optional-maintenance5.patch', 'zink-pixmap-without-dri3.patch')
OPTIONS = ['-Dbuildtype=release', '-Dgallium-drivers=zink', '-Dvulkan-drivers=[]',
'-Dllvm=disabled', '-Dplatforms=x11,wayland', '-Dglvnd=enabled',
'-Dglvnd-vendor-name=droiddeck_qualcomm', '-Dgallium-va=disabled',
'-Dvideo-codecs=[]', '-Dbuild-tests=false', '-Dtools=[]',
'-Dglx=dri', '-Degl=enabled', '-Dgbm=enabled']
LIBRARIES = {
'libgallium-26.2.3.so': 'src/gallium/targets/dri/libgallium-26.2.3.so',
'dri/zink_dri.so': 'src/gallium/targets/dril/libdril_dri.so',
'libGLX_droiddeck_qualcomm.so.0': 'src/glx/libGLX_droiddeck_qualcomm.so.0.0.0',
'libEGL_droiddeck_qualcomm.so.0': 'src/egl/libEGL_droiddeck_qualcomm.so.0.0.0',
'libgbm.so.1': 'src/gbm/libgbm.so.1.0.0',
'gbm/dri_gbm.so': 'src/gbm/backends/dri/dri_gbm.so',
}
def run(args, cwd=None):
subprocess.run([str(arg) for arg in args], cwd=cwd, check=True)
def prepare(source):
if source.exists():
raise ValueError('Source directory already exists; use a new directory or --prepared-source')
source.mkdir(parents=True)
run(['git', 'init', source])
run(['git', 'remote', 'add', 'origin', 'https://gitlab.freedesktop.org/mesa/mesa.git'], source)
run(['git', 'fetch', '--depth', '1', 'origin', REVISION], source)
run(['git', 'checkout', '--detach', 'FETCH_HEAD'], source)
for patch in PATCHES:
run(['git', 'apply', HERE / patch], source)
def package(source, output, strip_tool):
output.mkdir(parents=True, exist_ok=True)
for name, relative in LIBRARIES.items():
destination = output / name
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / 'build' / relative, destination)
run([strip_tool, '--strip-unneeded', destination])
(output / 'egl-vendor.json').write_text(json.dumps({
'file_format_version': '1.0.0', 'ICD': {'library_path': 'libEGL_droiddeck_qualcomm.so.0'}}) + '\n')
shutil.copyfile(HERE / 'qualcomm-gl.sh', output / 'qualcomm-gl.sh')
shutil.copytree(source / 'licenses', output / 'licenses', dirs_exist_ok=True)
shutil.copyfile(source / 'docs/license.rst', output / 'licenses/Mesa-license.rst')
for patch in PATCHES:
shutil.copyfile(HERE / patch, output / 'licenses' / patch)
(output / 'licenses/source.json').write_text(json.dumps({
'url': 'https://gitlab.freedesktop.org/mesa/mesa/-/tree/' + REVISION,
'source_commit': REVISION, 'options': OPTIONS,
'patches': [{'path': patch, 'sha256': hashlib.sha256((HERE / patch).read_bytes()).hexdigest()}
for patch in PATCHES]}, indent=2) + '\n')
files = [{'path': p.relative_to(output).as_posix(), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest(),
'size': p.stat().st_size} for p in sorted(output.rglob('*')) if p.is_file() and p.name != 'build.json']
(output / 'build.json').write_text(json.dumps({'source_commit': REVISION, 'files': files}, indent=2) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, default=ROOT / 'build/qualcomm-zink/source')
parser.add_argument('--output', type=Path, default=ROOT / 'build/qualcomm-zink/runtime')
parser.add_argument('--prepared-source', action='store_true')
parser.add_argument('--prepare-only', action='store_true')
parser.add_argument('--package-only', action='store_true')
parser.add_argument('--strip', default='strip')
parser.add_argument('--jobs', type=int, default=4)
args = parser.parse_args()
if not args.prepared_source and not args.package_only:
prepare(args.source)
if not args.prepare_only:
if not args.package_only:
run(['meson', 'setup', 'build', *OPTIONS], args.source)
run(['ninja', '-C', 'build', '-j' + str(args.jobs)], args.source)
package(args.source, args.output, args.strip)
+150
View File
@@ -0,0 +1,150 @@
diff --git a/src/shaders/cs_composite_blit.comp b/src/shaders/cs_composite_blit.comp
index 4d974dc..1bf726d 100644
--- a/src/shaders/cs_composite_blit.comp
+++ b/src/shaders/cs_composite_blit.comp
@@ -15,7 +15,19 @@ layout(
vec4 sampleLayer(uint layerIdx, vec2 uv) {
if ((c_ycbcrMask & (1 << layerIdx)) != 0)
- return sampleLayer(s_ycbcr_samplers[layerIdx], layerIdx, uv, false);
+ {
+ switch (layerIdx) {
+ case 0u: return sampleLayer(s_ycbcr_samplers[0], layerIdx, uv, false);
+ case 1u: return sampleLayer(s_ycbcr_samplers[1], layerIdx, uv, false);
+ case 2u: return sampleLayer(s_ycbcr_samplers[2], layerIdx, uv, false);
+ case 3u: return sampleLayer(s_ycbcr_samplers[3], layerIdx, uv, false);
+ case 4u: return sampleLayer(s_ycbcr_samplers[4], layerIdx, uv, false);
+ case 5u: return sampleLayer(s_ycbcr_samplers[5], layerIdx, uv, false);
+ case 6u: return sampleLayer(s_ycbcr_samplers[6], layerIdx, uv, false);
+ case 7u: return sampleLayer(s_ycbcr_samplers[7], layerIdx, uv, false);
+ }
+ return vec4(0.0);
+ }
return sampleLayer(s_samplers[layerIdx], layerIdx, uv, true);
}
diff --git a/src/shaders/cs_composite_blur.comp b/src/shaders/cs_composite_blur.comp
index 318b0e9..d99193b 100644
--- a/src/shaders/cs_composite_blur.comp
+++ b/src/shaders/cs_composite_blur.comp
@@ -18,7 +18,19 @@ layout(
vec4 sampleLayer(uint layerIdx, vec2 uv) {
if ((c_ycbcrMask & (1 << layerIdx)) != 0)
- return sampleLayer(s_ycbcr_samplers[layerIdx], layerIdx, uv, false);
+ {
+ switch (layerIdx) {
+ case 0u: return sampleLayer(s_ycbcr_samplers[0], layerIdx, uv, false);
+ case 1u: return sampleLayer(s_ycbcr_samplers[1], layerIdx, uv, false);
+ case 2u: return sampleLayer(s_ycbcr_samplers[2], layerIdx, uv, false);
+ case 3u: return sampleLayer(s_ycbcr_samplers[3], layerIdx, uv, false);
+ case 4u: return sampleLayer(s_ycbcr_samplers[4], layerIdx, uv, false);
+ case 5u: return sampleLayer(s_ycbcr_samplers[5], layerIdx, uv, false);
+ case 6u: return sampleLayer(s_ycbcr_samplers[6], layerIdx, uv, false);
+ case 7u: return sampleLayer(s_ycbcr_samplers[7], layerIdx, uv, false);
+ }
+ return vec4(0.0);
+ }
return sampleLayer(s_samplers[layerIdx], layerIdx, uv, true);
}
diff --git a/src/shaders/cs_composite_blur_cond.comp b/src/shaders/cs_composite_blur_cond.comp
index 39b0405..28f4e1e 100644
--- a/src/shaders/cs_composite_blur_cond.comp
+++ b/src/shaders/cs_composite_blur_cond.comp
@@ -18,7 +18,19 @@ layout(
vec4 sampleLayer(uint layerIdx, vec2 uv) {
if ((c_ycbcrMask & (1 << layerIdx)) != 0)
- return sampleLayer(s_ycbcr_samplers[layerIdx], layerIdx, uv, false);
+ {
+ switch (layerIdx) {
+ case 0u: return sampleLayer(s_ycbcr_samplers[0], layerIdx, uv, false);
+ case 1u: return sampleLayer(s_ycbcr_samplers[1], layerIdx, uv, false);
+ case 2u: return sampleLayer(s_ycbcr_samplers[2], layerIdx, uv, false);
+ case 3u: return sampleLayer(s_ycbcr_samplers[3], layerIdx, uv, false);
+ case 4u: return sampleLayer(s_ycbcr_samplers[4], layerIdx, uv, false);
+ case 5u: return sampleLayer(s_ycbcr_samplers[5], layerIdx, uv, false);
+ case 6u: return sampleLayer(s_ycbcr_samplers[6], layerIdx, uv, false);
+ case 7u: return sampleLayer(s_ycbcr_samplers[7], layerIdx, uv, false);
+ }
+ return vec4(0.0);
+ }
return sampleLayer(s_samplers[layerIdx], layerIdx, uv, true);
}
diff --git a/src/shaders/cs_composite_rcas.comp b/src/shaders/cs_composite_rcas.comp
index 3caefb1..269d42c 100644
--- a/src/shaders/cs_composite_rcas.comp
+++ b/src/shaders/cs_composite_rcas.comp
@@ -46,7 +46,19 @@ void FsrRcasInputF(inout float r, inout float g, inout float b) {}
vec4 sampleLayer(uint layerIdx, vec2 uv) {
if ((c_ycbcrMask & (1 << layerIdx)) != 0)
- return sampleLayerEx(s_ycbcr_samplers[layerIdx], layerIdx - 1, layerIdx, uv, false);
+ {
+ switch (layerIdx) {
+ case 0u: return sampleLayerEx(s_ycbcr_samplers[0], layerIdx - 1, layerIdx, uv, false);
+ case 1u: return sampleLayerEx(s_ycbcr_samplers[1], layerIdx - 1, layerIdx, uv, false);
+ case 2u: return sampleLayerEx(s_ycbcr_samplers[2], layerIdx - 1, layerIdx, uv, false);
+ case 3u: return sampleLayerEx(s_ycbcr_samplers[3], layerIdx - 1, layerIdx, uv, false);
+ case 4u: return sampleLayerEx(s_ycbcr_samplers[4], layerIdx - 1, layerIdx, uv, false);
+ case 5u: return sampleLayerEx(s_ycbcr_samplers[5], layerIdx - 1, layerIdx, uv, false);
+ case 6u: return sampleLayerEx(s_ycbcr_samplers[6], layerIdx - 1, layerIdx, uv, false);
+ case 7u: return sampleLayerEx(s_ycbcr_samplers[7], layerIdx - 1, layerIdx, uv, false);
+ }
+ return vec4(0.0);
+ }
return sampleLayerEx(s_samplers[layerIdx], layerIdx - 1, layerIdx, uv, true);
}
diff --git a/src/shaders/cs_composite_rcas_1px.comp b/src/shaders/cs_composite_rcas_1px.comp
index 822aa82..8632ddf 100644
--- a/src/shaders/cs_composite_rcas_1px.comp
+++ b/src/shaders/cs_composite_rcas_1px.comp
@@ -46,7 +46,19 @@ void FsrRcasInputF(inout float r, inout float g, inout float b) {}
vec4 sampleLayer(uint layerIdx, vec2 uv) {
if ((c_ycbcrMask & (1 << layerIdx)) != 0)
- return sampleLayerEx(s_ycbcr_samplers[layerIdx], layerIdx - 1, layerIdx, uv, false);
+ {
+ switch (layerIdx) {
+ case 0u: return sampleLayerEx(s_ycbcr_samplers[0], layerIdx - 1, layerIdx, uv, false);
+ case 1u: return sampleLayerEx(s_ycbcr_samplers[1], layerIdx - 1, layerIdx, uv, false);
+ case 2u: return sampleLayerEx(s_ycbcr_samplers[2], layerIdx - 1, layerIdx, uv, false);
+ case 3u: return sampleLayerEx(s_ycbcr_samplers[3], layerIdx - 1, layerIdx, uv, false);
+ case 4u: return sampleLayerEx(s_ycbcr_samplers[4], layerIdx - 1, layerIdx, uv, false);
+ case 5u: return sampleLayerEx(s_ycbcr_samplers[5], layerIdx - 1, layerIdx, uv, false);
+ case 6u: return sampleLayerEx(s_ycbcr_samplers[6], layerIdx - 1, layerIdx, uv, false);
+ case 7u: return sampleLayerEx(s_ycbcr_samplers[7], layerIdx - 1, layerIdx, uv, false);
+ }
+ return vec4(0.0);
+ }
return sampleLayerEx(s_samplers[layerIdx], layerIdx - 1, layerIdx, uv, true);
}
diff --git a/src/shaders/cs_gaussian_blur_horizontal.comp b/src/shaders/cs_gaussian_blur_horizontal.comp
index 2037f1c..3c202bb 100644
--- a/src/shaders/cs_gaussian_blur_horizontal.comp
+++ b/src/shaders/cs_gaussian_blur_horizontal.comp
@@ -51,7 +51,19 @@ void main()
vec4 layerColor;
// YCBCR technically has incorrect blending here but... meh.
if ((c_ycbcrMask & (1 << i)) != 0)
- layerColor = gaussian_blur(s_ycbcr_samplers[i], i, pos, u_blur_radius, false, false);
+ {
+ switch (i) {
+ case 0: layerColor = gaussian_blur(s_ycbcr_samplers[0], i, pos, u_blur_radius, false, false); break;
+ case 1: layerColor = gaussian_blur(s_ycbcr_samplers[1], i, pos, u_blur_radius, false, false); break;
+ case 2: layerColor = gaussian_blur(s_ycbcr_samplers[2], i, pos, u_blur_radius, false, false); break;
+ case 3: layerColor = gaussian_blur(s_ycbcr_samplers[3], i, pos, u_blur_radius, false, false); break;
+ case 4: layerColor = gaussian_blur(s_ycbcr_samplers[4], i, pos, u_blur_radius, false, false); break;
+ case 5: layerColor = gaussian_blur(s_ycbcr_samplers[5], i, pos, u_blur_radius, false, false); break;
+ case 6: layerColor = gaussian_blur(s_ycbcr_samplers[6], i, pos, u_blur_radius, false, false); break;
+ case 7: layerColor = gaussian_blur(s_ycbcr_samplers[7], i, pos, u_blur_radius, false, false); break;
+ default: layerColor = vec4(0.0); break;
+ }
+ }
else
layerColor = gaussian_blur(s_samplers[i], i, pos, u_blur_radius, false, true);
+56
View File
@@ -0,0 +1,56 @@
#include <EGL/egl.h>
#include <GL/gl.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint major, minor, count;
const EGLint attributes[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE };
const EGLint size[] = { EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE };
EGLConfig config;
if (!eglInitialize(display, &major, &minor) || !eglBindAPI(EGL_OPENGL_API) ||
!eglChooseConfig(display, attributes, &config, 1, &count) || count != 1) {
fprintf(stderr, "EGL setup failed: 0x%x\n", eglGetError());
return 1;
}
EGLSurface surface = eglCreatePbufferSurface(display, config, size);
EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT ||
!eglMakeCurrent(display, surface, surface, context)) {
fprintf(stderr, "EGL context failed: 0x%x\n", eglGetError());
return 1;
}
const char *renderer = (const char *)glGetString(GL_RENDERER);
printf("Renderer: %s\nOpenGL: %s\n", renderer, glGetString(GL_VERSION));
if (!renderer || !strstr(renderer, "zink") || !strstr(renderer, "Adreno") ||
strstr(renderer, "llvmpipe")) return 1;
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, 16, 16);
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex2f(-1.0f, -1.0f);
glVertex2f(3.0f, -1.0f);
glVertex2f(-1.0f, 3.0f);
glEnd();
unsigned char pixels[16 * 16 * 4];
memset(pixels, 0, sizeof(pixels));
glReadPixels(0, 0, 16, 16, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
if (glGetError() != GL_NO_ERROR) return 1;
for (unsigned i = 0; i < sizeof(pixels); i += 4) {
if (pixels[i] != 255 || pixels[i + 1] || pixels[i + 2] || pixels[i + 3] != 255) {
fprintf(stderr, "Readback mismatch at pixel %u\n", i / 4);
return 1;
}
}
puts("GPU triangle/readback: all 256 pixels passed");
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(display, context);
eglDestroySurface(display, surface);
eglTerminate(display);
return 0;
}
+161
View File
@@ -0,0 +1,161 @@
"""Stage the checksum-pinned ARM64 glibc bridge, including its corresponding source."""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import tarfile
import urllib.request
import zipfile
def fetch(cache, lock, suffix='.tzst'):
expected = lock['sha256']
cache.mkdir(parents=True, exist_ok=True)
archive = cache / (expected + suffix)
def valid(path):
return path.is_file() and path.stat().st_size == lock['size'] and hashlib.sha256(path.read_bytes()).hexdigest() == expected
if not valid(archive):
temporary = archive.with_suffix('.partial')
try:
with urllib.request.urlopen(lock['url'], timeout=120) as source, temporary.open('wb') as target:
shutil.copyfileobj(source, target)
if not valid(temporary):
raise ValueError('Qualcomm bridge archive failed SHA-256 verification')
temporary.replace(archive)
finally:
temporary.unlink(missing_ok=True)
return archive
def pinned_builds(root, lock):
pins = []
built = lock['gamescope'].get('build')
if built:
pins.append((built['binary'], lock['gamescope']['member_sha256'], None))
pins.append((built['source'], built['source_sha256'], built['source_size']))
if 'mesa' in lock:
pins += [(lock['mesa']['directory'] + '/' + entry['path'], entry['sha256'], entry['size']) for entry in lock['mesa']['files']]
if 'build' in lock.get('wsi', {}):
pins += [(lock['wsi']['build']['directory'] + '/' + entry['name'], entry['sha256'], entry['size'])
for entry in lock['wsi']['files'] if entry.get('built')]
def matches(name, sha256, size):
path = root / name
return path.is_file() and (size is None or path.stat().st_size == size) and hashlib.sha256(path.read_bytes()).hexdigest() == sha256
return all(matches(*pin) for pin in pins)
def unpack_builds(cache, lock):
builds = lock.get('builds')
root = Path(__file__).resolve().parents[2]
if not builds or pinned_builds(root, lock):
return
destination = root / 'build'
with tarfile.open(fetch(cache, builds, '.tar.xz'), 'r:xz') as package:
for member in package.getmembers():
relative = Path(member.name)
if relative.is_absolute() or '..' in relative.parts or not (member.isfile() or member.isdir()):
raise ValueError('Invalid Qualcomm build member: ' + member.name)
if member.isfile():
target = destination / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(package.extractfile(member).read())
if not pinned_builds(root, lock):
raise ValueError('Qualcomm builds failed SHA-256 verification')
def stage(output, cache, lock, ndk=None):
archive = fetch(cache, lock)
output.mkdir(parents=True, exist_ok=True)
shutil.copyfile(archive, output / 'runtime.tzst')
gamescope = lock['gamescope']
built = gamescope.get('build')
if built:
root = Path(__file__).resolve().parents[2]
def build_input(name):
target = (root / built[name]).resolve()
if not target.is_relative_to(root / 'build'):
raise ValueError('Invalid Qualcomm Gamescope build path')
if not target.is_file():
raise FileNotFoundError('Build private Gamescope first with tools/qualcomm/build_gamescope.py: ' + str(target))
return target.read_bytes()
binary = build_input('binary')
source = build_input('source')
if len(source) != built['source_size'] or hashlib.sha256(source).hexdigest() != built['source_sha256']:
raise ValueError('Qualcomm Gamescope source failed SHA-256 verification')
licenses = output / 'licenses'
licenses.mkdir(exist_ok=True)
(licenses / 'gamescope-patched-source.tar.gz').unlink(missing_ok=True)
(licenses / 'gamescope-patched-source.tar.gzip').write_bytes(source)
else:
with zipfile.ZipFile(fetch(cache, gamescope)) as package:
binary = package.read(gamescope['member'])
if hashlib.sha256(binary).hexdigest() != gamescope['member_sha256']:
raise ValueError('Qualcomm Gamescope binary failed SHA-256 verification')
(output / 'gamescope').write_bytes(binary)
if 'mesa' in lock:
root = Path(__file__).resolve().parents[2]
directory = (root / lock['mesa']['directory']).resolve()
if not directory.is_relative_to(root / 'build'):
raise ValueError('Invalid Qualcomm Mesa build path')
for entry in lock['mesa']['files']:
relative = Path(entry['path'])
if relative.is_absolute() or '..' in relative.parts:
raise ValueError('Invalid Qualcomm Mesa destination')
origin = directory / relative
if not origin.is_file():
raise FileNotFoundError('Build private Zink first with tools/qualcomm/build_zink.py: ' + str(origin))
data = origin.read_bytes()
if len(data) != entry['size'] or hashlib.sha256(data).hexdigest() != entry['sha256']:
raise ValueError('Qualcomm Mesa member failed SHA-256 verification: ' + entry['path'])
target = output / 'mesa' / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
if 'wsi' in lock:
built = None
if 'build' in lock['wsi']:
root = Path(__file__).resolve().parents[2]
built = (root / lock['wsi']['build']['directory']).resolve()
if not built.is_relative_to(root / 'build'):
raise ValueError('Invalid Qualcomm WSI build path')
with zipfile.ZipFile(fetch(cache, lock['wsi'])) as package:
for entry in lock['wsi']['files']:
target = Path(entry['path'])
if target.is_absolute() or '..' in target.parts:
raise ValueError('Invalid WSI destination')
if entry.get('built'):
if built is None or Path(entry['name']).name != entry['name']:
raise ValueError('Invalid Qualcomm WSI build member: ' + entry['name'])
origin = built / entry['name']
if not origin.is_file():
raise FileNotFoundError('Build the Qualcomm WSI layer first with tools/qualcomm/build_wsi.py: ' + str(origin))
data = origin.read_bytes()
else:
data = package.read(entry['name'])
if len(data) != entry['size'] or hashlib.sha256(data).hexdigest() != entry['sha256']:
raise ValueError('Qualcomm WSI member failed SHA-256 verification')
destination = output / target
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(data)
if 'shaders' in lock:
if ndk is None:
raise ValueError('The Android NDK is required to build Qualcomm shader compatibility')
from build_shaders import build
build(output / 'shaders', fetch(cache, lock['shaders']), lock['shaders'], ndk)
(output / 'runtime.json').write_text(json.dumps(lock, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path)
parser.add_argument('--cache', type=Path, required=True)
parser.add_argument('--ndk', type=Path)
parser.add_argument('--builds-only', action='store_true')
args = parser.parse_args()
lock = json.loads(Path(__file__).with_name('runtime.json').read_text())
if args.builds_only:
unpack_builds(args.cache, lock)
elif args.output is None or args.ndk is None:
parser.error('--output and --ndk are required')
else:
stage(args.output, args.cache, lock, args.ndk)
@@ -0,0 +1,145 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index 811d80c..5f181a9 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -2245,6 +2245,18 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
assert( drmFormat == pDMA->format );
}
+ // Without DRM format modifiers the stride cannot be imposed, so it must match the driver's own LINEAR layout.
+ const bool bImplicitLinearImport = !g_device.supportsModifiers() && pDMA && pDMA->modifier == DRM_FORMAT_MOD_LINEAR;
+ if ( bImplicitLinearImport )
+ {
+ if ( pDMA->n_planes != 1 )
+ {
+ vk_log.errorf( "LINEAR DMA-BUF import without DRM format modifiers needs a single plane" );
+ return false;
+ }
+ imageInfo.tiling = tiling = VK_IMAGE_TILING_LINEAR;
+ }
+
if ( g_device.supportsModifiers() && pDMA && pDMA->modifier != DRM_FORMAT_MOD_INVALID )
{
VkExternalImageFormatProperties externalImageProperties = {
@@ -2416,7 +2428,22 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
vk_errorf( res, "vkCreateImage failed" );
return false;
}
-
+
+ if ( bImplicitLinearImport )
+ {
+ const VkImageSubresource subresource = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT };
+ VkSubresourceLayout layout = {};
+ g_device.vk.GetImageSubresourceLayout( g_device.device(), m_vkImage, &subresource, &layout );
+ if ( layout.offset != pDMA->offset[0] || layout.rowPitch != pDMA->stride[0] )
+ {
+ vk_log.errorf( "LINEAR DMA-BUF layout (offset %" PRIu32 ", stride %" PRIu32 ") differs from the driver's (offset %" PRIu64 ", stride %" PRIu64 ")",
+ pDMA->offset[0], pDMA->stride[0], uint64_t( layout.offset ), uint64_t( layout.rowPitch ) );
+ g_device.vk.DestroyImage( g_device.device(), m_vkImage, nullptr );
+ m_vkImage = VK_NULL_HANDLE;
+ return false;
+ }
+ }
+
VkMemoryRequirements memRequirements;
g_device.vk.GetImageMemoryRequirements(g_device.device(), m_vkImage, &memRequirements);
@@ -2963,6 +2990,27 @@ static bool is_image_format_modifier_supported(VkFormat format, uint32_t drmForm
return res == VK_SUCCESS;
}
+static bool is_linear_dmabuf_importable( VkPhysicalDeviceImageFormatInfo2 imageFormatInfo )
+{
+ VkPhysicalDeviceExternalImageFormatInfo externalInfo = {
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
+ .pNext = imageFormatInfo.pNext,
+ .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,
+ };
+ imageFormatInfo.pNext = &externalInfo;
+ imageFormatInfo.tiling = VK_IMAGE_TILING_LINEAR;
+
+ VkExternalImageFormatProperties externalProps = {
+ .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES,
+ };
+ VkImageFormatProperties2 props = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
+ .pNext = &externalProps,
+ };
+ return g_device.vk.GetPhysicalDeviceImageFormatProperties2( g_device.physDev(), &imageFormatInfo, &props ) == VK_SUCCESS &&
+ ( externalProps.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT ) != 0;
+}
+
bool vulkan_init_format(VkFormat format, uint32_t drmFormat)
{
// First, check whether the Vulkan format is supported
@@ -3071,6 +3119,8 @@ bool vulkan_init_format(VkFormat format, uint32_t drmFormat)
return false;
wlr_drm_format_set_add( &sampledDRMFormats, drmFormat, DRM_FORMAT_MOD_INVALID );
+ if ( is_linear_dmabuf_importable( imageFormatInfo ) )
+ wlr_drm_format_set_add( &sampledDRMFormats, drmFormat, DRM_FORMAT_MOD_LINEAR );
return false;
}
}
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 618794b..2f30851 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -40,6 +40,7 @@
#include <wlr/types/wlr_seat.h>
#include <wlr/types/wlr_touch.h>
#include <wlr/types/wlr_drm.h>
+#include <wlr/types/wlr_linux_dmabuf_v1.h>
#include <wlr/util/log.h>
#include <wlr/xwayland/server.h>
#include <wlr/types/wlr_xdg_shell.h>
@@ -2216,6 +2217,25 @@ bool wlserver_init( void ) {
wlr_renderer_init_wl_display(wlserver.wlr.renderer, wlserver.display);
+ // wlroots only creates linux-dmabuf for renderers with a DRM device, and Android exposes none.
+ const wlr_drm_format_set *pDmabufFormats = wlr_renderer_get_texture_formats( wlserver.wlr.renderer, WLR_BUFFER_CAP_DMABUF );
+ if ( wlr_renderer_get_drm_fd( wlserver.wlr.renderer ) < 0 && pDmabufFormats != nullptr && pDmabufFormats->len > 0 )
+ {
+ wlr_linux_dmabuf_feedback_v1 feedback = {};
+ wl_array_init( &feedback.tranches );
+ wlr_linux_dmabuf_feedback_v1_tranche *pTranche = wlr_linux_dmabuf_feedback_add_tranche( &feedback );
+ bool bFormatsCopied = pTranche != nullptr;
+ for ( size_t i = 0; bFormatsCopied && i < pDmabufFormats->len; i++ )
+ {
+ const wlr_drm_format &format = pDmabufFormats->formats[ i ];
+ for ( size_t j = 0; bFormatsCopied && j < format.len; j++ )
+ bFormatsCopied = wlr_drm_format_set_add( &pTranche->formats, format.format, format.modifiers[ j ] );
+ }
+ if ( !bFormatsCopied || !wlr_linux_dmabuf_v1_create( wlserver.display, 3, &feedback ) )
+ wl_log.errorf( "Failed to create linux-dmabuf without a DRM device" );
+ wlr_linux_dmabuf_feedback_v1_finish( &feedback );
+ }
+
wlserver.wlr.compositor = wlr_compositor_create(wlserver.display, 5, wlserver.wlr.renderer);
wl_signal_add( &wlserver.wlr.compositor->events.new_surface, &new_surface_listener );
diff --git a/subprojects/wlroots/types/wlr_linux_dmabuf_v1.c b/subprojects/wlroots/types/wlr_linux_dmabuf_v1.c
index 0dc42f4..5bc9b74 100644
--- a/subprojects/wlroots/types/wlr_linux_dmabuf_v1.c
+++ b/subprojects/wlroots/types/wlr_linux_dmabuf_v1.c
@@ -892,13 +892,13 @@ static bool set_default_feedback(struct wlr_linux_dmabuf_v1 *linux_dmabuf,
}
drmDevice *device = NULL;
- if (drmGetDeviceFromDevId(feedback->main_device, 0, &device) != 0) {
+ int main_device_fd = -1;
+ if (feedback->main_device == 0) {
+ wlr_log(WLR_DEBUG, "No DRM device, skipping DMA-BUF import checks");
+ } else if (drmGetDeviceFromDevId(feedback->main_device, 0, &device) != 0) {
wlr_log_errno(WLR_ERROR, "drmGetDeviceFromDevId failed");
goto error_compiled;
- }
-
- int main_device_fd = -1;
- if (device->available_nodes & (1 << DRM_NODE_RENDER)) {
+ } else if (device->available_nodes & (1 << DRM_NODE_RENDER)) {
const char *name = device->nodes[DRM_NODE_RENDER];
main_device_fd = open(name, O_RDWR | O_CLOEXEC);
drmFreeDevice(&device);
+124
View File
@@ -0,0 +1,124 @@
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -866,6 +866,7 @@
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
inline int drmRenderFd() {return m_drmRendererFd;}
inline bool supportsModifiers() {return m_bSupportsModifiers;}
+ inline bool supportsDmaBuf() {return m_bSupportsDmaBuf;}
inline uint32_t vendorID() const {return m_uVendorID;}
inline const VkPhysicalDeviceMemoryProperties &memoryProperties() const {return m_memoryProperties;}
inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
@@ -938,6 +939,7 @@
uint32_t m_uVendorID = 0;
bool m_bHasDrmPrimaryDevId = false;
bool m_bSupportsModifiers = false;
+ bool m_bSupportsDmaBuf = false;
bool m_bSupportsMutableSwapchain = false;
bool m_bSupportsPresentWait = false;
bool m_bInitialized = false;
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -452,10 +452,16 @@
bool hasDrmProps = vulkan_has_drm_props();
bool supportsForeignQueue = false;
+ bool supportsMemoryFd = false;
+ bool supportsDmaBuf = false;
bool supportsHDRMetadata = false;
bool presentIdExtension = false;
bool presentWaitExtension = false;
for (const auto& ext : m_supportedExts) {
+ if ( strcmp(ext.extensionName, VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME) == 0 )
+ supportsMemoryFd = true;
+ if ( strcmp(ext.extensionName, VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME) == 0 )
+ supportsDmaBuf = true;
if ( strcmp(ext.extensionName, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0 )
m_bSupportsModifiers = true;
@@ -471,6 +477,18 @@
if ( strcmp(ext.extensionName, VK_EXT_HDR_METADATA_EXTENSION_NAME) == 0 )
supportsHDRMetadata = true;
+ }
+
+ m_bSupportsDmaBuf = supportsMemoryFd && supportsDmaBuf;
+ if ( !m_bSupportsDmaBuf )
+ {
+ if ( !GetBackend()->UsesVulkanSwapchain() )
+ {
+ vk_log.errorf( "This backend requires DMA-BUF import/export support" );
+ return false;
+ }
+ m_bSupportsModifiers = false;
+ vk_log.infof( "DMA-BUF unavailable; using SHM inputs with Vulkan swapchain rendering" );
}
vk_log.infof( "physical device %s DRM format modifiers", m_bSupportsModifiers ? "supports" : "does not support" );
@@ -617,8 +635,11 @@
enabledExtensions.push_back( VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME );
}
- enabledExtensions.push_back( VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME );
- enabledExtensions.push_back( VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME );
+ if ( m_bSupportsDmaBuf )
+ {
+ enabledExtensions.push_back( VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME );
+ enabledExtensions.push_back( VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME );
+ }
enabledExtensions.push_back( VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME );
@@ -2144,6 +2165,11 @@
{
flags.bExportable = true;
}
+ if ( ( pDMA || flags.bExportable ) && !g_device.supportsDmaBuf() )
+ {
+ vk_log.errorf( "DMA-BUF texture requested without import/export support" );
+ return false;
+ }
if ( flags.bTransferSrc == true )
{
@@ -2983,6 +3009,8 @@
}
wlr_drm_format_set_add( &sampledShmFormats, drmFormat, DRM_FORMAT_MOD_LINEAR );
+ if ( !g_device.supportsDmaBuf() )
+ return true;
if ( g_device.supportsModifiers() )
{
@@ -4836,7 +4864,7 @@
{
if (buffer_caps & WLR_BUFFER_CAP_DMABUF)
{
- return &sampledDRMFormats;
+ return g_device.supportsDmaBuf() ? &sampledDRMFormats : nullptr;
}
else if (buffer_caps & WLR_BUFFER_CAP_DATA_PTR)
{
@@ -4878,7 +4906,10 @@
struct wlr_renderer *vulkan_renderer_create( void )
{
VulkanRenderer_t *renderer = new VulkanRenderer_t();
- wlr_renderer_init(&renderer->base, &renderer_impl, WLR_BUFFER_CAP_DMABUF | WLR_BUFFER_CAP_DATA_PTR);
+ uint32_t caps = WLR_BUFFER_CAP_DATA_PTR;
+ if ( g_device.supportsDmaBuf() )
+ caps |= WLR_BUFFER_CAP_DMABUF;
+ wlr_renderer_init(&renderer->base, &renderer_impl, caps);
return &renderer->base;
}
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -2243,7 +2243,8 @@
// Have to make this old ancient thing for compat with older XWayland.
// Someday, he will be purged.
- wlr_drm_create(wlserver.display, wlserver.wlr.renderer);
+ if ( wlr_renderer_get_texture_formats( wlserver.wlr.renderer, WLR_BUFFER_CAP_DMABUF ) != nullptr )
+ wlr_drm_create(wlserver.display, wlserver.wlr.renderer);
if ( GetBackend()->SupportsExplicitSync() )
{
@@ -0,0 +1,358 @@
diff --git a/src/nested_swapchain.hpp b/src/nested_swapchain.hpp
new file mode 100644
index 0000000..06fc987
--- /dev/null
+++ b/src/nested_swapchain.hpp
@@ -0,0 +1,53 @@
+#pragma once
+
+#include <algorithm>
+#include <vulkan/vulkan_core.h>
+
+namespace gamescope
+{
+struct NestedSwapchainConfig
+{
+ bool copy = false;
+ uint32_t imageCount = 0;
+ VkImageUsageFlags usage = 0;
+ VkCompositeAlphaFlagBitsKHR alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
+ VkExtent2D extent = {};
+};
+
+inline bool ChooseNestedSwapchainConfig( const VkSurfaceCapabilitiesKHR &caps,
+ bool mutableFormat, uint32_t width, uint32_t height, NestedSwapchainConfig &config )
+{
+ constexpr VkImageUsageFlags direct = VK_IMAGE_USAGE_SAMPLED_BIT |
+ VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
+ config.copy = !mutableFormat || ( caps.supportedUsageFlags & direct ) != direct;
+ config.usage = config.copy ? VkImageUsageFlags{VK_IMAGE_USAGE_TRANSFER_DST_BIT} : direct;
+ if ( ( caps.supportedUsageFlags & config.usage ) != config.usage )
+ return false;
+
+ bool foundAlpha = false;
+ for ( auto alpha : { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
+ VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR } )
+ {
+ if ( caps.supportedCompositeAlpha & alpha )
+ {
+ config.alpha = alpha;
+ foundAlpha = true;
+ break;
+ }
+ }
+ if ( !foundAlpha || caps.maxImageExtent.width < caps.minImageExtent.width ||
+ caps.maxImageExtent.height < caps.minImageExtent.height )
+ return false;
+
+ config.imageCount = caps.minImageCount + ( caps.minImageCount != UINT32_MAX );
+ if ( caps.maxImageCount )
+ config.imageCount = std::min( config.imageCount, caps.maxImageCount );
+ if ( config.imageCount < caps.minImageCount )
+ return false;
+ config.extent = caps.currentExtent.width == UINT32_MAX
+ ? VkExtent2D{ std::clamp( width, caps.minImageExtent.width, caps.maxImageExtent.width ),
+ std::clamp( height, caps.minImageExtent.height, caps.maxImageExtent.height ) }
+ : caps.currentExtent;
+ return config.extent.width && config.extent.height;
+}
+}
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index ffad695..ffc8e28 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -12,6 +12,7 @@
#include <deque>
#include <dlfcn.h>
#include "vulkan_include.h"
+#include "nested_swapchain.hpp"
#include "Utils/Algorithm.h"
#if defined(__linux__)
@@ -450,6 +451,8 @@ bool CVulkanDevice::createDevice()
bool hasDrmProps = vulkan_has_drm_props();
bool supportsForeignQueue = false;
bool supportsHDRMetadata = false;
+ bool presentIdExtension = false;
+ bool presentWaitExtension = false;
for (const auto& ext : m_supportedExts) {
if ( strcmp(ext.extensionName, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0 )
m_bSupportsModifiers = true;
@@ -457,6 +460,13 @@ bool CVulkanDevice::createDevice()
if ( strcmp(ext.extensionName, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME) == 0 )
supportsForeignQueue = true;
+ if ( strcmp(ext.extensionName, VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME) == 0 )
+ m_bSupportsMutableSwapchain = true;
+ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_ID_EXTENSION_NAME) == 0 )
+ presentIdExtension = true;
+ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_WAIT_EXTENSION_NAME) == 0 )
+ presentWaitExtension = true;
+
if ( strcmp(ext.extensionName, VK_EXT_HDR_METADATA_EXTENSION_NAME) == 0 )
supportsHDRMetadata = true;
}
@@ -576,10 +586,24 @@ bool CVulkanDevice::createDevice()
if ( GetBackend()->UsesVulkanSwapchain() )
{
enabledExtensions.push_back( VK_KHR_SWAPCHAIN_EXTENSION_NAME );
- enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
+ if ( m_bSupportsMutableSwapchain )
+ enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
- enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
- enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
+ if ( presentIdExtension && presentWaitExtension )
+ {
+ VkPhysicalDevicePresentWaitFeaturesKHR wait = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR };
+ VkPhysicalDevicePresentIdFeaturesKHR id = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR, .pNext = &wait };
+ VkPhysicalDeviceFeatures2 features = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &id };
+ vk.GetPhysicalDeviceFeatures2( physDev(), &features );
+ m_bSupportsPresentWait = id.presentId && wait.presentWait;
+ }
+ if ( m_bSupportsPresentWait )
+ {
+ enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
+ enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
+ }
+ else
+ vk_log.infof( "Using FIFO acquire pacing; presentation timestamps unavailable" );
if ( supportsHDRMetadata )
enabledExtensions.push_back( VK_EXT_HDR_METADATA_EXTENSION_NAME );
@@ -654,7 +678,7 @@ bool CVulkanDevice::createDevice()
VkPhysicalDeviceFeatures2 features2 = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
- .pNext = &presentIdFeatures,
+ .pNext = m_bSupportsPresentWait ? static_cast<void *>( &presentIdFeatures ) : static_cast<void *>( &features13 ),
.features = {
.shaderInt16 = m_bSupportsFp16,
},
@@ -2660,7 +2684,7 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
return true;
}
-bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format )
+bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format, bool transferOnly )
{
m_drmFormat = VulkanFormatToDRM( format );
m_vkImage = image;
@@ -2672,6 +2696,12 @@ bool CVulkanTexture::BInitFromSwapchain( VkImage image, uint32_t width, uint32_t
m_contentWidth = width;
m_contentHeight = height;
m_bOutputImage = true;
+ if ( transferOnly )
+ {
+ // A copy destination needs no views (and the swapchain need not be mutable).
+ m_bInitialized = true;
+ return true;
+ }
VkImageViewCreateInfo createInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
@@ -3094,7 +3124,7 @@ void vulkan_present_to_window( void )
VkPresentInfoKHR presentInfo = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
- .pNext = &presentIdInfo,
+ .pNext = g_device.supportsPresentWait() ? &presentIdInfo : nullptr,
.swapchainCount = 1,
.pSwapchains = &g_output.swapChain,
.pImageIndices = &g_output.nOutImage,
@@ -3102,14 +3132,22 @@ void vulkan_present_to_window( void )
if ( g_device.vk.QueuePresentKHR( g_device.queue(), &presentInfo ) == VK_SUCCESS )
{
- g_currentPresentWaitId = presentId;
- g_currentPresentWaitId.notify_all();
+ if ( g_device.supportsPresentWait() )
+ {
+ g_currentPresentWaitId = presentId;
+ g_currentPresentWaitId.notify_all();
+ }
}
else
vulkan_remake_swapchain();
while ( !acquire_next_image() )
vulkan_remake_swapchain();
+ if ( !g_device.supportsPresentWait() )
+ {
+ // Estimated scheduling anchor after FIFO buffer acquisition, not presentation feedback.
+ GetVBlankTimer().MarkVBlank( get_time_in_nanos(), true );
+ }
}
gamescope::Rc<CVulkanTexture> vulkan_create_1d_lut(uint32_t size)
@@ -3219,7 +3257,19 @@ extern bool g_bOutputHDREnabled;
bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
{
- uint32_t imageCount = pOutput->surfaceCaps.minImageCount + 1;
+ // Re-query on resize as well as initial creation.
+ if ( g_device.vk.GetPhysicalDeviceSurfaceCapabilitiesKHR( g_device.physDev(), pOutput->surface, &pOutput->surfaceCaps ) != VK_SUCCESS )
+ return false;
+ gamescope::NestedSwapchainConfig config;
+ if ( !gamescope::ChooseNestedSwapchainConfig( pOutput->surfaceCaps, g_device.supportsMutableSwapchain(), g_nOutputWidth, g_nOutputHeight, config ) )
+ {
+ vk_log.errorf( "Surface supports neither direct composition nor transfer presentation" );
+ return false;
+ }
+ pOutput->copyToSwapchain = config.copy;
+ g_nOutputWidth = config.extent.width;
+ g_nOutputHeight = config.extent.height;
+ uint32_t imageCount = config.imageCount;
uint32_t formatCount = pOutput->surfaceFormats.size();
uint32_t surfaceFormat = formatCount;
VkColorSpaceKHR preferredColorSpace = g_bOutputHDREnabled ? VK_COLOR_SPACE_HDR10_ST2084_EXT : VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
@@ -3254,6 +3304,13 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
}
}
+ if ( surfaceFormat == formatCount )
+ {
+ for ( surfaceFormat = 0; surfaceFormat < formatCount; ++surfaceFormat )
+ if ( pOutput->surfaceFormats[surfaceFormat].format == VK_FORMAT_R8G8B8A8_UNORM &&
+ pOutput->surfaceFormats[surfaceFormat].colorSpace == preferredColorSpace )
+ break;
+ }
if ( surfaceFormat == formatCount )
return false;
@@ -3276,8 +3333,8 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
VkSwapchainCreateInfoKHR createInfo = {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
- .pNext = formats[0] != formats[1] ? &usageListInfo : nullptr,
- .flags = formats[0] != formats[1] ? VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR : (VkSwapchainCreateFlagBitsKHR )0,
+ .pNext = !config.copy && formats[0] != formats[1] ? &usageListInfo : nullptr,
+ .flags = !config.copy && formats[0] != formats[1] ? VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR : (VkSwapchainCreateFlagBitsKHR )0,
.surface = pOutput->surface,
.minImageCount = imageCount,
.imageFormat = eVkFormat,
@@ -3287,10 +3344,10 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
.height = g_nOutputHeight,
},
.imageArrayLayers = 1,
- .imageUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
+ .imageUsage = config.usage,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.preTransform = pOutput->surfaceCaps.currentTransform,
- .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
+ .compositeAlpha = config.alpha,
.presentMode = VK_PRESENT_MODE_FIFO_KHR,
.clipped = VK_TRUE,
};
@@ -3304,12 +3361,30 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput )
g_device.vk.GetSwapchainImagesKHR( g_device.device(), pOutput->swapChain, &imageCount, swapchainImages.data() );
pOutput->outputImages.resize(imageCount);
+ pOutput->presentationImages.clear();
+ if ( config.copy )
+ {
+ vk_log.infof( "Nested swapchain: composing offscreen and copying to FIFO presentation images" );
+ pOutput->presentationImages.resize(imageCount);
+ }
for ( uint32_t i = 0; i < pOutput->outputImages.size(); i++ )
{
pOutput->outputImages[i] = new CVulkanTexture();
- if ( !pOutput->outputImages[i]->BInitFromSwapchain(swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat))
+ if ( config.copy )
+ {
+ CVulkanTexture::createFlags flags;
+ flags.bStorage = true;
+ flags.bSampled = true;
+ flags.bTransferSrc = true;
+ if ( !pOutput->outputImages[i]->BInit( g_nOutputWidth, g_nOutputHeight, 1, pOutput->uOutputFormat, flags ) )
+ return false;
+ pOutput->presentationImages[i] = new CVulkanTexture();
+ if ( !pOutput->presentationImages[i]->BInitFromSwapchain( swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat, true ) )
+ return false;
+ }
+ else if ( !pOutput->outputImages[i]->BInitFromSwapchain(swapchainImages[i], g_nOutputWidth, g_nOutputHeight, eVkFormat))
return false;
}
@@ -3335,6 +3410,10 @@ bool vulkan_remake_swapchain( void )
g_device.vk.QueueWaitIdle( g_device.queue() );
pOutput->outputImages.clear();
+ pOutput->presentationImages.clear();
+ if ( pOutput->acquireFence )
+ g_device.vk.DestroyFence( g_device.device(), pOutput->acquireFence, nullptr );
+ pOutput->acquireFence = VK_NULL_HANDLE;
g_device.vk.DestroySwapchainKHR( g_device.device(), pOutput->swapChain, nullptr );
@@ -3670,7 +3749,7 @@ bool vulkan_init( VkInstance instance, VkSurfaceKHR surface )
if (!init_nis_data())
return false;
- if ( GetBackend()->UsesVulkanSwapchain() )
+ if ( GetBackend()->UsesVulkanSwapchain() && g_device.supportsPresentWait() )
{
std::thread present_wait_thread( present_wait_thread_func );
present_wait_thread.detach();
@@ -4579,6 +4658,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco
CompositeTimingEnd( cmdBuffer.get(), *oTimingSlot, pszKey, pszKeyPre, pszKeyPost );
}
+ if ( !pOutputOverride && g_output.copyToSwapchain )
+ cmdBuffer->copyImage( compositeImage, g_output.presentationImages[g_output.nOutImage] );
+
uint64_t sequence = g_device.submit(std::move(cmdBuffer));
if ( oTimingSlot )
g_CompositeTiming.pending.back().ulSeqNo = sequence;
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index fa519db..674a3b4 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -162,7 +162,7 @@ public:
};
bool BInit( uint32_t width, uint32_t height, uint32_t depth, uint32_t drmFormat, createFlags flags, wlr_dmabuf_attributes *pDMA = nullptr, uint32_t contentWidth = 0, uint32_t contentHeight = 0, CVulkanTexture *pExistingImageToReuseMemory = nullptr, gamescope::OwningRc<gamescope::IBackendFb> pBackendFb = nullptr );
- bool BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format );
+ bool BInitFromSwapchain( VkImage image, uint32_t width, uint32_t height, VkFormat format, bool transferOnly = false );
uint32_t IncRef();
uint32_t DecRef();
@@ -586,7 +586,9 @@ struct VulkanOutput_t
std::shared_ptr<gamescope::BackendBlob> swapchainHDRMetadata;
VkSwapchainKHR swapChain;
- VkFence acquireFence;
+ VkFence acquireFence = VK_NULL_HANDLE;
+ bool copyToSwapchain = false;
+ std::vector<gamescope::OwningRc<CVulkanTexture>> presentationImages;
uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs
std::vector<gamescope::OwningRc<CVulkanTexture>> outputImages;
@@ -756,6 +758,7 @@ static inline uint32_t div_roundup(uint32_t x, uint32_t y)
VK_FUNC(CreateDescriptorPool) \
VK_FUNC(CreateDescriptorSetLayout) \
VK_FUNC(CreateFence) \
+ VK_FUNC(DestroyFence) \
VK_FUNC(CreateGraphicsPipelines) \
VK_FUNC(CreateImage) \
VK_FUNC(CreateImageView) \
@@ -862,6 +865,8 @@ public:
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
inline int drmRenderFd() {return m_drmRendererFd;}
inline bool supportsModifiers() {return m_bSupportsModifiers;}
+ inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
+ inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
inline dev_t primaryDevId() {return m_drmPrimaryDevId;}
inline bool supportsFp16() {return m_bSupportsFp16;}
@@ -930,6 +935,8 @@ protected:
uint32_t m_uVendorID = 0;
bool m_bHasDrmPrimaryDevId = false;
bool m_bSupportsModifiers = false;
+ bool m_bSupportsMutableSwapchain = false;
+ bool m_bSupportsPresentWait = false;
bool m_bInitialized = false;
@@ -0,0 +1,121 @@
diff --git a/src/dmabuf_import.hpp b/src/dmabuf_import.hpp
new file mode 100644
index 0000000..ffa002b
--- /dev/null
+++ b/src/dmabuf_import.hpp
@@ -0,0 +1,21 @@
+#pragma once
+#include <vulkan/vulkan_core.h>
+
+namespace gamescope
+{
+inline uint32_t DmabufMemoryType( const VkPhysicalDeviceMemoryProperties &memory,
+ uint32_t imageBits, uint32_t fdBits, VkMemoryPropertyFlags preferred )
+{
+ uint32_t fallback = UINT32_MAX;
+ const uint32_t compatible = imageBits & fdBits;
+ for ( uint32_t i = 0; i < memory.memoryTypeCount; ++i )
+ {
+ if ( !( compatible & ( 1u << i ) ) ) continue;
+ if ( fallback == UINT32_MAX ) fallback = i;
+ if ( ( memory.memoryTypes[i].propertyFlags & preferred ) == preferred ) return i;
+ }
+ // Device-local is a preference for an existing imported buffer. CPU mapping
+ // properties are requirements and must never be silently relaxed.
+ return preferred == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ? fallback : UINT32_MAX;
+}
+}
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
index a5d9bbb..8d9f8f9 100644
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -13,6 +13,7 @@
#include <dlfcn.h>
#include "vulkan_include.h"
#include "nested_swapchain.hpp"
+#include "dmabuf_import.hpp"
#include "Utils/Algorithm.h"
#if defined(__linux__)
@@ -2347,6 +2348,22 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
m_format = imageInfo.format;
+ VkMemoryFdPropertiesKHR fdProperties = {
+ .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,
+ };
+ if ( pDMA )
+ {
+ if ( !g_device.vk.GetMemoryFdPropertiesKHR )
+ return false;
+ res = g_device.vk.GetMemoryFdPropertiesKHR( g_device.device(),
+ VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, pDMA->fd[0], &fdProperties );
+ if ( res != VK_SUCCESS )
+ {
+ vk_errorf( res, "vkGetMemoryFdPropertiesKHR failed" );
+ return false;
+ }
+ }
+
res = g_device.vk.CreateImage(g_device.device(), &imageInfo, nullptr, &m_vkImage);
if (res != VK_SUCCESS) {
vk_errorf( res, "vkCreateImage failed" );
@@ -2356,10 +2373,22 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
VkMemoryRequirements memRequirements;
g_device.vk.GetImageMemoryRequirements(g_device.device(), m_vkImage, &memRequirements);
+ uint32_t memoryType = pDMA
+ ? gamescope::DmabufMemoryType( g_device.memoryProperties(), memRequirements.memoryTypeBits,
+ fdProperties.memoryTypeBits, properties )
+ : uint32_t( g_device.findMemoryType( properties, memRequirements.memoryTypeBits ) );
+ if ( memoryType == UINT32_MAX )
+ {
+ vk_log.errorf( "No compatible image memory type (image=0x%x, fd=0x%x)",
+ memRequirements.memoryTypeBits, fdProperties.memoryTypeBits );
+ g_device.vk.DestroyImage( g_device.device(), m_vkImage, nullptr );
+ m_vkImage = VK_NULL_HANDLE;
+ return false;
+ }
VkMemoryAllocateInfo allocInfo = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = memRequirements.size,
- .memoryTypeIndex = uint32_t(g_device.findMemoryType(properties, memRequirements.memoryTypeBits)),
+ .memoryTypeIndex = memoryType,
};
m_size = allocInfo.allocationSize;
@@ -2452,6 +2481,13 @@ bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uin
if ( res != VK_SUCCESS )
{
vk_errorf( res, "vkBindImageMemory failed" );
+ if ( pDMA )
+ vk_log.errorf( "DMA-BUF: %ux%u format=%u modifier=0x%" PRIx64
+ " planes=%d stride=%u offset=%u tiling=%u allocation=%" PRIu64
+ " memoryType=%u imageBits=0x%x fdBits=0x%x", width, height, imageInfo.format,
+ pDMA->modifier, pDMA->n_planes, pDMA->stride[0], pDMA->offset[0], imageInfo.tiling,
+ uint64_t( allocInfo.allocationSize ), allocInfo.memoryTypeIndex,
+ memRequirements.memoryTypeBits, fdProperties.memoryTypeBits );
return false;
}
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index 674a3b4..5ffec4a 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -791,6 +791,7 @@ static inline uint32_t div_roundup(uint32_t x, uint32_t y)
VK_FUNC(GetImageMemoryRequirements) \
VK_FUNC(GetImageSubresourceLayout) \
VK_FUNC(GetMemoryFdKHR) \
+ VK_FUNC(GetMemoryFdPropertiesKHR) \
VK_FUNC(GetQueryPoolResults) \
VK_FUNC(GetSemaphoreCounterValue) \
VK_FUNC(GetSwapchainImagesKHR) \
@@ -865,6 +866,8 @@ public:
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
inline int drmRenderFd() {return m_drmRendererFd;}
inline bool supportsModifiers() {return m_bSupportsModifiers;}
+ inline uint32_t vendorID() const {return m_uVendorID;}
+ inline const VkPhysicalDeviceMemoryProperties &memoryProperties() const {return m_memoryProperties;}
inline bool supportsMutableSwapchain() {return m_bSupportsMutableSwapchain;}
inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
@@ -0,0 +1,78 @@
diff --git a/src/sdl_refresh.hpp b/src/sdl_refresh.hpp
new file mode 100644
--- /dev/null
+++ b/src/sdl_refresh.hpp
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <cstdint>
+
+namespace gamescope
+{
+struct SDLRefreshChoice
+{
+ int32_t refresh = 0;
+ bool configured = false;
+};
+
+// SDL reports the desktop mode again when its window is shown, moved or resized. Keep an
+// explicit -r as the rate exposed by nested Gamescope; discover the desktop rate only when the
+// caller did not configure one.
+inline constexpr SDLRefreshChoice ChooseSDLRefresh( int32_t configuredRefresh, int32_t desktopRefresh )
+{
+ return configuredRefresh > 0
+ ? SDLRefreshChoice{ configuredRefresh, true }
+ : SDLRefreshChoice{ desktopRefresh, false };
+}
+}
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -18,14 +18,20 @@
#include "steamcompmgr.hpp"
#include "Utils/Defer.h"
#include "refresh_rate.h"
+#include "log.hpp"
+#include "sdl_refresh.hpp"
#include "sdlscancodetable.hpp"
static int g_nOldNestedRefresh = 0;
static bool g_bWindowFocused = true;
+static int g_nLastLoggedConfiguredRefresh = -1;
+static int g_nLastLoggedDesktopRefresh = -1;
+static int g_nLastLoggedEffectiveRefresh = -1;
static int g_nOutputWidthPts = 0;
static int g_nOutputHeightPts = 0;
+static LogScope sdl_log( "sdl_backend" );
extern bool g_bForceHDR10OutputDebug;
extern bool steamMode;
@@ -846,9 +851,25 @@ namespace gamescope
SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
display_index = SDL_GetWindowDisplayIndex( m_Connector.GetSDLWindow() );
if ( SDL_GetDesktopDisplayMode( display_index, &mode ) == 0 )
{
- g_nOutputRefresh = ConvertHztomHz( mode.refresh_rate );
+ const int nDesktopRefresh = ConvertHztomHz( mode.refresh_rate );
+ const SDLRefreshChoice refresh = ChooseSDLRefresh( g_nOldNestedRefresh, nDesktopRefresh );
+ g_nOutputRefresh = refresh.refresh;
+
+ if ( g_nLastLoggedConfiguredRefresh != g_nOldNestedRefresh ||
+ g_nLastLoggedDesktopRefresh != nDesktopRefresh ||
+ g_nLastLoggedEffectiveRefresh != refresh.refresh )
+ {
+ sdl_log.infof( "Refresh mode: configured=%.3fHz desktop=%.3fHz effective=%.3fHz source=%s",
+ ConvertmHzToHz( float( g_nOldNestedRefresh ) ),
+ ConvertmHzToHz( float( nDesktopRefresh ) ),
+ ConvertmHzToHz( float( refresh.refresh ) ),
+ refresh.configured ? "configured -r" : "SDL desktop" );
+ g_nLastLoggedConfiguredRefresh = g_nOldNestedRefresh;
+ g_nLastLoggedDesktopRefresh = nDesktopRefresh;
+ g_nLastLoggedEffectiveRefresh = refresh.refresh;
+ }
}
}
break;
@@ -0,0 +1,23 @@
diff --git a/src/Backends/SDLBackend.cpp b/src/Backends/SDLBackend.cpp
--- a/src/Backends/SDLBackend.cpp
+++ b/src/Backends/SDLBackend.cpp
@@ -351,14 +351,15 @@ namespace gamescope
std::optional oCompositeResult = vulkan_composite( (FrameInfo_t *)pFrameInfo, nullptr, false );
if ( !oCompositeResult )
return -EINVAL;
+ // Present has no render-finished semaphore, so wait before the native consumer can read
+ // the old contents. This serializes composition and present; a future pipelined path must
+ // signal a binary render-finished semaphore and make vkQueuePresentKHR wait on it.
+ vulkan_wait( *oCompositeResult, true );
+
vulkan_present_to_window();
// TODO: Hook up PresentationFeedback.
-
- // Wait for the composite result on our side *after* we
- // commit the buffer to the compositor to avoid a bubble.
- vulkan_wait( *oCompositeResult, true );
GetVBlankTimer().UpdateWasCompositing( true );
GetVBlankTimer().UpdateLastDrawTime( get_time_in_nanos() - g_SteamCompMgrVBlankTime.ulWakeupTime );
@@ -0,0 +1,176 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -95,6 +95,7 @@
#include "Script/Script.h"
#include "refresh_rate.h"
#include "commit.h"
+#include "buffer_commit_sync.hpp"
#include "reshade_effect_manager.hpp"
#include "BufferMemo.h"
#include "vrclient_detect.h"
@@ -8451,7 +8452,6 @@ void update_wayland_res(CommitDoneList_t *doneCommits, steamcompmgr_win_t *w, Re
return;
}
- int fence = -1;
global_focus_t *pCurrentFocus = GetCurrentFocus();
static bool bMangoappSocketDisable = env_to_bool( getenv( "GAMESCOPE_MANGOAPP_SOCKET_DISABLE" ));
@@ -8492,8 +8492,6 @@ void update_wayland_res(CommitDoneList_t *doneCommits, steamcompmgr_win_t *w, Re
bool bValidPreemptiveScale = reslistentry.pAcquirePoint && pUpscaleFocus && cv_upscale_preemptive;
bool bPreemptiveUpscale = bValidPreemptiveScale && newCommit->ShouldPreemptivelyUpscale( pUpscaleFocus->eUpscaleFilter, pUpscaleFocus->eUpscaleScaler );
- bool bKnownReady = false;
-
std::pair<int32_t, bool> eventFd = gamescope::CAcquireTimelinePoint::k_InvalidEvent;
if ( bPreemptiveUpscale )
@@ -8589,31 +8587,44 @@ void update_wayland_res(CommitDoneList_t *doneCommits, steamcompmgr_win_t *w, Re
pBackendFb->SetBuffer( buf );
}
- if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent )
- {
- fence = eventFd.first;
- bKnownReady = eventFd.second;
- }
- else
- {
- struct wlr_dmabuf_attributes dmabuf = {0};
- if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) )
- {
- fence = dup( dmabuf.fd[0] );
- }
- else
+ gamescope::BufferCommitSync commitSync = gamescope::SelectBufferCommitSync(
+ eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent,
+ eventFd.first,
+ eventFd.second,
+ [&]() -> std::optional<int> {
+ struct wlr_dmabuf_attributes dmabuf = {0};
+ if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) )
+ {
+ int fd = dup( dmabuf.fd[0] );
+ if ( fd < 0 )
+ xwm_log.errorf( "Failed to duplicate DMA-BUF fence: %d", errno );
+ return fd;
+ }
+ return std::nullopt;
+ } );
+ if ( commitSync.source == gamescope::BufferCommitSyncSource::SynchronousUpload )
+ {
+ // vulkan_create_texture_from_wlr_buffer waited for this SHM upload to finish.
+ // Exporting its image memory as a DMA-BUF does not produce a sync fence and can
+ // return an invalid fd on drivers that do not export the allocation.
+ static bool loggedSynchronousUpload = false;
+ if ( !loggedSynchronousUpload )
{
- fence = newCommit->vulkanTex->memoryFence();
+ xwm_log.infof( "Treating synchronously uploaded SHM commit %lu as ready without an external fence",
+ newCommit->commitID );
+ loggedSynchronousUpload = true;
}
}
gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 );
+ if ( !gamescope::DispatchBufferCommitSync( newCommit.get(), g_ImageWaiter, commitSync,
+ mango_nudge, uMangoMsgType, doneCommits ) )
{
- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits );
- if ( bKnownReady )
- newCommit->Signal();
- else
- g_ImageWaiter.AddWaitable( newCommit.get() );
+ xwm_log.errorf( "Failed to queue %s commit fence fd %d for commit %lu",
+ gamescope::BufferCommitSyncSourceName( commitSync.source ), commitSync.fence, newCommit->commitID );
+ // Dropping the commit releases its buffer and discards presentation feedback.
+ w->receivedDoneCommit = true;
+ return;
}
w->commit_queue.push_back( std::move(newCommit) );
diff --git a/src/buffer_commit_sync.hpp b/src/buffer_commit_sync.hpp
new file mode 100644
--- /dev/null
+++ b/src/buffer_commit_sync.hpp
@@ -0,0 +1,79 @@
+#pragma once
+
+#include <optional>
+
+namespace gamescope
+{
+enum class BufferCommitSyncSource
+{
+ ExplicitAcquire,
+ DmaBuf,
+ SynchronousUpload,
+};
+
+struct BufferCommitSync
+{
+ int fence = -1;
+ bool knownReady = false;
+ BufferCommitSyncSource source = BufferCommitSyncSource::SynchronousUpload;
+
+ static constexpr BufferCommitSync ExplicitAcquire( int fence, bool knownReady )
+ {
+ return { fence, knownReady, BufferCommitSyncSource::ExplicitAcquire };
+ }
+
+ static constexpr BufferCommitSync DmaBuf( int fence )
+ {
+ return { fence, false, BufferCommitSyncSource::DmaBuf };
+ }
+
+ static constexpr BufferCommitSync SynchronousUpload()
+ {
+ return { -1, true, BufferCommitSyncSource::SynchronousUpload };
+ }
+};
+
+template <typename GetDmaBufFence>
+BufferCommitSync SelectBufferCommitSync( bool hasExplicitAcquire, int explicitFence,
+ bool explicitKnownReady, GetDmaBufFence &&getDmaBufFence )
+{
+ if ( hasExplicitAcquire )
+ return BufferCommitSync::ExplicitAcquire( explicitFence, explicitKnownReady );
+
+ if ( std::optional<int> dmaBufFence = getDmaBufFence() )
+ return BufferCommitSync::DmaBuf( *dmaBufFence );
+
+ return BufferCommitSync::SynchronousUpload();
+}
+
+constexpr const char *BufferCommitSyncSourceName( BufferCommitSyncSource source )
+{
+ switch ( source )
+ {
+ case BufferCommitSyncSource::ExplicitAcquire:
+ return "explicit acquire";
+ case BufferCommitSyncSource::DmaBuf:
+ return "DMA-BUF";
+ case BufferCommitSyncSource::SynchronousUpload:
+ return "synchronous upload";
+ }
+
+ return "unknown";
+}
+
+template <typename Commit, typename Waiter, typename DoneCommits>
+bool DispatchBufferCommitSync( Commit *commit, Waiter &waiter, const BufferCommitSync &sync,
+ bool mangoNudge, unsigned int mangoMsgType, DoneCommits *doneCommits )
+{
+ commit->SetFence( sync.fence, mangoNudge, mangoMsgType, doneCommits );
+ if ( !sync.knownReady && sync.fence < 0 )
+ return false;
+ if ( sync.knownReady )
+ {
+ commit->Signal();
+ return true;
+ }
+
+ return waiter.AddWaitable( commit );
+}
+}
@@ -0,0 +1,54 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -1851,16 +1851,22 @@
commit->fifo = false;
}
- if ( gamescope::OwningRc<CVulkanTexture> pTexture = s_BufferMemos.LookupVulkanTexture( buf ) )
- {
- // Going from OwningRc -> Rc now.
- commit->vulkanTex = pTexture;
- return commit;
- }
-
struct wlr_dmabuf_attributes dmabuf = {0};
+ const bool bIsDmabuf = wlr_buffer_get_dmabuf( buf, &dmabuf );
+ // DMA-BUF textures reference the producer's live allocation. SHM textures are
+ // snapshots uploaded into separate memory and must be refreshed every commit.
+ if ( bIsDmabuf )
+ {
+ if ( gamescope::OwningRc<CVulkanTexture> pTexture = s_BufferMemos.LookupVulkanTexture( buf ) )
+ {
+ // Going from OwningRc -> Rc now.
+ commit->vulkanTex = pTexture;
+ return commit;
+ }
+ }
+
gamescope::OwningRc<gamescope::IBackendFb> pBackendFb;
- if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) )
+ if ( bIsDmabuf )
{
pBackendFb = GetBackend()->ImportDmabufToBackend( &dmabuf );
}
@@ -1874,7 +1880,8 @@
commit->vulkanTex = pOwnedTexture;
- s_BufferMemos.MemoizeBuffer( buf, std::move( pOwnedTexture ) );
+ if ( bIsDmabuf )
+ s_BufferMemos.MemoizeBuffer( buf, std::move( pOwnedTexture ) );
return commit;
}
@@ -8599,7 +8606,8 @@
} );
if ( commitSync.source == gamescope::BufferCommitSyncSource::SynchronousUpload )
{
- // vulkan_create_texture_from_wlr_buffer waited for this SHM upload to finish.
+ // Every SHM commit is uploaded synchronously; only DMA-BUF textures are memoized.
+ // vulkan_create_texture_from_wlr_buffer waited for this upload to finish.
// Exporting its image memory as a DMA-BUF does not produce a sync fence and can
// return an invalid fd on drivers that do not export the allocation.
static bool loggedSynchronousUpload = false;
@@ -0,0 +1,15 @@
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
--- a/src/rendervulkan.cpp
+++ b/src/rendervulkan.cpp
@@ -4966,7 +4966,10 @@
CVulkanTexture::createFlags texCreateFlags;
texCreateFlags.bSampled = true;
texCreateFlags.bTransferDst = true;
- texCreateFlags.bFlippable = true;
+ // Swapchain backends sample this synchronous SHM upload locally. They never
+ // scan it out or forward its DMA-BUF, so external allocation and ownership
+ // transfers are unnecessary. Keep exportable inputs for the other backends.
+ texCreateFlags.bFlippable = !GetBackend()->UsesVulkanSwapchain();
if ( pTex->BInit( width, height, 1u, drmFormat, texCreateFlags, nullptr, 0, 0, nullptr, pBackendFb ) == false )
return nullptr;
@@ -0,0 +1,14 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -2350,6 +2350,9 @@ bool MouseCursor::getTexture()
CVulkanTexture::createFlags texCreateFlags;
- texCreateFlags.bFlippable = true;
+ // The Vulkan swapchain backend samples cursor pixels locally. It does not
+ // scan out or forward a cursor DMA-BUF, so keep this allocation internal.
+ // Hardware and forwarding backends retain their exportable cursor texture.
+ texCreateFlags.bFlippable = !GetBackend()->UsesVulkanSwapchain();
if ( GetBackend()->SupportsPlaneHardwareCursor() )
{
texCreateFlags.bLinear = true; // cursor buffer needs to be linear
@@ -0,0 +1,10 @@
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -2,6 +2,7 @@
#define _GNU_SOURCE 1
#include <assert.h>
+#include <cfloat>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
@@ -0,0 +1,45 @@
diff --git a/hybris/vulkan/icd/instance.c b/hybris/vulkan/icd/instance.c
index a3e3020..6717d19 100644
--- a/hybris/vulkan/icd/instance.c
+++ b/hybris/vulkan/icd/instance.c
@@ -70,6 +70,27 @@ static void VKAPI_CALL destroy_instance(VkInstance instance,
free_state(state);
}
+/* Android's loader leaves some core physical-device queries to the driver, so
+ * for its instance they resolve to the HAL's own entries. Which ones it wraps
+ * differs between releases (Android 14 wraps vkGetPhysicalDeviceProperties),
+ * so one identical entry is enough; another driver, or a layer intercepting
+ * all of them, matches none. */
+static int platform_uses_hal(PFN_vkGetInstanceProcAddr platform,
+ PFN_vkGetInstanceProcAddr hal, VkInstance instance)
+{
+ static const char *const queries[] = {
+ "vkGetPhysicalDeviceProperties", "vkGetPhysicalDeviceFeatures",
+ "vkGetPhysicalDeviceMemoryProperties", "vkGetPhysicalDeviceQueueFamilyProperties",
+ "vkGetPhysicalDeviceFormatProperties",
+ };
+ for (size_t i = 0; i < sizeof(queries) / sizeof(queries[0]); ++i) {
+ PFN_vkVoidFunction entry = hal(instance, queries[i]);
+ if (entry && platform(instance, queries[i]) == entry)
+ return 1;
+ }
+ return 0;
+}
+
VkResult hybris_icd_create_instance(hwvulkan_device_t *hal,
PFN_vkGetInstanceProcAddr platform,
const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
@@ -113,10 +134,8 @@ VkResult hybris_icd_create_instance(hwvulkan_device_t *hal,
state->resolver = hal->GetInstanceProcAddr;
state->destroy = (PFN_vkDestroyInstance)platform(*instance, "vkDestroyInstance");
/* Never pass a handle from an Android layer or an independently selected
- * updatable driver to our HAL. This core query is an unhooked driver entry
- * in Android's loader and must resolve to the same implementation. */
- if (platform(*instance, "vkGetPhysicalDeviceProperties") !=
- state->resolver(*instance, "vkGetPhysicalDeviceProperties")) {
+ * updatable driver to our HAL. */
+ if (!platform_uses_hal(platform, state->resolver, *instance)) {
fprintf(stderr, "hybris ICD: Android instance and configured HAL use different dispatch implementations\n");
state->destroy(*instance, allocator);
*instance = VK_NULL_HANDLE;
@@ -0,0 +1,31 @@
diff --git a/hybris/vulkan/icd/device.c b/hybris/vulkan/icd/device.c
index 1758b37..a9bfee4 100644
--- a/hybris/vulkan/icd/device.c
+++ b/hybris/vulkan/icd/device.c
@@ -148,6 +148,9 @@ PFN_vkVoidFunction VKAPI_CALL hybris_icd_device_proc(VkDevice device, const char
int swapchain_enabled = state ? state->swapchain_enabled : 0;
pthread_mutex_unlock(&device_guard);
PFN_vkVoidFunction backend = resolver ? resolver(device, name) : NULL;
+ /* Same promotion as vkGetPhysicalDeviceCalibrateableTimeDomainsKHR. */
+ if (!backend && resolver && !strcmp(name, "vkGetCalibratedTimestampsKHR"))
+ backend = resolver(device, "vkGetCalibratedTimestampsEXT");
PFN_vkVoidFunction local = hybris_icd_swapchain_proc(name, swapchain_enabled);
if (local) return local;
if (backend && swapchain_enabled) {
diff --git a/hybris/vulkan/icd/instance.c b/hybris/vulkan/icd/instance.c
index 6717d19..7f30014 100644
--- a/hybris/vulkan/icd/instance.c
+++ b/hybris/vulkan/icd/instance.c
@@ -295,6 +295,12 @@ PFN_vkVoidFunction hybris_icd_instance_proc(VkInstance instance, const char *nam
int platforms_enabled = state ? state->platforms_enabled : 0;
pthread_mutex_unlock(&instance_guard);
PFN_vkVoidFunction backend = resolver ? resolver(instance, name) : NULL;
+ /* VK_KHR_calibrated_timestamps is VK_EXT_calibrated_timestamps promoted with
+ * the same signature and time-domain values. A HAL that only has the EXT
+ * name returns NULL for the KHR one, and the desktop loader aborts when an
+ * application or layer calls the KHR trampoline. */
+ if (!backend && resolver && !strcmp(name, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR"))
+ backend = resolver(instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT");
PFN_vkVoidFunction local_wsi = hybris_icd_wsi_proc(name, surface_enabled, platforms_enabled);
if (local_wsi) return local_wsi;
/* Device WSI entry points are adapter-owned. Enablement is checked on the
@@ -0,0 +1,89 @@
diff --git a/hybris/vulkan/icd/instance.c b/hybris/vulkan/icd/instance.c
index 7f30014..b9db254 100644
--- a/hybris/vulkan/icd/instance.c
+++ b/hybris/vulkan/icd/instance.c
@@ -9,6 +9,7 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
+#include <sys/auxv.h>
/* Driver handles keep their loader-owned dispatch header untouched. */
struct physical_state {
@@ -285,6 +286,63 @@ static VkResult VKAPI_CALL create_device(VkPhysicalDevice physical,
return hybris_icd_create_device(create, resolver, state->generation, physical, info, allocator, device);
}
+/* DXVK before its 2025 memory rework takes the first memory type with the requested property
+ * flags and skips later device-local ones. Qualcomm HALs list DEVICE_LOCAL|HOST_VISIBLE types
+ * that no buffer or image may use ahead of the cached coherent type that buffers do use, so DXVK
+ * found no memory for its upload buffers. Report host flags only on host-visible types that no
+ * other host-visible type of the same heap strictly contains; indices and heaps are unchanged. */
+static void trim_host_memory_types(VkPhysicalDeviceMemoryProperties *memory)
+{
+ const char *keep = getauxval(AT_SECURE) ? NULL : getenv("HYBRIS_VULKAN_KEEP_MEMORY_TYPES");
+ if (keep && !strcmp(keep, "1")) return;
+ const VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
+ VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
+ VkMemoryPropertyFlags original[VK_MAX_MEMORY_TYPES];
+ uint32_t count = memory->memoryTypeCount < VK_MAX_MEMORY_TYPES ? memory->memoryTypeCount : VK_MAX_MEMORY_TYPES;
+ for (uint32_t i = 0; i < count; ++i) original[i] = memory->memoryTypes[i].propertyFlags;
+ for (uint32_t i = 0; i < count; ++i) {
+ if (!(original[i] & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) continue;
+ for (uint32_t j = 0; j < count; ++j) {
+ if (j == i || !(original[j] & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
+ memory->memoryTypes[j].heapIndex != memory->memoryTypes[i].heapIndex) continue;
+ if ((original[i] & original[j]) == original[i] && original[j] != original[i]) {
+ memory->memoryTypes[i].propertyFlags = original[i] & ~host;
+ break;
+ }
+ }
+ }
+}
+
+static void VKAPI_CALL memory_properties(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties *out)
+{
+ struct hybris_icd_physical context;
+ if (!hybris_icd_lookup_physical(physical, &context)) return;
+ PFN_vkGetPhysicalDeviceMemoryProperties query = (PFN_vkGetPhysicalDeviceMemoryProperties)
+ context.resolver(context.instance, "vkGetPhysicalDeviceMemoryProperties");
+ query(physical, out);
+ trim_host_memory_types(out);
+}
+
+static void memory_properties2(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties2 *out, const char *name)
+{
+ struct hybris_icd_physical context;
+ if (!hybris_icd_lookup_physical(physical, &context)) return;
+ PFN_vkGetPhysicalDeviceMemoryProperties2 query = (PFN_vkGetPhysicalDeviceMemoryProperties2)
+ context.resolver(context.instance, name);
+ query(physical, out);
+ trim_host_memory_types(&out->memoryProperties);
+}
+
+static void VKAPI_CALL memory_properties2_core(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties2 *out)
+{
+ memory_properties2(physical, out, "vkGetPhysicalDeviceMemoryProperties2");
+}
+
+static void VKAPI_CALL memory_properties2_khr(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties2 *out)
+{
+ memory_properties2(physical, out, "vkGetPhysicalDeviceMemoryProperties2KHR");
+}
+
PFN_vkVoidFunction hybris_icd_instance_proc(VkInstance instance, const char *name)
{
pthread_mutex_lock(&instance_guard);
@@ -310,6 +368,12 @@ PFN_vkVoidFunction hybris_icd_instance_proc(VkInstance instance, const char *nam
PFN_vkVoidFunction image = backend ? hybris_icd_swapchain_image_proc(name) : NULL;
if (image) return image;
/* Preserve the HAL's command scope and extension gating. */
+ if (backend && !strcmp(name, "vkGetPhysicalDeviceMemoryProperties"))
+ return (PFN_vkVoidFunction)memory_properties;
+ if (backend && !strcmp(name, "vkGetPhysicalDeviceMemoryProperties2"))
+ return (PFN_vkVoidFunction)memory_properties2_core;
+ if (backend && !strcmp(name, "vkGetPhysicalDeviceMemoryProperties2KHR"))
+ return (PFN_vkVoidFunction)memory_properties2_khr;
if (backend && !strcmp(name, "vkDestroyInstance"))
return (PFN_vkVoidFunction)destroy_instance;
if (backend && !strcmp(name, "vkEnumeratePhysicalDevices"))
@@ -0,0 +1,233 @@
diff --git a/hybris/vulkan/placed/placed_layer.c b/hybris/vulkan/placed/placed_layer.c
index 15bf8f5..9dc8b7d 100644
--- a/hybris/vulkan/placed/placed_layer.c
+++ b/hybris/vulkan/placed/placed_layer.c
@@ -37,7 +37,7 @@
#define MAP_FIXED_NOREPLACE 0x100000
#endif
-enum backend { BACKEND_UNSUPPORTED, BACKEND_OPAQUE, BACKEND_NATIVE_ALIAS };
+enum backend { BACKEND_UNSUPPORTED, BACKEND_OPAQUE, BACKEND_NATIVE_ALIAS, BACKEND_DEDICATED_EXPORT };
struct alloc {
VkAllocationCallbacks cb;
@@ -162,6 +162,7 @@ struct resource {
};
struct memory {
VkDeviceMemory h;
+ VkBuffer hidden;
VkDeviceSize size;
int exportable, fd;
void *native, *alias;
@@ -477,10 +478,6 @@ static enum backend select_backend(struct instance *i, VkPhysicalDevice p) {
if (!properties)
return BACKEND_OPAQUE;
properties(p, &props);
- /* Preserve the original OPAQUE_FD path for non-Mali drivers. Some drivers
- * reject a combined capability query while supporting each real resource. */
- if (props.vendorID != 0x13b5)
- return BACKEND_OPAQUE;
PFN_vkGetPhysicalDeviceExternalBufferProperties f =
(void *)iproc(i, "vkGetPhysicalDeviceExternalBufferProperties");
if (!f)
@@ -494,11 +491,21 @@ static enum backend select_backend(struct instance *i, VkPhysicalDevice p) {
.handleType = OPAQUE};
VkExternalBufferProperties out = {.sType = VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES};
f(p, &in, &out);
- if ((out.externalMemoryProperties.externalMemoryFeatures &
- VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT) &&
- (out.externalMemoryProperties.compatibleHandleTypes & OPAQUE))
+ VkExternalMemoryFeatureFlags features = out.externalMemoryProperties.externalMemoryFeatures;
+ int exportable = (features & VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT) &&
+ (out.externalMemoryProperties.compatibleHandleTypes & OPAQUE);
+ /* Qualcomm reports OPAQUE_FD export as dedicated-only: external resources then bind
+ * only to dedicated exported memory and cannot use the cached host-visible type. */
+ if (props.vendorID != 0x13b5 && exportable &&
+ (features & VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT))
+ return BACKEND_DEDICATED_EXPORT;
+ if (exportable)
return BACKEND_OPAQUE;
}
+ /* Preserve the original OPAQUE_FD path for non-Mali drivers. Some drivers
+ * reject a combined capability query while supporting each real resource. */
+ if (props.vendorID != 0x13b5)
+ return BACKEND_OPAQUE;
return have_mali_mapping_lock() ? BACKEND_NATIVE_ALIAS : BACKEND_UNSUPPORTED;
}
static VkResult VKAPI_CALL l_CreateDevice(VkPhysicalDevice p, const VkDeviceCreateInfo *ci,
@@ -609,7 +616,7 @@ static VkResult VKAPI_CALL l_CreateDevice(VkPhysicalDevice p, const VkDeviceCrea
for (uint32_t n = 0; n < d->props.memoryTypeCount; n++)
if (d->props.memoryTypes[n].propertyFlags & HOST)
d->host_bits |= 1u << n;
- if (d->active && d->backend == BACKEND_OPAQUE && !d->GetMemoryFdKHR) {
+ if (d->active && d->backend != BACKEND_NATIVE_ALIAS && !d->GetMemoryFdKHR) {
d->DestroyDevice(d->h, ac);
result = VK_ERROR_EXTENSION_NOT_PRESENT;
goto failed;
@@ -620,7 +627,10 @@ static VkResult VKAPI_CALL l_CreateDevice(VkPhysicalDevice p, const VkDeviceCrea
pthread_mutex_unlock(&lock);
if (d->active)
fprintf(stderr, "DD_PLACED device active backend=%s page=%zu host_bits=%08x\n",
- d->backend == BACKEND_NATIVE_ALIAS ? "native-alias" : "opaque", page_size(),
+ d->backend == BACKEND_NATIVE_ALIAS ? "native-alias"
+ : d->backend == BACKEND_DEDICATED_EXPORT ? "dedicated-export"
+ : "opaque",
+ page_size(),
d->host_bits);
chain_free(&chain);
dealloc(a, exts);
@@ -794,7 +804,7 @@ static VkResult VKAPI_CALL l_CreateBuffer(VkDevice h, const VkBufferCreateInfo *
return VK_ERROR_INITIALIZATION_FAILED;
if (!d->active)
return d->CreateBuffer(h, ci, ac, out);
- if (d->backend == BACKEND_NATIVE_ALIAS)
+ if (d->backend != BACKEND_OPAQUE)
return d->CreateBuffer(h, ci, ac, out);
if (unsupported_external(ci->pNext, 0))
return VK_ERROR_INVALID_EXTERNAL_HANDLE;
@@ -845,7 +855,7 @@ static VkResult VKAPI_CALL l_CreateImage(VkDevice h, const VkImageCreateInfo *ci
return VK_ERROR_INITIALIZATION_FAILED;
if (!d->active)
return d->CreateImage(h, ci, ac, out);
- if (d->backend == BACKEND_NATIVE_ALIAS)
+ if (d->backend != BACKEND_OPAQUE)
return d->CreateImage(h, ci, ac, out);
if (unsupported_external(ci->pNext, 1))
return VK_ERROR_INVALID_EXTERNAL_HANDLE;
@@ -978,7 +988,7 @@ static void VKAPI_CALL l_GetDeviceBufferMemoryRequirements(
d->GetDeviceBufferMemoryRequirements(h, in, out);
return;
}
- if (d->backend == BACKEND_NATIVE_ALIAS) {
+ if (d->backend != BACKEND_OPAQUE) {
d->GetDeviceBufferMemoryRequirements(h, in, out);
return;
}
@@ -1011,7 +1021,7 @@ static void VKAPI_CALL l_GetDeviceImageMemoryRequirements(VkDevice h,
d->GetDeviceImageMemoryRequirements(h, in, out);
return;
}
- if (d->backend == BACKEND_NATIVE_ALIAS) {
+ if (d->backend != BACKEND_OPAQUE) {
d->GetDeviceImageMemoryRequirements(h, in, out);
return;
}
@@ -1051,6 +1061,84 @@ static int allocation_chain_supported(const void *p) {
return 1;
}
static int has_import(const void *p) { return !allocation_chain_supported(p); }
+static void track_memory(struct device *d, struct memory *m) {
+ pthread_mutex_lock(&lock);
+ m->next = d->memories;
+ d->memories = m;
+ pthread_mutex_unlock(&lock);
+}
+/* Resources stay native. A host-visible allocation that is not dedicated already is
+ * dedicated to a hidden buffer of its size so that it can be exported; the driver binds
+ * other resources to it and the layer never uses the buffer. */
+static VkResult allocate_dedicated_export(struct device *d, VkDevice h,
+ const VkMemoryAllocateInfo *ci,
+ const VkAllocationCallbacks *ac, VkDeviceMemory *out,
+ struct memory *m) {
+ int host = !!(d->host_bits & (1u << ci->memoryTypeIndex));
+ const VkMemoryDedicatedAllocateInfo *ded =
+ (void *)find_chain(ci->pNext, VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO);
+ int own = ded && (ded->buffer || ded->image);
+ VkResult r;
+ if (!host || has_import(ci->pNext) ||
+ find_chain(ci->pNext, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO)) {
+ r = d->AllocateMemory(h, ci, ac, out);
+ goto done;
+ }
+ VkMemoryAllocateInfo copy = *ci;
+ VkMemoryDedicatedAllocateInfo hidden = {.sType =
+ VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO};
+ VkExportMemoryAllocateInfo ext = {.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO,
+ .handleTypes = OPAQUE};
+ struct chain_copy chain = {.a = m->a};
+ if (!own) {
+ VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
+ .size = ci->allocationSize,
+ .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
+ VK_BUFFER_USAGE_TRANSFER_DST_BIT,
+ .sharingMode = VK_SHARING_MODE_EXCLUSIVE};
+ VkMemoryRequirements req = {0};
+ if (d->CreateBuffer(h, &bi, ac, &m->hidden) == VK_SUCCESS) {
+ d->GetBufferMemoryRequirements(h, m->hidden, &req);
+ if (!(req.memoryTypeBits & (1u << ci->memoryTypeIndex)) ||
+ req.size < ci->allocationSize) {
+ d->DestroyBuffer(h, m->hidden, ac);
+ m->hidden = VK_NULL_HANDLE;
+ }
+ } else
+ m->hidden = VK_NULL_HANDLE;
+ if (!m->hidden) {
+ if (atomic_fetch_add(&failure_logs, 1) < 64)
+ fprintf(stderr, "DD_PLACED dedicated-export: no hidden buffer for size=%llu type=%u\n",
+ (unsigned long long)ci->allocationSize, ci->memoryTypeIndex);
+ r = d->AllocateMemory(h, ci, ac, out);
+ goto done;
+ }
+ hidden.buffer = m->hidden;
+ copy.allocationSize = req.size;
+ r = chain_edit(ci->pNext, hidden.sType, &hidden, m->a, &chain);
+ if (r != VK_SUCCESS)
+ goto failed;
+ ext.pNext = chain.head;
+ } else
+ ext.pNext = (void *)ci->pNext;
+ copy.pNext = &ext;
+ r = d->AllocateMemory(h, &copy, ac, out);
+ chain_free(&chain);
+ if (r != VK_SUCCESS)
+ goto failed;
+ m->exportable = 1;
+done:
+ if (r != VK_SUCCESS)
+ goto failed;
+ m->h = *out;
+ track_memory(d, m);
+ return VK_SUCCESS;
+failed:
+ if (m->hidden)
+ d->DestroyBuffer(h, m->hidden, ac);
+ dealloc(m->a, m);
+ return r;
+}
static VkResult VKAPI_CALL l_AllocateMemory(VkDevice h, const VkMemoryAllocateInfo *ci,
const VkAllocationCallbacks *ac, VkDeviceMemory *out) {
struct device *d = get_device(h);
@@ -1084,6 +1172,8 @@ static VkResult VKAPI_CALL l_AllocateMemory(VkDevice h, const VkMemoryAllocateIn
pthread_mutex_unlock(&lock);
return VK_SUCCESS;
}
+ if (d->backend == BACKEND_DEDICATED_EXPORT)
+ return allocate_dedicated_export(d, h, ci, ac, out, m);
const VkExportMemoryAllocateInfo *existing =
(void *)find_chain(ci->pNext, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO);
VkExportMemoryAllocateInfo ext = {.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO,
@@ -1176,12 +1266,15 @@ static void VKAPI_CALL l_FreeMemory(VkDevice h, VkDeviceMemory memory,
break;
}
pthread_mutex_unlock(&lock);
+ VkBuffer hidden = m ? m->hidden : VK_NULL_HANDLE;
if (m) {
pthread_mutex_lock(&placement_lock);
cleanup_memory(d, m);
pthread_mutex_unlock(&placement_lock);
}
d->FreeMemory(h, memory, ac);
+ if (hidden)
+ d->DestroyBuffer(h, hidden, ac);
}
static VkResult VKAPI_CALL l_MapMemory(VkDevice h, VkDeviceMemory memory, VkDeviceSize offset,
VkDeviceSize size, VkMemoryMapFlags flags, void **out) {
@@ -1671,6 +1764,8 @@ static void VKAPI_CALL l_DestroyDevice(VkDevice h, const VkAllocationCallbacks *
while (d->memories) {
struct memory *m = d->memories;
d->memories = m->next;
+ if (m->hidden)
+ d->DestroyBuffer(h, m->hidden, m->a.custom ? &m->a.cb : NULL);
pthread_mutex_lock(&placement_lock);
cleanup_memory(d, m);
pthread_mutex_unlock(&placement_lock);
+113
View File
@@ -0,0 +1,113 @@
#include <GL/gl.h>
#include <GL/glx.h>
#include <GL/glxext.h>
#include <X11/Xlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
XInitThreads();
Display *display = XOpenDisplay(NULL);
int opcode, event, error;
if (!display || XQueryExtension(display, "DRI3", &opcode, &event, &error)) {
fprintf(stderr, "This probe requires an X11 server without DRI3\n");
return 1;
}
const int attributes[] = {
GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT | GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_BIND_TO_TEXTURE_RGB_EXT, True,
GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, None
};
int count;
GLXFBConfig *configs = glXChooseFBConfig(display, DefaultScreen(display), attributes, &count);
XVisualInfo *visual = NULL;
GLXFBConfig config = NULL;
for (int i = 0; configs && i < count; ++i) {
visual = glXGetVisualFromFBConfig(display, configs[i]);
if (visual && visual->depth == 24) {
config = configs[i];
break;
}
if (visual) XFree(visual);
visual = NULL;
}
if (!config) return 1;
const int width = 17, height = 9;
Colormap colormap = XCreateColormap(display, RootWindow(display, visual->screen), visual->visual, AllocNone);
XSetWindowAttributes window_attributes = { .colormap = colormap };
Window output = XCreateWindow(display, RootWindow(display, visual->screen), 0, 0, width, height,
0, visual->depth, InputOutput, visual->visual, CWColormap, &window_attributes);
XMapWindow(display, output);
XSync(display, False);
GLXContext context = glXCreateNewContext(display, config, GLX_RGBA_TYPE, NULL, True);
if (!context || !glXMakeContextCurrent(display, output, output, context)) return 1;
const char *renderer = (const char *)glGetString(GL_RENDERER);
printf("Renderer: %s\n", renderer ? renderer : "unknown");
if (!renderer || !strstr(renderer, "zink") || !strstr(renderer, "Adreno")) return 1;
Pixmap pixmap = XCreatePixmap(display, RootWindow(display, visual->screen), width, height, visual->depth);
GC gc = XCreateGC(display, pixmap, 0, NULL);
const int texture_attributes[] = {
GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGB_EXT, None
};
GLXPixmap texture_pixmap = glXCreatePixmap(display, config, pixmap, texture_attributes);
PFNGLXBINDTEXIMAGEEXTPROC bind = (PFNGLXBINDTEXIMAGEEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXBindTexImageEXT");
PFNGLXRELEASETEXIMAGEEXTPROC release = (PFNGLXRELEASETEXIMAGEEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXReleaseTexImageEXT");
if (!texture_pixmap || !bind || !release) {
fprintf(stderr, "GLX pixmap setup failed\n");
return 1;
}
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DITHER);
glViewport(0, 0, width, height);
for (int phase = 0; phase < 2; ++phase) {
XSetForeground(display, gc, phase ? visual->blue_mask : visual->red_mask);
XFillRectangle(display, pixmap, gc, 0, 0, 8, height);
XSetForeground(display, gc, phase ? visual->red_mask | visual->green_mask : visual->green_mask);
XFillRectangle(display, pixmap, gc, 8, 0, width - 8, height);
XSync(display, False);
bind(display, texture_pixmap, GLX_FRONT_LEFT_EXT, NULL);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(-1, -1);
glTexCoord2f(1, 0); glVertex2f(1, -1);
glTexCoord2f(1, 1); glVertex2f(1, 1);
glTexCoord2f(0, 1); glVertex2f(-1, 1);
glEnd();
unsigned char pixels[17 * 9 * 4];
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
if (glGetError() != GL_NO_ERROR) return 1;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
unsigned char *pixel = &pixels[(y * width + x) * 4];
int red = phase ? x >= 8 : x < 8;
int green = x >= 8;
int blue = phase && x < 8;
if (pixel[0] != red * 255 || pixel[1] != green * 255 || pixel[2] != blue * 255 || pixel[3] != 255) {
fprintf(stderr, "Phase %d pixel %d,%d: %u %u %u %u\n", phase, x, y, pixel[0], pixel[1], pixel[2], pixel[3]);
return 1;
}
}
}
release(display, texture_pixmap, GLX_FRONT_LEFT_EXT);
}
puts("Pixmap bind/update: all 306 GPU readback pixels passed without DRI3");
glXDestroyPixmap(display, texture_pixmap);
XFreeGC(display, gc);
XFreePixmap(display, pixmap);
glDeleteTextures(1, &texture);
glXMakeContextCurrent(display, None, None, NULL);
glXDestroyContext(display, context);
XDestroyWindow(display, output);
XFreeColormap(display, colormap);
XFree(visual);
XFree(configs);
XCloseDisplay(display);
return 0;
}
+122
View File
@@ -0,0 +1,122 @@
"""Run a real Vulkan transfer and readback through the selected Linux ICD."""
import ctypes as c
import json
U = c.c_uint32
H = c.c_void_p
Q = c.c_uint64
def structure(name, fields):
return type(name, (c.Structure,), {'_fields_': fields})
Application = structure('Application', [('type', U), ('next', H), ('name', c.c_char_p), ('version', U), ('engine', c.c_char_p), ('engineVersion', U), ('api', U)])
Instance = structure('Instance', [('type', U), ('next', H), ('flags', U), ('application', c.POINTER(Application)), ('layerCount', U), ('layers', H), ('extensionCount', U), ('extensions', H)])
QueueCreate = structure('QueueCreate', [('type', U), ('next', H), ('flags', U), ('family', U), ('count', U), ('priorities', c.POINTER(c.c_float))])
DeviceCreate = structure('DeviceCreate', [('type', U), ('next', H), ('flags', U), ('queueCount', U), ('queues', c.POINTER(QueueCreate)), ('layerCount', U), ('layers', H), ('extensionCount', U), ('extensions', H), ('features', H)])
BufferCreate = structure('BufferCreate', [('type', U), ('next', H), ('flags', U), ('size', Q), ('usage', U), ('sharing', U), ('familyCount', U), ('families', H)])
Requirements = structure('Requirements', [('size', Q), ('alignment', Q), ('types', U)])
MemoryType = structure('MemoryType', [('flags', U), ('heap', U)])
Heap = structure('Heap', [('size', Q), ('flags', U)])
MemoryProperties = structure('MemoryProperties', [('typeCount', U), ('types', MemoryType * 32), ('heapCount', U), ('heaps', Heap * 16)])
Allocate = structure('Allocate', [('type', U), ('next', H), ('size', Q), ('index', U)])
PoolCreate = structure('PoolCreate', [('type', U), ('next', H), ('flags', U), ('family', U)])
CommandAllocate = structure('CommandAllocate', [('type', U), ('next', H), ('pool', H), ('level', U), ('count', U)])
Begin = structure('Begin', [('type', U), ('next', H), ('flags', U), ('inheritance', H)])
Barrier = structure('Barrier', [('type', U), ('next', H), ('source', U), ('destination', U)])
Copy = structure('Copy', [('source', Q), ('destination', Q), ('size', Q)])
Submit = structure('Submit', [('type', U), ('next', H), ('waitCount', U), ('waits', H), ('stages', H), ('commandCount', U), ('commands', c.POINTER(H)), ('signalCount', U), ('signals', H)])
def run():
vk = c.CDLL('libvulkan.so.1')
def function(name, arguments, result=c.c_int):
f = getattr(vk, name)
f.argtypes, f.restype = arguments, result
return f
def check(result, operation):
if result != 0:
raise RuntimeError(f'{operation}: VkResult {result}')
instance, device, pool = H(), H(), H()
buffers, memories = [], []
try:
app = Application(type=0, name=b'DroidDeck Qualcomm probe', api=(1 << 22) | (1 << 12))
info = Instance(type=1, application=c.pointer(app))
check(function('vkCreateInstance', [c.POINTER(Instance), H, c.POINTER(H)])(c.byref(info), None, c.byref(instance)), 'instance')
count = U()
enumerate_devices = function('vkEnumeratePhysicalDevices', [H, c.POINTER(U), c.POINTER(H)])
check(enumerate_devices(instance, c.byref(count), None), 'device count')
if not count.value: raise RuntimeError('No Vulkan devices')
devices = (H * count.value)()
check(enumerate_devices(instance, c.byref(count), devices), 'devices')
physical = H(devices[0])
properties = c.create_string_buffer(4096)
function('vkGetPhysicalDeviceProperties', [H, H], None)(physical, properties)
name = properties.raw[20:276].split(b'\0')[0].decode()
family_count = U()
families_fn = function('vkGetPhysicalDeviceQueueFamilyProperties', [H, c.POINTER(U), H], None)
families_fn(physical, c.byref(family_count), None)
families = (U * (family_count.value * 6))()
families_fn(physical, c.byref(family_count), families)
family = next(i for i in range(family_count.value) if families[i * 6] & 7)
priority = c.c_float(1)
queue_info = QueueCreate(type=2, family=family, count=1, priorities=c.pointer(priority))
device_info = DeviceCreate(type=3, queueCount=1, queues=c.pointer(queue_info))
check(function('vkCreateDevice', [H, c.POINTER(DeviceCreate), H, c.POINTER(H)])(physical, c.byref(device_info), None, c.byref(device)), 'device')
queue = H()
function('vkGetDeviceQueue', [H, U, U, c.POINTER(H)], None)(device, family, 0, c.byref(queue))
memory_props = MemoryProperties()
function('vkGetPhysicalDeviceMemoryProperties', [H, c.POINTER(MemoryProperties)], None)(physical, c.byref(memory_props))
for _ in range(2):
buffer = H()
buffer_info = BufferCreate(type=12, size=4096, usage=3)
check(function('vkCreateBuffer', [H, c.POINTER(BufferCreate), H, c.POINTER(H)])(device, c.byref(buffer_info), None, c.byref(buffer)), 'buffer')
buffers.append(buffer)
requirements = Requirements()
function('vkGetBufferMemoryRequirements', [H, H, c.POINTER(Requirements)], None)(device, buffer, c.byref(requirements))
index = next(i for i in range(memory_props.typeCount) if requirements.types & (1 << i) and memory_props.types[i].flags & 6 == 6)
allocation = Allocate(type=5, size=requirements.size, index=index)
memory = H()
check(function('vkAllocateMemory', [H, c.POINTER(Allocate), H, c.POINTER(H)])(device, c.byref(allocation), None, c.byref(memory)), 'memory')
memories.append(memory)
check(function('vkBindBufferMemory', [H, H, H, Q])(device, buffer, memory, 0), 'bind')
pool_info = PoolCreate(type=39, family=family)
check(function('vkCreateCommandPool', [H, c.POINTER(PoolCreate), H, c.POINTER(H)])(device, c.byref(pool_info), None, c.byref(pool)), 'pool')
command = H()
command_info = CommandAllocate(type=40, pool=pool, count=1)
check(function('vkAllocateCommandBuffers', [H, c.POINTER(CommandAllocate), c.POINTER(H)])(device, c.byref(command_info), c.byref(command)), 'command')
begin = Begin(type=42, flags=1)
check(function('vkBeginCommandBuffer', [H, c.POINTER(Begin)])(command, c.byref(begin)), 'begin')
pattern = 0x5A17C0DE
function('vkCmdFillBuffer', [H, H, Q, Q, U], None)(command, buffers[0], 0, 4096, pattern)
barrier_fn = function('vkCmdPipelineBarrier', [H, U, U, U, U, c.POINTER(Barrier), U, H, U, H], None)
barrier = Barrier(type=46, source=0x1000, destination=0x800)
barrier_fn(command, 0x1000, 0x1000, 0, 1, c.byref(barrier), 0, None, 0, None)
region = Copy(size=4096)
function('vkCmdCopyBuffer', [H, H, H, U, c.POINTER(Copy)], None)(command, buffers[0], buffers[1], 1, c.byref(region))
barrier = Barrier(type=46, source=0x1000, destination=0x2000)
barrier_fn(command, 0x1000, 0x4000, 0, 1, c.byref(barrier), 0, None, 0, None)
check(function('vkEndCommandBuffer', [H])(command), 'end')
submit = Submit(type=4, commandCount=1, commands=c.pointer(command))
check(function('vkQueueSubmit', [H, U, c.POINTER(Submit), H])(queue, 1, c.byref(submit), None), 'submit')
check(function('vkQueueWaitIdle', [H])(queue), 'wait')
mapped = H()
check(function('vkMapMemory', [H, H, Q, Q, U, c.POINTER(H)])(device, memories[1], 0, 4096, 0, c.byref(mapped)), 'map')
words = list((U * 1024).from_address(mapped.value))
function('vkUnmapMemory', [H, H], None)(device, memories[1])
if words != [pattern] * 1024: raise RuntimeError('GPU transfer readback mismatch')
print(json.dumps({'status': 'PASS', 'device': name, 'gpu_fill_copy_readback_bytes': 4096}))
finally:
if device:
function('vkDeviceWaitIdle', [H])(device)
if pool: function('vkDestroyCommandPool', [H, H, H], None)(device, pool, None)
for buffer in buffers: function('vkDestroyBuffer', [H, H, H], None)(device, buffer, None)
for memory in memories: function('vkFreeMemory', [H, H, H], None)(device, memory, None)
function('vkDestroyDevice', [H, H], None)(device, None)
if instance: function('vkDestroyInstance', [H, H], None)(instance, None)
if __name__ == '__main__':
run()
+5
View File
@@ -0,0 +1,5 @@
export LD_LIBRARY_PATH="$DROIDDECK_QUALCOMM_ROOT/mesa${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export LIBGL_DRIVERS_PATH="$DROIDDECK_QUALCOMM_ROOT/mesa/dri"
export GBM_BACKENDS_PATH="$DROIDDECK_QUALCOMM_ROOT/mesa/gbm"
export __GLX_VENDOR_LIBRARY_NAME=droiddeck_qualcomm
export __EGL_VENDOR_LIBRARY_FILENAMES="$DROIDDECK_QUALCOMM_ROOT/mesa/egl-vendor.json"
+310
View File
@@ -0,0 +1,310 @@
{
"url": "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/hybris-runtime-4ed93fb9-dda132a6de-qa/runtime.tzst",
"sha256": "743d11363e73b41ef33167e598bf23c7f21b673281faaf18f22e99ee4fda1952",
"size": 5806382,
"provenance": {
"builder": "wallentx/DroidDeck tools/hybris",
"producer_commit": "4ed93fb9ee6e2a0b24ff087196f2e93d247fd985",
"upstream_source_commit": "bc8cb3586b79d208fd21b925fa0209b3e432e008",
"added_patches": [
"tools/qualcomm/hybris-patches/0012-android-loader-wrapped-queries.patch",
"tools/qualcomm/hybris-patches/0013-calibrated-timestamps-khr-alias.patch",
"tools/qualcomm/hybris-patches/0014-trim-covered-host-memory-types.patch",
"tools/qualcomm/hybris-patches/0015-placed-memory-dedicated-export.patch"
],
"patch_commit": "a132a6de9786fd449d7fd9f0075a8fe897e935e1",
"component_ci_run": "https://github.com/Droid-Deck/DroidDeck-Components/actions/runs/40284992208",
"previous_build": {
"url": "https://github.com/wallentx/DroidDeck/releases/download/hybris-4ed93fb9ee6e2a0b24ff087196f2e93d247fd985/runtime.tzst",
"component_ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/39360327540"
}
},
"gamescope": {
"source_commit": "8f212644c46460549035971ab914421180f61a7c",
"member_sha256": "8c0c4ac3e3dc8223ded69945335f17f98d011e72380f4ae5e6d8daf284ded42c",
"build": {
"binary": "build/qualcomm-gamescope/gamescope",
"source": "build/qualcomm-gamescope/source.tar.gz",
"source_sha256": "c6484b98d8fe1f51042245360359dde6de0381db5316e50b78699a28423d8c97",
"source_size": 10054134
},
"patches": {
"tools/gamescope/patches/0002-steamcompmgr-fallback-appid-focus.patch": "611989049383b9d3a5d30f908a5dbe164c7ee5a4d451bebb9c108d6ba9a2d02b",
"tools/gamescope/patches/0009-fix-arm64-steam-night-mode.patch": "201ca8388f5376f03e5d001b3dbb8e5c404b38b81d443f456ae4fac17365866e",
"tools/gamescope/patches/0019-steamcompmgr-arm64-virtual-white.patch": "eeb5a5ea9b2a876ebbf04168f95b6520973ed05c2cf587bcf762cfc5460ecfe9",
"tools/gamescope/patches/0020-color-p3-red-is-wide-gamut.patch": "4a2532480acabce47dde01674fd0258b47141d2ab1233e0f8d0498ec0537da98",
"tools/gamescope/patches/0100-realtime-queue-and-gamepad-cursor.patch": "d7ad2ab66d7d0ecc73f20f412194fac74b764610fb651d23abb8fcec4e06ba04",
"tools/gamescope/patches/0101-nested-wayland-cursor-routing.patch": "4502958ed9a481e4c028fbee35340bc02637e484e6e5dc4e006e9c208e985440",
"tools/gamescope/patches/0110-wayland-backend-touch.patch": "2fab269c671829e75f8a45b3ebd2d8432969a13de8ac4421d7067444c51af312",
"tools/gamescope/patches/0111-wayland-pointer-warps-in-passthrough.patch": "8aeffc39fe778b73d9117badfb318cbdb3b7931bcf2626c6e6c8ace9b85776ac",
"tools/gamescope/patches/0112-restore-iconified-game-on-resume.patch": "475398b3435d2619932eaff9eacb4108a2efc85441cc48fde43d13da4e869d4d",
"tools/gamescope/patches/0114-take-override-redirect-from-mapnotify.patch": "56cf10c38f48569872263e63fc46964133e238c9421b3eba7a55fa78c24cc8a7",
"tools/gamescope/patches/0115-limiter-paces-per-window.patch": "6ee6df85d9d8093ee8b86fc146151dbb19c3c73f475849648751f553be4629ad",
"tools/gamescope/patches/0116-hold-overlay-repaint-for-next-frame.patch": "0affbf6d41cc7cfbf22b2f06bb5caa8504ac38506dc96abe684f35b60f18007d",
"tools/gamescope/patches/0116-release-cursor-shm-buffers.patch": "17e189efafbc9f086f62d2cb61adf03816827da1364e2161ec9015e9dea99375",
"tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch": "bf476ae58f77f0b6ca35b99930eae8fa554e2d565884dce5165d9f3faf3027d7",
"tools/qualcomm/gamescope-patches/0120-nested-swapchain-capability-fallback.patch": "905bd09e78025058ba0a777e96462f81b21775c641cc439669c2d75d39806e9c",
"tools/qualcomm/gamescope-patches/0122-dmabuf-import-memory-type.patch": "7c56d2b9cabb83e5ae0767a1d8fb3a026a68386a7840a225a515a4546f39f3b1",
"tools/qualcomm/gamescope-patches/0124-sdl-preserve-explicit-refresh.patch": "049012ccb4612e664530ebe9b8b4f00f60b0e82029b25fb58b6e09325c1c9ea0",
"tools/qualcomm/gamescope-patches/0125-sdl-wait-before-present.patch": "a0795bf0281692e121cee6dfcd3e7a0fa9d0bdeae1d7ed49db76691c7f636b82",
"tools/qualcomm/gamescope-patches/0126-shm-commit-ready.patch": "78c3f70565a5dd5b7c5ff0540156ae45a17a9f7ecc1a2954d663d845c2b8ba4b",
"tools/qualcomm/gamescope-patches/0127-refresh-shm-buffer-contents.patch": "cc9599d1699862a32f57edf74f8ec95f4db70e660777329af3d8ead3283a23f3",
"tools/qualcomm/gamescope-patches/0128-keep-swapchain-shm-textures-internal.patch": "929c9376c97124d1dcac72425ea9d71c71afb5eb775374a76fd21f64ed1a078d",
"tools/qualcomm/gamescope-patches/0129-keep-swapchain-cursors-internal.patch": "b4c81ff643a0c326c4a235210ef5508be5cc5cdc31967fdb76c76a7abfd4e241",
"tools/qualcomm/gamescope-patches/0130-explicit-float-header.patch": "4ee21fc758f460be15a503c714daadf3d930ee8bf0306ee4e8ba28b1f0d609c9",
"tools/qualcomm/constant-yuv-samplers.patch": "0d55360a560d13e28b8d57befc2a6e95b5b2678e0d1c11b9e275937d698698a5",
"tools/qualcomm/gamescope-no-dmabuf.patch": "b4ffa0fd0dbfc754b896261669df924e5545e486f2438bc130965702f006090d",
"tools/qualcomm/gamescope-linear-dmabuf.patch": "b58933508e0c879a91bc174ed7995371bb35a91afab313e6d44994d52583ec9f"
}
},
"builds": {
"url": "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/qualcomm-runtime-r3-4b8c7f84-qa/qualcomm-builds.tar.xz",
"sha256": "aac4a5dea4acacfb7004e9c4703a8e606d1032c7dfb9732b8609a1257997865f",
"size": 15136448
},
"wsi": {
"files": [
{
"mode": 420,
"name": "libVkLayer_window_system_integration.so",
"path": "wsi/libVkLayer_window_system_integration.so",
"sha256": "4319d14947c6957ae4f58897a6adc8a4194e68728dee9ff386a87e6a93845706",
"size": 397384,
"built": true
},
{
"mode": 420,
"name": "VkLayer_window_system_integration.json",
"path": "wsi/VkLayer_window_system_integration.json",
"sha256": "b80f1a621be6994e5cdb4760acee98bb013d0ff57fd63b1cc8de17cc764daaa2",
"size": 3754,
"built": true
},
{
"mode": 420,
"name": "LICENSE",
"path": "licenses/wsi-LICENSE",
"sha256": "5eb8d2da52230d2d66ce078a89ae0173aac63e2e73bed5f907a34736d114ea30",
"size": 1086
},
{
"mode": 420,
"name": "source-commit",
"path": "provenance/wsi-source-commit",
"sha256": "8367150b20502af36c472651850694a15a3e2a1fd6b6beb1f6e12a85a97824f5",
"size": 41
},
{
"mode": 420,
"name": "SHA256SUMS",
"path": "provenance/wsi-SHA256SUMS",
"sha256": "fda6f61028659648801de0e3a6fe1676efd99e1551881a5db8630970eae86158",
"size": 108
},
{
"mode": 420,
"name": "downstream.patch",
"path": "licenses/wsi-downstream.patch",
"sha256": "e2ed113d22f05563248ef606c774c22658b184fbc05912229007cd5281027e78",
"size": 769
},
{
"mode": 420,
"name": "source.tar.zst",
"path": "licenses/wsi-source.tar.zst",
"sha256": "22ae7c2d8aa3dfffdda601c3442d1966ab53ad225acdfadee69ba38974d0c4c5",
"size": 209468
},
{
"mode": 420,
"name": "vulkan-headers-commit",
"path": "provenance/wsi-vulkan-headers-commit",
"sha256": "16706d6cdbeb788426a90d66574dfd71068c4d993d39e76ec5c281b1f30dc7a6",
"size": 41
},
{
"built": true,
"mode": 420,
"name": "0001-wayland-icd-exported-linear-buffers.patch",
"path": "licenses/wsi-patches/0001-wayland-icd-exported-linear-buffers.patch",
"sha256": "fc1653c6d9ab718d296ece224f8a923f7c10cd0a3486f765af11306ca1c59f6c",
"size": 19862
},
{
"built": true,
"mode": 420,
"name": "0002-gcc16-stdc-version.patch",
"path": "licenses/wsi-patches/0002-gcc16-stdc-version.patch",
"sha256": "5a303b7f69c8ab819596bbf93ce9f68006e4473d2b383b6109941976da9d075a",
"size": 2202
},
{
"built": true,
"mode": 420,
"name": "0003-dma-heap-read-only-open.patch",
"path": "licenses/wsi-patches/0003-dma-heap-read-only-open.patch",
"sha256": "891f89c80310b2e5a7a3d8337632fddaaedad803b6337e69053048dd6c6ba3c0",
"size": 623
},
{
"built": true,
"mode": 420,
"name": "0004-acquire-next-image2-on-vulkan-1-0.patch",
"path": "licenses/wsi-patches/0004-acquire-next-image2-on-vulkan-1-0.patch",
"sha256": "30e968889e22f3ba4ea2e0c3b80e3752c4d61898e256230392a0242d125ec239",
"size": 1541
},
{
"built": true,
"mode": 420,
"name": "0005-optional-wayland-platform.patch",
"path": "licenses/wsi-patches/0005-optional-wayland-platform.patch",
"sha256": "ab634299e5a6f1156f4d435314c50c893c60a43e8a6726498c9a39109f5676e0",
"size": 5882
}
],
"id": "wsi",
"ignored": [],
"provenance": {
"ci_run": "https://github.com/wallentx/DroidDeck/actions/runs/38047627963",
"repository_commit": "abe58618a5194f1f15499cbd5f9ec75503782556",
"vulkan_headers_licenses": {
"note": "Added from tracked assembly inputs; the original WSI archive and compiled library are unchanged.",
"revision": "8d6039a455a7ecc7d2a592ff97f62db4e59b70bf",
"source_urls": [
"https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/8d6039a455a7ecc7d2a592ff97f62db4e59b70bf/LICENSE.md",
"https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/8d6039a455a7ecc7d2a592ff97f62db4e59b70bf/LICENSES/MIT.txt"
]
},
"mirrored_from": "https://github.com/wallentx/DroidDeck/releases/download/v0.3.2-progress.20261010.4/wsi-abe5861.zip"
},
"recipe_inputs": {
"tools/vulkan-wsi/build.sh": "9e403151c58e6b2ee15241f525c4bacb2495f072191da6a63065e7fcc25b3b3c",
"tools/vulkan-wsi/licenses/Vulkan-Headers/LICENSE.md": "95ad366d23fadf701d355bc45fb8b82ae2d700239471d35d41286ac3b08ff903",
"tools/vulkan-wsi/licenses/Vulkan-Headers/MIT.txt": "1ca3502222d967f3be5751c55f6b7ee735b5383909c3b501495f54b216dbf227",
"tools/vulkan-wsi/patches/0001-link-x11-external-memory.patch": "e2ed113d22f05563248ef606c774c22658b184fbc05912229007cd5281027e78",
"tools/vulkan-wsi/source.env": "71a88087265a09b4ce06e7c9b98ef6799c6a7657cc6ef9084de663e96f5cfe63"
},
"sha256": "348f9ec42159c1ee6e2baba4312a5e845d26687238f29e3f4a1b0c3c97e13b3c",
"size": 362717,
"url": "https://github.com/Droid-Deck/DroidDeck-Components/releases/download/qualcomm-runtime-r3-4b8c7f84-qa/wsi-abe5861.zip",
"build": {
"directory": "build/qualcomm-wsi"
}
},
"shaders": {
"url": "https://codeload.github.com/ValveSoftware/gamescope/tar.gz/8f212644c46460549035971ab914421180f61a7c",
"sha256": "40b75e449168caed811824b20716e2e7d236cf1bea6fb7dcfd742d50c8c6d6cc",
"size": 970867,
"source_commit": "8f212644c46460549035971ab914421180f61a7c",
"replacements": {
"05a8bfdf4ff5d71b": "cs_gaussian_blur_horizontal",
"ee0a3fcfa1cf1281": "cs_composite_rcas_1px",
"519ce32f2e53f5db": "cs_composite_rcas",
"ee86eeb49ae9951c": "cs_composite_blur_cond",
"73368f4579fe0d27": "cs_composite_blur",
"80346d82c5a6d850": "cs_composite_blit"
}
},
"mesa": {
"source_commit": "31e9a6b2e95e30d84bf3177d1f497d063e59b6b2",
"directory": "build/qualcomm-zink/runtime",
"files": [
{
"path": "dri/zink_dri.so",
"sha256": "5f6c653df307d04451a70e3a2f086bee2f0c4a8cbeecd278e2b619b45ee0098f",
"size": 133368
},
{
"path": "egl-vendor.json",
"sha256": "5bb351d2e10383f865f5b67d44bfff9a6a8964c6cc969efb1d94a058ef11f48d",
"size": 92
},
{
"path": "gbm/dri_gbm.so",
"sha256": "5d99296fa5c898e43d104610f9a8cc78ed8d4776100a00a5dfc5de2c29d1993b",
"size": 134024
},
{
"path": "libEGL_droiddeck_qualcomm.so.0",
"sha256": "f99c99b8edd380891bc18e276decb687b76e2dd249e7fe3fbded9aaf1f938d90",
"size": 398632
},
{
"path": "libgallium-26.2.3.so",
"sha256": "f05580834e111df6f8ddaa8c96620f80317e40fb8032ee4eebb668c14c4cf401",
"size": 21578352
},
{
"path": "libgbm.so.1",
"sha256": "3a4018b5afea4de258c8b116e8e0f94bb2488a57ad2f63b0d5021d4cc922d91e",
"size": 67840
},
{
"path": "libGLX_droiddeck_qualcomm.so.0",
"sha256": "bae86c5d5847e245f790174ff68646d5ab1c68224cbb55faf0c53d15ef152b5f",
"size": 397704
},
{
"path": "licenses/Apache-2.0",
"sha256": "7e4d3fba250d15e9e0afa380d4b611828fa2560cc8fdebe95bcf2f01a487de12",
"size": 10045
},
{
"path": "licenses/BSL-1.0",
"sha256": "9b9fea7520a816107fcac2598b7c0155222f16bc430e989706b22f4367f1df7d",
"size": 1649
},
{
"path": "licenses/exceptions/Linux-Syscall-Note",
"sha256": "9b4084655174654608fd037e9ddb4feeadfada01cd042e9c17b05aa7105b2b9f",
"size": 1257
},
{
"path": "licenses/GPL-1.0-or-later",
"sha256": "8ff76f1528e6e4e9400c0f6b1f2d19d4979aaac3bcc44bb707a55389132825c4",
"size": 13047
},
{
"path": "licenses/GPL-2.0-only",
"sha256": "6667ad4063569cd53b13500550d93fcd3dc11bcf82c5514296af013a0b720ba5",
"size": 18424
},
{
"path": "licenses/Mesa-license.rst",
"sha256": "0d1a0472ecc81830e75c20d59b0ea02841e3db21255e0ebad97ab682c54d6615",
"size": 1816
},
{
"path": "licenses/MIT",
"sha256": "323c587d0ccf10e376f8bf9a7f31fb4ca6078105194b42e0b1e0ee2bc9bde71f",
"size": 1372
},
{
"path": "licenses/SGI-B-2.0",
"sha256": "686bf035a1fd22076416fd3b90370ac67771e884bf57f55693d51f8ce7c710a7",
"size": 1822
},
{
"path": "licenses/source.json",
"sha256": "e1640432c0505d5464d14c593bda1ffc944eac5005da560bdea162efc23f1add",
"size": 860
},
{
"path": "licenses/zink-optional-maintenance5.patch",
"sha256": "25f0733bc42199344f205a916f6674d578a9a78250fd6b4cecbfb1cbbc8f8cf5",
"size": 1682
},
{
"path": "licenses/zink-pixmap-without-dri3.patch",
"sha256": "8a0b0480be2823cc5df2bb5510c2f39a1402da9cb9199602d7bf691c5c486100",
"size": 1907
},
{
"path": "qualcomm-gl.sh",
"sha256": "2ed84bb2a5fa20cde52f18733fe3e8d1fda22f3f0d0bdad47363ff71a04522f5",
"size": 353
}
]
}
}
+94
View File
@@ -0,0 +1,94 @@
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
static PFN_vkGetInstanceProcAddr next_instance;
static PFN_vkGetDeviceProcAddr next_device;
static int gamescope;
static PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance, const char *);
static PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice, const char *);
static VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator, VkInstance *instance) {
VkLayerInstanceCreateInfo *chain = (void *)info->pNext;
while (chain && (chain->sType != VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO || chain->function != VK_LAYER_LINK_INFO)) chain = (void *)chain->pNext;
if (!chain) return VK_ERROR_INITIALIZATION_FAILED;
next_instance = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
gamescope = info->pApplicationInfo && info->pApplicationInfo->pApplicationName &&
!strcmp(info->pApplicationInfo->pApplicationName, "gamescope");
PFN_vkCreateInstance create = (void *)next_instance(0, "vkCreateInstance");
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
return create(info, allocator, instance);
}
static VkResult VKAPI_CALL create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info, const VkAllocationCallbacks *allocator, VkDevice *device) {
VkLayerDeviceCreateInfo *chain = (void *)info->pNext;
while (chain && (chain->sType != VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO || chain->function != VK_LAYER_LINK_INFO)) chain = (void *)chain->pNext;
if (!chain) return VK_ERROR_INITIALIZATION_FAILED;
PFN_vkGetInstanceProcAddr get = chain->u.pLayerInfo->pfnNextGetInstanceProcAddr;
next_device = chain->u.pLayerInfo->pfnNextGetDeviceProcAddr;
PFN_vkCreateDevice create = (void *)get(0, "vkCreateDevice");
chain->u.pLayerInfo = chain->u.pLayerInfo->pNext;
return create(physical, info, allocator, device);
}
static uint64_t fingerprint(const void *data, size_t size) {
const unsigned char *bytes = data;
uint64_t hash = 14695981039346656037ULL;
while (size--) hash = (hash ^ *bytes++) * 1099511628211ULL;
return hash;
}
static VkResult VKAPI_CALL create_shader(VkDevice device, const VkShaderModuleCreateInfo *info, const VkAllocationCallbacks *allocator, VkShaderModule *module) {
PFN_vkCreateShaderModule create = (void *)next_device(device, "vkCreateShaderModule");
const char *directory = getenv("DROIDDECK_QUALCOMM_SHADERS");
void *data = 0;
VkShaderModuleCreateInfo replacement = *info;
if (directory && gamescope) {
char path[4096];
snprintf(path, sizeof(path), "%s/%016llx.spv", directory, (unsigned long long)fingerprint(info->pCode, info->codeSize));
FILE *file = fopen(path, "rb");
if (file) {
fseek(file, 0, SEEK_END);
long size = ftell(file);
rewind(file);
if (size > 20 && size < 4194304 && !(size & 3)) {
data = malloc(size);
if (data && fread(data, 1, size, file) == (size_t)size && *(const uint32_t *)data == 0x07230203) {
replacement.codeSize = size;
replacement.pCode = data;
fprintf(stderr, "Qualcomm: substituting Gamescope shader %016llx\n", (unsigned long long)fingerprint(info->pCode, info->codeSize));
}
}
fclose(file);
}
}
VkResult result = create(device, &replacement, allocator, module);
free(data);
return result;
}
static PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char *name) {
if (!strcmp(name, "vkGetDeviceProcAddr")) return (void *)device_proc;
if (!strcmp(name, "vkCreateShaderModule")) return (void *)create_shader;
return next_device ? next_device(device, name) : 0;
}
static PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char *name) {
if (!strcmp(name, "vkGetInstanceProcAddr")) return (void *)instance_proc;
if (!strcmp(name, "vkGetDeviceProcAddr")) return (void *)device_proc;
if (!strcmp(name, "vkCreateInstance")) return (void *)create_instance;
if (!strcmp(name, "vkCreateDevice")) return (void *)create_device;
if (!strcmp(name, "vkCreateShaderModule")) return (void *)create_shader;
return next_instance ? next_instance(instance, name) : 0;
}
VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *interface) {
if (interface->loaderLayerInterfaceVersion > 2) interface->loaderLayerInterfaceVersion = 2;
interface->pfnGetInstanceProcAddr = instance_proc;
interface->pfnGetDeviceProcAddr = device_proc;
interface->pfnGetPhysicalDeviceProcAddr = 0;
return VK_SUCCESS;
}
@@ -0,0 +1,434 @@
diff --git a/wsi/display/swapchain.cpp b/wsi/display/swapchain.cpp
index 12bd8d0..d4cfac8 100644
--- a/wsi/display/swapchain.cpp
+++ b/wsi/display/swapchain.cpp
@@ -198,7 +198,7 @@ VkResult swapchain::init_image_factory(const VkSwapchainCreateInfoKHR &swapchain
wsialloc_create_info_args wsialloc_args = { external_image_create_info.selected_format,
external_image_create_info.flags, external_image_create_info.extent,
- external_image_create_info.explicit_compression };
+ external_image_create_info.explicit_compression, false };
auto backing_memory_creator =
m_allocator.make_unique<external_image_backing_memory_creator>(m_device_data, *m_wsi_allocator, wsialloc_args);
diff --git a/wsi/extensions/external_memory_extension.cpp b/wsi/extensions/external_memory_extension.cpp
index c5bd7e8..f52c760 100644
--- a/wsi/extensions/external_memory_extension.cpp
+++ b/wsi/extensions/external_memory_extension.cpp
@@ -35,10 +35,46 @@
#include "external_memory_extension.hpp"
#include "wsi/image_usage.hpp"
+#include "wsi/wsi_factory.hpp"
+
+#include <drm_fourcc.h>
namespace
{
+bool linear_dma_buf_exportable(VkPhysicalDevice physical_device, const VkImageCreateInfo &image_create_info)
+{
+ VkPhysicalDeviceExternalImageFormatInfoKHR external_info = {};
+ external_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO_KHR;
+ external_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
+
+ VkPhysicalDeviceImageFormatInfo2KHR image_info = {};
+ image_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2_KHR;
+ image_info.pNext = &external_info;
+ image_info.format = image_create_info.format;
+ image_info.type = image_create_info.imageType;
+ image_info.tiling = VK_IMAGE_TILING_LINEAR;
+ image_info.usage = image_create_info.usage;
+ image_info.flags = image_create_info.flags;
+
+ VkExternalImageFormatPropertiesKHR external_props = {};
+ external_props.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR;
+ VkImageFormatProperties2KHR format_props = {};
+ format_props.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
+ format_props.pNext = &external_props;
+
+ auto &instance_data = layer::instance_private_data::get(physical_device);
+ if (instance_data.disp.GetPhysicalDeviceImageFormatProperties2KHR(physical_device, &image_info, &format_props) !=
+ VK_SUCCESS)
+ {
+ return false;
+ }
+ const auto &limits = format_props.imageFormatProperties.maxExtent;
+ return (external_props.externalMemoryProperties.externalMemoryFeatures &
+ VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT) != 0 &&
+ limits.width >= image_create_info.extent.width && limits.height >= image_create_info.extent.height;
+}
+
VkImageCreateFlags2KHR get_image_create_flags(const VkImageCreateInfo &image_create_info) noexcept
{
const auto *flags2 = util::find_extension<VkImageCreateFlags2CreateInfoKHR>(
@@ -284,6 +320,39 @@ std::variant<VkResult, util::unique_ptr<swapchain_image_create_external_memory>>
util::vector<VkDrmFormatModifierPropertiesEXT> drm_format_props(
util::allocator(allocator, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
+ util::extension_list device_extensions{ util::allocator(allocator, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND) };
+ TRY_LOG_CALL(get_available_device_extensions(physical_device, device_extensions));
+ if (!device_extensions.contains(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME))
+ {
+ const uint32_t fourcc = util::drm::vk_to_drm_format(image_create_info.format);
+ bool linear_offered = false;
+ for (const auto &format : surface_formats)
+ {
+ linear_offered = linear_offered || (format.fourcc == fourcc && format.modifier == DRM_FORMAT_MOD_LINEAR);
+ }
+ if (!linear_offered || !linear_dma_buf_exportable(physical_device, image_create_info))
+ {
+ WSI_LOG_ERROR("The driver has no DRM format modifiers and cannot export a LINEAR image the compositor accepts.");
+ return VK_ERROR_INITIALIZATION_FAILED;
+ }
+
+ wsialloc_allocate_result exported = {};
+ exported.format.fourcc = fourcc;
+ exported.format.modifier = DRM_FORMAT_MOD_LINEAR;
+ for (auto &fd : exported.buffer_fds)
+ {
+ fd = -1;
+ }
+ auto ext_memory = allocator.make_unique<swapchain_image_create_external_memory>(
+ image_create_info, compression, exported, util::vector<VkSubresourceLayout>(allocator), drm_format_props,
+ true);
+ if (ext_memory == nullptr)
+ {
+ return VK_ERROR_OUT_OF_HOST_MEMORY;
+ }
+ return ext_memory;
+ }
+
TRY_LOG_CALL(get_surface_compatible_formats(image_create_info, physical_device, compression, surface_formats,
importable_formats, exportable_modifiers, drm_format_props));
@@ -316,7 +385,7 @@ std::variant<VkResult, util::unique_ptr<swapchain_image_create_external_memory>>
swapchain_image_create_external_memory::swapchain_image_create_external_memory(
const VkImageCreateInfo &image_create_info, std::optional<image_create_compression_control> &compression,
wsialloc_allocate_result wsialloc_selected_format, util::vector<VkSubresourceLayout> plane_layouts,
- const util::vector<VkDrmFormatModifierPropertiesEXT> &drm_format_props)
+ const util::vector<VkDrmFormatModifierPropertiesEXT> &drm_format_props, bool icd_export)
: m_wsialloc_selected_format(wsialloc_selected_format)
, m_create_flags()
, m_create_extent()
@@ -325,6 +394,7 @@ swapchain_image_create_external_memory::swapchain_image_create_external_memory(
, m_plane_layouts(std::move(plane_layouts))
, m_drm_mod_info()
, m_external_info()
+ , m_icd_export(icd_export)
{
if (compression)
{
@@ -354,6 +424,16 @@ VkResult swapchain_image_create_external_memory::extend_image_create_info(VkImag
{
assert(image_create_info != nullptr);
+ if (m_icd_export)
+ {
+ m_external_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR;
+ m_external_info.pNext = image_create_info->pNext;
+ m_external_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
+ image_create_info->pNext = &m_external_info;
+ image_create_info->tiling = VK_IMAGE_TILING_LINEAR;
+ return VK_SUCCESS;
+ }
+
if (m_wsialloc_selected_format.is_disjoint)
{
auto *image_create_flags2 = util::find_extension<VkImageCreateFlags2CreateInfoKHR>(
@@ -389,7 +469,7 @@ external_image_create_info swapchain_image_create_external_memory::get_external_
assert(m_wsialloc_selected_format.format.fourcc != 0);
external_image_create_info image_info = { m_wsialloc_selected_format.format, m_create_flags, m_create_extent,
- m_use_fixed_rate_compression };
+ m_use_fixed_rate_compression, m_icd_export };
return image_info;
}
diff --git a/wsi/extensions/external_memory_extension.hpp b/wsi/extensions/external_memory_extension.hpp
index 508de48..c4aad21 100644
--- a/wsi/extensions/external_memory_extension.hpp
+++ b/wsi/extensions/external_memory_extension.hpp
@@ -52,6 +52,7 @@ struct external_image_create_info
VkImageCreateFlags2KHR flags;
VkExtent3D extent;
bool explicit_compression;
+ bool icd_export;
};
/**
@@ -68,12 +69,14 @@ public:
* @param wsialloc_selected_format Selected format for allocation by WSIAlloc.
* @param plane_layouts Plane layouts description for each plane.
* @param drm_format_props A list of all device supported VkDrmFormatModifierPropertiesEXT.
+ * @param icd_export Whether the driver allocates and exports a LINEAR image instead of importing one.
*/
swapchain_image_create_external_memory(const VkImageCreateInfo &image_create_info,
std::optional<image_create_compression_control> &compression,
wsialloc_allocate_result wsialloc_selected_format,
util::vector<VkSubresourceLayout> plane_layouts,
- const util::vector<VkDrmFormatModifierPropertiesEXT> &drm_format_props);
+ const util::vector<VkDrmFormatModifierPropertiesEXT> &drm_format_props,
+ bool icd_export = false);
/**
* @brief Create swapchain_image_create_external_memory object.
@@ -117,6 +120,7 @@ private:
util::vector<VkSubresourceLayout> m_plane_layouts;
VkImageDrmFormatModifierExplicitCreateInfoEXT m_drm_mod_info;
VkExternalMemoryImageCreateInfoKHR m_external_info;
+ bool m_icd_export;
};
} /* namespace wsi */
diff --git a/wsi/external_memory.cpp b/wsi/external_memory.cpp
index 4c454fd..8e23412 100644
--- a/wsi/external_memory.cpp
+++ b/wsi/external_memory.cpp
@@ -51,6 +51,18 @@ external_memory::~external_memory()
}
auto &device_data = layer::device_private_data::get(m_device);
+ if (m_memory_type == wsi_memory_type::ICD_EXPORTED_DMA_BUF)
+ {
+ if (m_memories[0] != VK_NULL_HANDLE)
+ {
+ device_data.disp.FreeMemory(m_device, m_memories[0], m_allocator.get_original_callbacks());
+ }
+ if (m_buffer_fds[0] >= 0)
+ {
+ close(m_buffer_fds[0]);
+ }
+ return;
+ }
for (uint32_t plane = 0; plane < get_num_planes(); plane++)
{
auto &memory = m_memories[plane];
@@ -158,6 +170,10 @@ VkResult external_memory::import_plane_memory(int fd, VkDeviceMemory *memory)
VkResult external_memory::bind_swapchain_image_memory(const VkImage &image)
{
auto &device_data = layer::device_private_data::get(m_device);
+ if (m_memory_type == wsi_memory_type::ICD_EXPORTED_DMA_BUF)
+ {
+ return device_data.disp.BindImageMemory(m_device, image, m_memories[0], 0);
+ }
if (is_disjoint())
{
util::vector<VkBindImageMemoryInfo> bind_img_mem_infos(m_allocator);
@@ -324,6 +340,57 @@ VkResult external_memory::allocate_host_visible_and_bind(const VkImage &image, c
return VK_SUCCESS;
}
+VkResult external_memory::export_memory_and_bind_swapchain_image(const VkImage &image)
+{
+ auto &device_data = layer::device_private_data::get(m_device);
+
+ VkMemoryRequirements mem_requirements;
+ device_data.disp.GetImageMemoryRequirements(m_device, image, &mem_requirements);
+
+ m_memory_type = wsi_memory_type::ICD_EXPORTED_DMA_BUF;
+ m_optimal_props = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
+ m_required_props = 0;
+ uint32_t memory_type_index = 0;
+ TRY_LOG_CALL(find_host_visible_memory_type(mem_requirements, &memory_type_index));
+
+ VkMemoryDedicatedAllocateInfo dedicated_info = {};
+ dedicated_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
+ dedicated_info.image = image;
+
+ VkExportMemoryAllocateInfo export_info = {};
+ export_info.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
+ export_info.pNext = &dedicated_info;
+ export_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
+
+ VkMemoryAllocateInfo alloc_info = {};
+ alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
+ alloc_info.pNext = &export_info;
+ alloc_info.allocationSize = mem_requirements.size;
+ alloc_info.memoryTypeIndex = memory_type_index;
+
+ TRY_LOG(device_data.disp.AllocateMemory(m_device, &alloc_info, m_allocator.get_original_callbacks(), &m_memories[0]),
+ "Failed to allocate exportable swapchain memory");
+ TRY_LOG(device_data.disp.BindImageMemory(m_device, image, m_memories[0], 0),
+ "Failed to bind exportable swapchain memory");
+
+ VkMemoryGetFdInfoKHR fd_info = {};
+ fd_info.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR;
+ fd_info.memory = m_memories[0];
+ fd_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
+ TRY_LOG(device_data.disp.GetMemoryFdKHR(m_device, &fd_info, &m_buffer_fds[0]),
+ "Failed to export swapchain memory as a dma-buf");
+
+ VkImageSubresource subresource = {};
+ subresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
+ VkSubresourceLayout layout = {};
+ device_data.disp.GetImageSubresourceLayout(m_device, image, &subresource, &layout);
+ m_offsets[0] = static_cast<uint32_t>(layout.offset);
+ m_strides[0] = static_cast<int>(layout.rowPitch);
+ m_num_planes = 1;
+ m_num_memories = 1;
+ return VK_SUCCESS;
+}
+
VkResult external_memory::allocate_and_bind_image(const VkImage &image, const VkImageCreateInfo &image_info)
{
switch (m_memory_type)
diff --git a/wsi/external_memory.hpp b/wsi/external_memory.hpp
index 9b2e836..9837d50 100644
--- a/wsi/external_memory.hpp
+++ b/wsi/external_memory.hpp
@@ -50,6 +50,7 @@ enum class wsi_memory_type
{
EXTERNAL_DMA_BUF, /* External file descriptors (dma-buf import; the default). */
HOST_VISIBLE, /* Host-accessible memory, allocated and mapped by the layer. */
+ ICD_EXPORTED_DMA_BUF, /* Driver-allocated memory exported as a dma-buf. */
};
class external_memory
@@ -192,6 +193,13 @@ public:
*/
VkResult import_memory_and_bind_swapchain_image(const VkImage &image);
+ /**
+ * @brief Allocates dedicated driver memory for a LINEAR swapchain image, binds it and exports it as a dma-buf.
+ *
+ * The plane offset and stride come from the driver's own layout of @p image.
+ */
+ VkResult export_memory_and_bind_swapchain_image(const VkImage &image);
+
/* --- RK3588 host-visible memory (X11 SHM backend) --- */
/** @brief Configure this object to allocate host-visible memory for the image. */
diff --git a/wsi/image_backing_memory_external.cpp b/wsi/image_backing_memory_external.cpp
index 636b706..836429e 100644
--- a/wsi/image_backing_memory_external.cpp
+++ b/wsi/image_backing_memory_external.cpp
@@ -37,6 +37,11 @@ namespace wsi
VkResult image_backing_memory_external::allocate()
{
+ if (m_create_info.icd_export)
+ {
+ return VK_SUCCESS;
+ }
+
allocation_params params = { (m_create_info.flags & VK_IMAGE_CREATE_PROTECTED_BIT) != 0,
m_create_info.extent,
&m_create_info.selected_format,
@@ -72,6 +77,12 @@ VkResult image_backing_memory_external::allocate()
return VK_SUCCESS;
}
+VkResult image_backing_memory_external::export_and_bind(VkImage image)
+{
+ TRY_LOG(m_external_mem.export_memory_and_bind_swapchain_image(image), "Failed to export swapchain image memory");
+ return VK_SUCCESS;
+}
+
VkResult image_backing_memory_external::import_and_bind(VkImage image)
{
TRY_LOG(m_external_mem.import_memory_and_bind_swapchain_image(image),
diff --git a/wsi/image_backing_memory_external.hpp b/wsi/image_backing_memory_external.hpp
index 1182acc..e40285d 100644
--- a/wsi/image_backing_memory_external.hpp
+++ b/wsi/image_backing_memory_external.hpp
@@ -53,6 +53,7 @@ struct wsialloc_create_info_args
VkImageCreateFlags2KHR flags;
VkExtent3D extent;
bool explicit_compression;
+ bool icd_export;
};
class image_backing_memory_external : public image_backing_memory
@@ -87,6 +88,15 @@ public:
*/
VkResult import_and_bind(VkImage image);
+ /** @brief Whether the image is allocated by the driver and exported instead of imported. */
+ bool is_icd_exported() const
+ {
+ return m_create_info.icd_export;
+ }
+
+ /** @brief Allocate driver memory for @p image, bind it and export it as a dma-buf. */
+ VkResult export_and_bind(VkImage image);
+
/**
* @brief Bind Vulkan image
*
diff --git a/wsi/wayland/swapchain.cpp b/wsi/wayland/swapchain.cpp
index 9215b52..5fe16f7 100644
--- a/wsi/wayland/swapchain.cpp
+++ b/wsi/wayland/swapchain.cpp
@@ -304,7 +304,8 @@ VkResult swapchain::init_image_factory(const VkSwapchainCreateInfoKHR &swapchain
wsialloc_create_info_args wsialloc_args = { external_image_create_info.selected_format,
external_image_create_info.flags, external_image_create_info.extent,
- external_image_create_info.explicit_compression };
+ external_image_create_info.explicit_compression,
+ external_image_create_info.icd_export };
auto backing_memory_creator =
m_allocator.make_unique<external_image_backing_memory_creator>(m_device_data, *m_wsi_allocator, wsialloc_args);
@@ -414,6 +415,10 @@ VkResult swapchain::allocate_and_bind_swapchain_image(swapchain_image &image)
auto &backing_memory = swapchain_image_factory::get_backing_memory_from_image<image_backing_memory_external>(image);
TRY_LOG_CALL(backing_memory.allocate());
+ if (backing_memory.is_icd_exported())
+ {
+ TRY_LOG_CALL(backing_memory.export_and_bind(image.get_image()));
+ }
wayland_owner<wl_buffer> buffer = nullptr;
buffer = create_wl_buffer(backing_memory);
@@ -423,7 +428,10 @@ VkResult swapchain::allocate_and_bind_swapchain_image(swapchain_image &image)
return VK_ERROR_INITIALIZATION_FAILED;
}
- TRY_LOG_CALL(backing_memory.import_and_bind(image.get_image()));
+ if (!backing_memory.is_icd_exported())
+ {
+ TRY_LOG_CALL(backing_memory.import_and_bind(image.get_image()));
+ }
auto image_data = m_allocator.make_unique<wayland_image_data>(std::move(buffer));
if (image_data == nullptr)
diff --git a/wsi/wsi_factory.cpp b/wsi/wsi_factory.cpp
index 87795dc..53666be 100644
--- a/wsi/wsi_factory.cpp
+++ b/wsi/wsi_factory.cpp
@@ -216,6 +216,12 @@ VkResult add_device_extensions_required_by_layer(VkPhysicalDevice phys_dev,
TRY_LOG(props->get_required_device_extensions(extensions_required_by_layer, api_version),
"Failed to acquire required device extensions");
+ /* Without DRM format modifiers, Wayland swapchains export driver-allocated LINEAR images instead. */
+ if (!available_device_extensions.contains(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME))
+ {
+ extensions_required_by_layer.remove(VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME);
+ }
+
bool supported = available_device_extensions.contains(extensions_required_by_layer);
if (!supported)
{
diff --git a/wsi/x11/swapchain.cpp b/wsi/x11/swapchain.cpp
index a857035..fbe13c9 100644
--- a/wsi/x11/swapchain.cpp
+++ b/wsi/x11/swapchain.cpp
@@ -442,11 +442,16 @@ VkResult swapchain::init_image_factory(const VkSwapchainCreateInfoKHR &swapchain
std::get<util::unique_ptr<swapchain_image_create_external_memory>>(std::move(sc_img_create_ext_mem_result));
auto external_image_create_info = sc_img_create_ext_mem->get_external_image_create_info();
+ if (external_image_create_info.icd_export)
+ {
+ WSI_LOG_ERROR("DRI3 presentation needs importable DRM format modifiers");
+ return VK_ERROR_INITIALIZATION_FAILED;
+ }
TRY_LOG_CALL(image_handle_creator->add_extension(std::move(sc_img_create_ext_mem)));
wsialloc_create_info_args wsialloc_args = { external_image_create_info.selected_format,
external_image_create_info.flags, external_image_create_info.extent,
- external_image_create_info.explicit_compression };
+ external_image_create_info.explicit_compression, false };
auto backing_memory_creator =
m_allocator.make_unique<external_image_backing_memory_creator>(m_device_data, *m_wsi_allocator, wsialloc_args);
if (backing_memory_creator == nullptr)
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more