From b4210b5a67ebb3352526de2604d4d2187d079d7e Mon Sep 17 00:00:00 2001 From: The412Banner Date: Sun, 29 Nov 2026 22:34:00 -0500 Subject: [PATCH] upscale: build the upscaler layer as VK_LAYER_DROIDDECK_upscale Port of the NeuralScale layer (previous commit) for DroidDeck: - Layer VK_LAYER_DROIDDECK_upscale, library libVkLayer_droiddeck_upscale.so, implicit manifest template (DROIDDECK_UPSCALE=1 / DROIDDECK_UPSCALE_DISABLE=1). - Settings read as DROIDDECK_UPSCALE_, then WINLATOR_FSR4_. - No hardcoded com.winlator.cmod data dir; without a dir frames get the blit fallback. - Compiled NPU graph caches go to // (v79/v81 from HTP_ARCH, the SoC properties or the mapped QNN stub) instead of /v81/. - The arch stub is loaded from the QNN library search list first, so NATIVELIB_DIR is enough without LD_LIBRARY_PATH. - driverID/driverName are only rewritten with GPU_SPOOF word "1"; SPOOF_DLSS=1 alone reports RTX vendor/device IDs. - APK build via app/src/main/cpp/CMakeLists.txt; glibc build for the PRoot guest (build-glibc.sh, DD_UPSCALE_NO_ANDROID: QNN stubs, stderr log) in the runtime recipe, installed to usr/local/lib/droiddeck-upscale-layer/. - -Bsymbolic so the exported vkGetInstanceProcAddr is not interposed by a libvulkan in the global scope. - Pack scripts take their paths as arguments. Seam protocol, buffer sizes, magic values and backend IDs are unchanged. --- app/src/main/cpp/CMakeLists.txt | 1 + tools/components/recipes.json | 5 +- tools/components/recipes/runtime.sh | 2 + tools/upscale/layer/CMakeLists.txt | 32 +++ tools/upscale/layer/README.md | 206 ++++++++++++++ .../layer/VK_LAYER_DROIDDECK_upscale.json | 17 ++ tools/upscale/layer/build-glibc.sh | 52 ++++ tools/upscale/layer/dd_upscale_compat.h | 56 ++++ tools/upscale/layer/fsr3_gpu.c | 10 +- tools/upscale/layer/fsr411_full_gpu.c | 10 +- tools/upscale/layer/fsr412_lite.c | 12 +- tools/upscale/layer/fsr4_builtin.c | 12 +- tools/upscale/layer/fsr4_layer.c | 118 ++++---- tools/upscale/layer/fsr4_pipeline.c | 69 ++--- tools/upscale/layer/fsr4_qnn.c | 252 ++++++++++++++++-- tools/upscale/layer/fsr4_qnn.h | 9 +- .../layer/scripts/pack_fsr412_lite_weights.py | 11 +- .../layer/scripts/pack_fsr4_weights.py | 10 +- 18 files changed, 749 insertions(+), 135 deletions(-) create mode 100644 tools/upscale/layer/CMakeLists.txt create mode 100644 tools/upscale/layer/README.md create mode 100644 tools/upscale/layer/VK_LAYER_DROIDDECK_upscale.json create mode 100755 tools/upscale/layer/build-glibc.sh create mode 100644 tools/upscale/layer/dd_upscale_compat.h diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index a33cf37e49..d81f46c880 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -30,6 +30,7 @@ message(STATUS "dd-fg chain: win-fg ${DDFG_UPSTREAM} (src ${DDFG_CHAIN_HASH})") add_subdirectory(waylandcomp) add_subdirectory(questxr) +add_subdirectory(../../../../tools/upscale/layer upscale_layer) add_library(sdnative SHARED sdnative/sdnative.c) target_link_libraries(sdnative log) diff --git a/tools/components/recipes.json b/tools/components/recipes.json index 5cccf80ffa..0461668c26 100644 --- a/tools/components/recipes.json +++ b/tools/components/recipes.json @@ -16,6 +16,7 @@ "tools/pipewire", "tools/vr", "tools/gpuload", + "tools/upscale/layer", "app/src/main/cpp/waylandcomp/generated", "app/src/main/cpp/waylandcomp/src/headpose_shm.h", "app/src/main/cpp/waylandcomp/src/spatialpose_shm.h", @@ -24,7 +25,9 @@ "outputs": [ "app/src/main/assets/linuxfs/usr/local/bin/gamescope", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so", - "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" + "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so", + "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so", + "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json" ], "ndk": true, "packages": [ diff --git a/tools/components/recipes/runtime.sh b/tools/components/recipes/runtime.sh index 9de7efba18..f395d5c862 100644 --- a/tools/components/recipes/runtime.sh +++ b/tools/components/recipes/runtime.sh @@ -6,6 +6,8 @@ VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr" VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \ tools/gpuload/build.sh --native "$D/usr/local/lib/droiddeck-gpuload" +VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \ + tools/upscale/layer/build-glibc.sh "$D/usr/local/lib/droiddeck-upscale-layer" for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")" done diff --git a/tools/upscale/layer/CMakeLists.txt b/tools/upscale/layer/CMakeLists.txt new file mode 100644 index 0000000000..ed66706764 --- /dev/null +++ b/tools/upscale/layer/CMakeLists.txt @@ -0,0 +1,32 @@ +cmake_minimum_required(VERSION 3.22.1) + +# VK_LAYER_DROIDDECK_upscale for the APK (bionic, arm64-v8a). Added from app/src/main/cpp/CMakeLists.txt. +# The glibc build for the PRoot guest is build-glibc.sh. +add_library(VkLayer_droiddeck_upscale SHARED + fsr4_layer.c + fsr4_pipeline.c + fsr4_builtin.c + fsr412_lite.c + fsr411_full_gpu.c + fsr3_gpu.c + fsr4_qnn.c +) + +target_include_directories(VkLayer_droiddeck_upscale PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + +target_compile_definitions(VkLayer_droiddeck_upscale PRIVATE VK_USE_PLATFORM_ANDROID_KHR=1) + +target_compile_options(VkLayer_droiddeck_upscale PRIVATE + -O2 + -Wall + -Wextra + -Wno-unused-function + -Wno-missing-field-initializers + -fvisibility=hidden +) + +# -Bsymbolic keeps the exported vkGetInstanceProcAddr/vkGetDeviceProcAddr bound to this library even when +# a libvulkan in the global scope exports the same names. +target_link_options(VkLayer_droiddeck_upscale PRIVATE -Wl,-z,max-page-size=16384 -Wl,-Bsymbolic) + +target_link_libraries(VkLayer_droiddeck_upscale android log dl m) diff --git a/tools/upscale/layer/README.md b/tools/upscale/layer/README.md new file mode 100644 index 0000000000..5d97850046 --- /dev/null +++ b/tools/upscale/layer/README.md @@ -0,0 +1,206 @@ +# VK_LAYER_DROIDDECK_upscale + +A Vulkan layer that runs the upscaler calls of Windows games (FSR 4 / FSR 3 / FSR 2 through +FidelityFX, DLSS through NGX, XeSS) on the device: on the Adreno GPU, or on the Snapdragon +Hexagon NPU through Qualcomm QNN. The Windows side is a set of bridge DLLs +(`amd_fidelityfx_*.dll`, `nvngx.dll`, `libxess.dll`, ...). They talk to this layer through two +Vulkan buffers with magic sizes and a `vkCmdUpdateBuffer` doorbell (`fsr4_seam_proto.h`). That +protocol, its buffer sizes, magic values and backend IDs are unchanged from upstream, so the +upstream bridge DLLs work against this layer. + +Layer name `VK_LAYER_DROIDDECK_upscale`, library `libVkLayer_droiddeck_upscale.so`, implicit layer. +The manifest template `VK_LAYER_DROIDDECK_upscale.json` turns it on with `DROIDDECK_UPSCALE=1` and +off with `DROIDDECK_UPSCALE_DISABLE=1`. + +## Origin, credits, licence + +GPL-3.0, like DroidDeck. Ported from `app/src/main/cpp/fsr4npu/` of +[michaelisomer-cyber/Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale) +at commit `a0ab6b0f770e1a6786b4e68def46b4edb8baafd0` (GPL-3.0). That project is a fork of +[StevenMXZ/Winlator-Ludashi](https://github.com/StevenMXZ/Winlator-Ludashi). The first commit +that adds this folder holds the upstream files unchanged; the DroidDeck changes are in the +commits after it. + +Work this code builds on, as credited upstream: + +- AMD FidelityFX SDK (FSR 3.1, FSR 4.0.2, FSR 4.1.x): [GPUOpen FidelityFX-SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK) +- Intel XeSS 3.0 SDK: [intel/xess](https://github.com/intel/xess) +- FSR 4 Vulkan DP4a reference pipelines: [dvj5411/fsr4vk](https://github.com/dvj5411/fsr4vk), [zrprod9-cmyk/vela](https://github.com/zrprod9-cmyk/vela), [puzzled-pancake/fsr4-hexagon](https://github.com/puzzled-pancake/fsr4-hexagon) +- RDR2 DLSS-gate byte patterns: OptiPatcher from [optiscaler/OptiScaler](https://github.com/optiscaler/OptiScaler) +- QNN HTP runtime handling adapted from BananaNative's SM8850 runtime (per the upstream source comments) +- Qualcomm QNN / QAIRT HTP runtime (Qualcomm AI Engine Direct SDK); `fsr4_qnn.h` is a clean-room + declaration of the C ABI subset, no Qualcomm headers are used + +## Files + +| File | What | +| --- | --- | +| `fsr4_layer.c` | Loader interface, device/extension/feature injection, GPU/DLSS spoof, seam mailbox + doorbell, ctrl and status files | +| `fsr4_pipeline.c/.h` | Backend dispatch and fallbacks, FSR 4.1.1 Full NPU (external pack) path | +| `fsr4_builtin.c/.h` | FSR 4.0.2 INT8 on the NPU (graph compiled on the device from `fsr4_v07_i8.wpack`) | +| `fsr412_lite.c/.h` | FSR 4.1.2 Lite INT8, GPU DP4a or NPU | +| `fsr411_full_gpu.c/.h` | FSR 4.1.1 Full INT8 on the GPU | +| `fsr3_gpu.c/.h` | FSR 3.1 on the GPU, also the fallback for every other backend | +| `fsr4_qnn.c/.h` | QNN/FastRPC/AHardwareBuffer runtime; stubs only in glibc builds | +| `fsr4_seam_proto.h` | Shared protocol with the Windows bridge DLLs (do not change) | +| `fsr_gpu_timer.h` | GPU timestamp helper for the status file | +| `dd_upscale_compat.h` | DroidDeck env lookup and logging (logcat, or stderr in glibc builds) | +| `shaders/*.comp` | GLSL source of `fsr3_*.spv`, `fsr4_builtin_*.spv`, `fsr412_lite/lite_npu_{pack,unpack}.spv` | +| `scripts/pack_*.py` | Build `fsr4_v07_i8.wpack` and `fsr412_lite/fsr412_lite_i8.wpack` from the AMD weights | +| `CMakeLists.txt` | APK build (bionic), added from `app/src/main/cpp/CMakeLists.txt` | +| `build-glibc.sh` | PRoot guest build (glibc), called by `tools/components/recipes/runtime.sh` | + +## Builds + +- APK (bionic, arm64-v8a, minSdk 26): Gradle's NDK build makes `libVkLayer_droiddeck_upscale.so` + through `add_subdirectory(../../../../tools/upscale/layer upscale_layer)`. Links `android log dl m`, + `-Wl,-z,max-page-size=16384 -Wl,-Bsymbolic`. The manifest's relative `library_path` is meant to be + rewritten to the absolute path by the app. +- PRoot guest (glibc): `tools/upscale/layer/build-glibc.sh OUT` (`CC`, default `aarch64-linux-gnu-gcc`; + Vulkan headers from `VK_INCLUDE` or the NDK). Built with `-DDD_UPSCALE_NO_ANDROID`: no + AHardwareBuffer, FastRPC, QNN or liblog (logs go to stderr). Every NPU init fails with + `npu_unavailable` and the backends take their GPU fallbacks. `OUT` gets the library and a manifest + with `library_path` `/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so` + (override with `DD_UPSCALE_GUEST_LIB`). The runtime recipe installs both into + `app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/`. +- `-Bsymbolic` is needed in both builds: the layer exports `vkGetInstanceProcAddr`, and a + `libvulkan` already in the global symbol scope would otherwise win the lookup (the loader then + fails with `Failed to find 'vkCreateInstance'`). + +## Environment + +Each key is read as `DROIDDECK_UPSCALE_` first, then `WINLATOR_FSR4_` +(`dd_upscale_compat.h`). Empty values count as unset. + +| Key | Read at | Meaning | +| --- | --- | --- | +| `DIR` (then `DM_FSR4_DIR`) | `fsr4_pipeline.c:566`, `:826` | Data dir (layout below). Unset: no backend can load its files, frames get a plain blit. No built-in fallback path | +| `POWER` | `fsr4_pipeline.c:575`, `:830` | HTP power vote: `burst`, `turbo` (default), `balanced`/`nom`, `low` | +| `BACKEND`, then `ENGINE` | `fsr4_layer.c:458` | Start backend (names under ctrl file). Unset: `fsr4_0_npu` | +| `NPU_SYNC` | `fsr4_layer.c:462` | `1` = GPU waits for the NPU each frame. Anything else = async (default). `sync`/`true` also mean sync | +| `SHARPNESS` | `fsr4_layer.c:464` | RCAS 0.0-1.0, default 0.55 | +| `PRESET` | `fsr4_pipeline.c:1239` | `ultraperf` or `performance` forces the preset; else from the game's quality mode / ratio | +| `CTRL_FILE` | `fsr4_layer.c:472` | Live control file, format below | +| `STATUS_FILE` | `fsr4_layer.c:526` | Live status file, format below | +| `NATIVELIB_DIR` | `fsr4_qnn.c:311` | Folder with the Qualcomm host libraries (see NPU setup) | +| `HTP_ARCH` | `fsr4_qnn.c:237` | Optional override of the HTP arch (`v79`, `v81`) used for the cache folder | +| `SPOOF_DLSS` | `fsr4_layer.c:557`, `:583` | `1` = expose `VK_NVX_binary_import` / `VK_NVX_image_view_handle` (stub functions) and report an RTX 2060 vendorID/deviceID/name | +| `GPU_SPOOF` | `fsr4_layer.c:570` | Words split by `,` `+` `;` or blanks: `rtx` / `rdna4` pick the reported GPU; `1` also rewrites driverID/driverName/driverInfo; `off`/`none`/`0` keep the real GPU even with `SPOOF_DLSS=1` | +| `VRAM_OVERRIDE` | `fsr4_layer.c:757` | `1` = report `VRAM_MB` as the size of every device-local heap (and its budget). Off otherwise | +| `VRAM_MB` (then `WRAPPER_VMEM_MAX_SIZE`) | `fsr4_layer.c:759` | Heap size in MB for `VRAM_OVERRIDE=1`, 512-65536 | +| `RDR2_PATCH` | `fsr4_layer.c:235` | `1` = patch RDR2.exe's DLSS vendor checks in memory. Off otherwise (Arxan crashes after loading with it) | +| `LOG` | `fsr4_qnn.c:145`, `fsr4_pipeline.c:443` | `2` = verbose QNN log and every NPU dispatch logged | +| `JX`, `JY`, `MX`, `MY` | `fsr4_pipeline.c:1387`-`1390` | Debug: jitter and motion-vector scale multipliers for the external FSR 4.1.1 NPU pack, default 1 | + +Not prefixed: `ADSP_LIBRARY_PATH` (read and, if `/adsp` is missing from it, prepended by the +layer, `fsr4_qnn.c:262`), `LD_LIBRARY_PATH` (searched for QNN libraries, `fsr4_qnn.c:303`). +Upstream's `WINLATOR_FSR4_DISABLE_LAYER` only lived in its manifest; the C code never read it. +Here the loader switch is `DROIDDECK_UPSCALE_DISABLE=1`. + +Spoof examples: `SPOOF_DLSS=1` gives RTX 2060 IDs with the real driverID; add `GPU_SPOOF=1` for +`VK_DRIVER_ID_NVIDIA_PROPRIETARY` too. `GPU_SPOOF=rdna4` gives Radeon RX 9070 XT IDs, +`GPU_SPOOF=rdna4,1` adds the AMD driverID. Upstream rewrote the driverID whenever `GPU_SPOOF` was +`rtx` or `rdna4`; here that needs the `1` word. + +## Ctrl file (read) + +`read_live_ctrl`, `fsr4_layer.c:454`-`505`. Re-read at most every 200 ms, when a doorbell arrives +and at `vkCreateDevice`. One `key=value` per line; keys missing from the file keep their last value +(first the env values): + +``` +enabled=1 # 0, off..., false... = bypass (plain blit); anything else = on +backend=fsr4_1_lite_gpu +engine=fsr4_1_lite_gpu # same as backend=, upstream writes both +npu_sync=async # 1, sync..., true... = sync; anything else = async +sharpness=0.55 # clamped to 0..1 +``` + +Backend names, matched by prefix (`parse_backend_str`, `fsr4_layer.c:421`): `fsr3`/`gpu` = FSR 3.1 +GPU (0), `xess`/`xess3` = XeSS 3 DP4a (1), `fsr4_0_npu`/`fsr4_npu`/`fsr4`/`npu` = FSR 4.0.2 NPU (2), +`fsr4_1_lite_npu`/`412_lite_npu` (3), `fsr4_1_full_npu`/`412_full_npu` (4), +`fsr4_1_lite_gpu`/`412_lite_gpu` (5), `fsr4_1_full_gpu`/`412_full_gpu` (6); anything else = 5. +If the first line has none of these keys, it is a bare flag: containing `0`, `off` or `false` turns +the upscaler off, anything else on. + +## Status file (written) + +`write_live_status`, `fsr4_layer.c:507`-`553`. Written to `.tmp`, then renamed over +`STATUS_FILE`. At most every 250 ms unless enabled/backend/sync/NPU use/quality/render width +changed; always at `vkCreateDevice`. Exactly these lines in this order: + +``` +layer=1 +driver= +ahb= +npu_state= +rdr2_patch= +engine= +backend= +backend_tag= +npu_sync= +sharpness=<%.2f> +enabled=<0|1> +active=<0|1> +npu=<0|1> +api= +quality= +render=x +output=x +preset= +gpu_us= +htp_us= +dispatches= +reason= +ts_ms= +``` + +## Data dir (`DROIDDECK_UPSCALE_DIR`) + +Same tree as upstream's `app/src/main/assets/fsr4/`. None of it is in this repo; it is installed at +run time. Paths the layer opens, relative to the dir: + +| Path | Used by | Built here? | +| --- | --- | --- | +| `fsr3_prepare.spv`, `fsr3_accumulate.spv`, `fsr3_rcas.spv` | FSR 3.1 GPU (`fsr3_gpu.c:343`, `:385`) | Source in `shaders/`. Upstream's files look like `glslc -O --target-env=vulkan1.1` output (Shaderc, SPIR-V 1.3); a local build of that is close in size, not byte-identical. Not built by the layer builds | +| `fsr4_builtin_pre.spv`, `fsr4_builtin_post_a.spv`, `fsr4_builtin_post_b.spv` | FSR 4.0.2 NPU (`fsr4_builtin.c:560`, `:609`) | Source in `shaders/` | +| `fsr4_v07_i8.wpack` | FSR 4.0.2 NPU graph (`fsr4_qnn.c:1583`) | `scripts/pack_fsr4_weights.py`, needs fsr4-hexagon and AMD weights | +| `fsr412_lite/0000.spv` ... `0010.spv`, `0013.spv`, `weights.bin` | FSR 4.1.2 Lite (`fsr412_lite.c:410`, `:688`) | No: precompiled AMD FidelityFX SDK passes (per upstream) | +| `fsr412_lite/lite_npu_pack.spv`, `lite_npu_unpack.spv` | Lite NPU (`fsr412_lite.c:618`) | Source in `shaders/` | +| `fsr412_lite/fsr412_lite_i8.wpack` | Lite NPU graph (`fsr412_lite.c:456`) | `scripts/pack_fsr412_lite_weights.py`, needs vela + `weights.bin` | +| `fsr411_full/{quality,performance}/pass-00.spv` ... `pass-27.spv`, `initializers.bin` | FSR 4.1.1 Full GPU (`fsr411_full_gpu.c:328`, `:346`) | No: precompiled AMD FidelityFX SDK passes (per upstream) | +| `adsp/libQnnHtpV79Skel.so`, `adsp/libQnnHtpV81Skel.so` | NPU side, loaded by FastRPC through `ADSP_LIBRARY_PATH`; also probed for the arch (`fsr4_qnn.c:224`) | No: Qualcomm QNN | +| `/fsr4_v07_i8_cache.bin`, `/fsr412_lite_i8_cache.bin` | Compiled NPU graphs, written by the layer on first use | Made on the device | +| `1080/{performance,ultraperf}/pass-00.spv`, `pass-01-npu.spv`, `pass-28.spv`, `initializers.bin`, `v81/nf4_k1h.bin`, `v81/nf4up_k1h.bin` | Optional external FSR 4.1.1 Full NPU pack (`fsr4_pipeline.c:460`-`478`, `fsr4_qnn.c:1018`); v81 only | No | +| `jni/arm64-v8a/`, `` | First two places searched for QNN host libraries | No | + +`` is `v79` or `v81`: `HTP_ARCH` if set, else the SoC (`ro.soc.model` / +`ro.vendor.qti.soc_model` starting with `SM8750` = v79, `SM8850` = v81, or `ro.vendor.qti.soc_name` / +`ro.board.platform` `sun` = v79, `canoe` = v81), else the `libQnnHtpVStub.so` mapped in the +process, else the only skel present in `adsp/`, else `htp` (`fsr4_qnn.c:176`-`250`). Upstream always +used `v81/`. + +## NPU setup (Android build only) + +- Host libraries: `libQnnSystem.so`, `libQnnHtp.so`, `libQnnHtpV79Stub.so`, `libQnnHtpV81Stub.so`, + `libQnnHtpPrepare.so` (on-device graph compile). Searched in this order (`fsr4_qnn.c:303`): + `/jni/arm64-v8a/`, `/`, `/`, each `LD_LIBRARY_PATH` entry, then the bare + name (Android `sphal` namespace first, then the default one). +- `libQnnHtp.so` opens the arch stub by name itself. The layer loads `libQnnHtpVStub.so` + (both stubs when the arch is unknown) from the same search list first (`fsr4_qnn.c:364`), so + `NATIVELIB_DIR` alone is enough; `LD_LIBRARY_PATH` does not have to name the folder. +- `ADSP_LIBRARY_PATH` must list `/adsp` (the skels), `;`-separated, e.g. + `/adsp;/vendor/dsp/cdsp;/vendor/lib/rfsa/adsp;/system/lib/rfsa/adsp`. The layer prepends + `/adsp` itself when it is missing. +- `libcdsprpc.so` comes from the vendor partition. + +## DroidDeck changes from upstream + +- Layer name, library name, log tags, manifest (implicit, `DROIDDECK_UPSCALE` / `DROIDDECK_UPSCALE_DISABLE`). +- `DROIDDECK_UPSCALE_` env with `WINLATOR_FSR4_` fallback. +- No hardcoded `/data/user/0/com.winlator.cmod/files/fsr4` fallback; no data dir means GPU blit. +- Compiled NPU graph caches in `//` instead of `/v81/`. +- driverID/driverName/driverInfo rewrite only with `GPU_SPOOF` word `1`; `SPOOF_DLSS=1` alone reports RTX vendor/device IDs. +- Arch stub preloaded from the library search list (`NATIVELIB_DIR` works without `LD_LIBRARY_PATH`). +- glibc build (`DD_UPSCALE_NO_ANDROID`) with QNN stubs and stderr logging. +- `-Bsymbolic` link flag; pack scripts take their paths as arguments instead of the author's Windows paths. diff --git a/tools/upscale/layer/VK_LAYER_DROIDDECK_upscale.json b/tools/upscale/layer/VK_LAYER_DROIDDECK_upscale.json new file mode 100644 index 0000000000..8c101c1f95 --- /dev/null +++ b/tools/upscale/layer/VK_LAYER_DROIDDECK_upscale.json @@ -0,0 +1,17 @@ +{ + "file_format_version": "1.2.0", + "layer": { + "name": "VK_LAYER_DROIDDECK_upscale", + "type": "GLOBAL", + "library_path": "libVkLayer_droiddeck_upscale.so", + "api_version": "1.3.275", + "implementation_version": "1", + "description": "In-game upscaler: FSR 4 / FSR 3.1 / XeSS / DLSS calls from the Windows bridge DLLs run on the GPU or the Hexagon NPU", + "enable_environment": { + "DROIDDECK_UPSCALE": "1" + }, + "disable_environment": { + "DROIDDECK_UPSCALE_DISABLE": "1" + } + } +} diff --git a/tools/upscale/layer/build-glibc.sh b/tools/upscale/layer/build-glibc.sh new file mode 100755 index 0000000000..a7d78d7503 --- /dev/null +++ b/tools/upscale/layer/build-glibc.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Builds VK_LAYER_DROIDDECK_upscale for the arm64 glibc guest (PRoot mode): tools/upscale/layer/build-glibc.sh OUT +# DD_UPSCALE_NO_ANDROID leaves out AHardwareBuffer, FastRPC, QNN and liblog, so NPU backends use their GPU fallbacks. +# OUT gets libVkLayer_droiddeck_upscale.so and VK_LAYER_DROIDDECK_upscale.json (absolute guest library_path). +# -Bsymbolic: the layer exports vkGetInstanceProcAddr; without it a libvulkan already in the global scope +# wins the lookup and the loader gets its own trampoline back ("Failed to find 'vkCreateInstance'"). +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../../.." && pwd) + +out=${1:?usage: tools/upscale/layer/build-glibc.sh OUT} +case "$out" in /*) ;; *) out="$PWD/$out" ;; esac +guest_lib=${DD_UPSCALE_GUEST_LIB:-/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so} +cc=${CC:-aarch64-linux-gnu-gcc} +strip=${STRIP:-aarch64-linux-gnu-strip} + +vkinc=${VK_INCLUDE:-} +if [ -z "$vkinc" ]; then + ndks=("${NDK:-}" "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}") + sdk_ndks=("${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/*) + for ((i = ${#sdk_ndks[@]} - 1; i >= 0; i--)); do ndks+=("${sdk_ndks[i]}"); done + for ndk in "${ndks[@]}"; do + [ -n "$ndk" ] && [ -d "$ndk" ] || continue + for cand in "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include; do + if [ -f "$cand/vulkan/vulkan_android.h" ]; then vkinc=$cand; break 2; fi + done + done +fi +[ -n "$vkinc" ] && [ -f "$vkinc/vulkan/vulkan_core.h" ] && [ -f "$vkinc/vulkan/vulkan_android.h" ] || { + echo "tools/upscale/layer/build-glibc.sh: no Vulkan headers (set VK_INCLUDE)" >&2; exit 1; } +command -v "$cc" >/dev/null || { echo "tools/upscale/layer/build-glibc.sh: $cc not found (set CC)" >&2; exit 1; } + +work="$repo/build/upscale-layer" +rm -rf "$work" && mkdir -p "$work/include" "$work/out" +# Only the Vulkan headers: the NDK sysroot's libc headers must not shadow glibc's. +cp -R "$vkinc/vulkan" "$work/include/" +if [ -d "$vkinc/vk_video" ]; then cp -R "$vkinc/vk_video" "$work/include/"; fi + +"$cc" -std=gnu11 -shared -fPIC -O2 -Wall -Wextra -Wno-unused-function -Wno-missing-field-initializers \ + -fvisibility=hidden -pthread -Wl,-z,defs -Wl,-Bsymbolic -DDD_UPSCALE_NO_ANDROID -I"$work/include" -I"$here" \ + -o "$work/out/libVkLayer_droiddeck_upscale.so" \ + "$here/fsr4_layer.c" "$here/fsr4_pipeline.c" "$here/fsr4_builtin.c" "$here/fsr412_lite.c" \ + "$here/fsr411_full_gpu.c" "$here/fsr3_gpu.c" "$here/fsr4_qnn.c" -lm -ldl +"$strip" --strip-unneeded "$work/out/libVkLayer_droiddeck_upscale.so" + +sed "s|\"library_path\": \"[^\"]*\"|\"library_path\": \"$guest_lib\"|" \ + "$here/VK_LAYER_DROIDDECK_upscale.json" > "$work/out/VK_LAYER_DROIDDECK_upscale.json" +grep -q "\"library_path\": \"$guest_lib\"" "$work/out/VK_LAYER_DROIDDECK_upscale.json" + +mkdir -p "$out" +cp "$work/out/libVkLayer_droiddeck_upscale.so" "$work/out/VK_LAYER_DROIDDECK_upscale.json" "$out/" +echo "built $out" diff --git a/tools/upscale/layer/dd_upscale_compat.h b/tools/upscale/layer/dd_upscale_compat.h new file mode 100644 index 0000000000..939c3fc164 --- /dev/null +++ b/tools/upscale/layer/dd_upscale_compat.h @@ -0,0 +1,56 @@ +// DroidDeck glue for the upscaler layer: environment lookup and logging. +// +// Every setting is read as DROIDDECK_UPSCALE_ first and WINLATOR_FSR4_ second, so +// launchers written for the upstream layer keep working. Empty values count as unset. +// +// Android builds log to logcat. DD_UPSCALE_NO_ANDROID builds (glibc, PRoot guest) log to stderr. +#pragma once + +#include +#include + +static inline const char *dd_upscale_env(const char *key) { + char name[96]; + snprintf(name, sizeof name, "DROIDDECK_UPSCALE_%s", key); + const char *v = getenv(name); + if (v && *v) return v; + snprintf(name, sizeof name, "WINLATOR_FSR4_%s", key); + v = getenv(name); + return (v && *v) ? v : NULL; +} + +// Data dir with the SPIR-V passes, weights and QNN files. NULL when no launcher set one. +static inline const char *dd_upscale_dir(void) { + const char *dir = dd_upscale_env("DIR"); + if (!dir) { + dir = getenv("DM_FSR4_DIR"); + if (dir && !*dir) dir = NULL; + } + return dir; +} + +#ifdef DD_UPSCALE_NO_ANDROID +#include + +#define DD_LOG_INFO 4 +#define DD_LOG_WARN 5 +#define DD_LOG_ERROR 6 + +__attribute__((format(printf, 3, 4))) +static inline int dd_upscale_log(int prio, const char *tag, const char *fmt, ...) { + char msg[1024]; + va_list ap; + va_start(ap, fmt); + vsnprintf(msg, sizeof msg, fmt, ap); + va_end(ap); + const char lvl = prio >= DD_LOG_ERROR ? 'E' : (prio == DD_LOG_WARN ? 'W' : 'I'); + return fprintf(stderr, "%c/%s: %s\n", lvl, tag, msg); +} +#else +#include + +#define DD_LOG_INFO ANDROID_LOG_INFO +#define DD_LOG_WARN ANDROID_LOG_WARN +#define DD_LOG_ERROR ANDROID_LOG_ERROR +#define dd_upscale_log __android_log_print +#endif diff --git a/tools/upscale/layer/fsr3_gpu.c b/tools/upscale/layer/fsr3_gpu.c index 91572c389e..83908e0e35 100644 --- a/tools/upscale/layer/fsr3_gpu.c +++ b/tools/upscale/layer/fsr3_gpu.c @@ -7,17 +7,17 @@ #include "fsr3_gpu.h" #include "fsr_gpu_timer.h" -#include +#include "dd_upscale_compat.h" #include #include #include #include #include -#define F3_TAG "WinlatorFSR3GPU" -#define F3_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F3_TAG, __VA_ARGS__) -#define F3_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F3_TAG, __VA_ARGS__) -#define F3_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, F3_TAG, __VA_ARGS__) +#define F3_TAG "DroidDeckUpscaleFSR3" +#define F3_LOGI(...) dd_upscale_log(DD_LOG_INFO, F3_TAG, __VA_ARGS__) +#define F3_LOGW(...) dd_upscale_log(DD_LOG_WARN, F3_TAG, __VA_ARGS__) +#define F3_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F3_TAG, __VA_ARGS__) typedef struct { VkImage img; diff --git a/tools/upscale/layer/fsr411_full_gpu.c b/tools/upscale/layer/fsr411_full_gpu.c index 770de4e361..cca924258a 100644 --- a/tools/upscale/layer/fsr411_full_gpu.c +++ b/tools/upscale/layer/fsr411_full_gpu.c @@ -4,16 +4,16 @@ #include "fsr411_full_gpu.h" #include "fsr_gpu_timer.h" -#include +#include "dd_upscale_compat.h" #include #include #include #include -#define F411_TAG "WinlatorFSR411FullGPU" -#define F411_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F411_TAG, __VA_ARGS__) -#define F411_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F411_TAG, __VA_ARGS__) -#define F411_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, F411_TAG, __VA_ARGS__) +#define F411_TAG "DroidDeckUpscaleFSR411" +#define F411_LOGI(...) dd_upscale_log(DD_LOG_INFO, F411_TAG, __VA_ARGS__) +#define F411_LOGW(...) dd_upscale_log(DD_LOG_WARN, F411_TAG, __VA_ARGS__) +#define F411_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F411_TAG, __VA_ARGS__) enum { F411_UW = 1920u, diff --git a/tools/upscale/layer/fsr412_lite.c b/tools/upscale/layer/fsr412_lite.c index 1789fbb5d5..fb0f14f870 100644 --- a/tools/upscale/layer/fsr412_lite.c +++ b/tools/upscale/layer/fsr412_lite.c @@ -8,7 +8,7 @@ #include "fsr4_qnn.h" #include "fsr_gpu_timer.h" -#include +#include "dd_upscale_compat.h" #include #include #include @@ -18,10 +18,10 @@ #include #include -#define L4_TAG "WinlatorFSR412Lite" -#define L4_LOGI(...) __android_log_print(ANDROID_LOG_INFO, L4_TAG, __VA_ARGS__) -#define L4_LOGW(...) __android_log_print(ANDROID_LOG_WARN, L4_TAG, __VA_ARGS__) -#define L4_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, L4_TAG, __VA_ARGS__) +#define L4_TAG "DroidDeckUpscaleFSR412" +#define L4_LOGI(...) dd_upscale_log(DD_LOG_INFO, L4_TAG, __VA_ARGS__) +#define L4_LOGW(...) dd_upscale_log(DD_LOG_WARN, L4_TAG, __VA_ARGS__) +#define L4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, L4_TAG, __VA_ARGS__) enum { L4_OUT_W = 1920u, @@ -454,7 +454,7 @@ static VkPipeline l4_load_pipe(const WlVkDispatch *vk, const char *dir, const ch static void *l4_npu_init_worker(void *arg) { WlFsr412Lite *c = (WlFsr412Lite *)arg; wl_fsr4_qnn *q = wl_fsr4_qnn_init_wpack(c->dir, "fsr412_lite/fsr412_lite_i8.wpack", - "v81/fsr412_lite_i8_cache.bin", "fsr412_lite_i8", + "fsr412_lite_i8_cache.bin", "fsr412_lite_i8", c->power_mode, WL_FSR4_LITE_IN_BYTES, WL_FSR4_LITE_OUT_BYTES); if (!q) { snprintf(c->npu_fail_reason, sizeof c->npu_fail_reason, "%s", wl_fsr4_qnn_last_error()); diff --git a/tools/upscale/layer/fsr4_builtin.c b/tools/upscale/layer/fsr4_builtin.c index d47dcdda7b..836b30ed58 100644 --- a/tools/upscale/layer/fsr4_builtin.c +++ b/tools/upscale/layer/fsr4_builtin.c @@ -1,13 +1,13 @@ // Built-in self-contained AMD FSR 4.0.2 INT8 + Qualcomm Hexagon HTP v81/v79 NPU pipeline. // Compiles the verified 103-op FSR 4.0.2 INT8 U-Net on a background thread on first launch -// via Qualcomm libQnnHtpPrepare.so, caches the binary to filesDir/fsr4/v81/fsr4_v07_i8_cache.bin, +// via Qualcomm libQnnHtpPrepare.so, caches the binary to //fsr4_v07_i8_cache.bin, // and executes zero-copy AHardwareBuffer GPU <-> Hexagon HTP inference inside the game's VkCommandBuffer. #define _GNU_SOURCE #include "fsr4_builtin.h" #include "fsr4_qnn.h" #include "fsr_gpu_timer.h" -#include +#include "dd_upscale_compat.h" #include #include #include @@ -17,10 +17,10 @@ #include #include -#define F4_TAG "WinlatorFSR4Builtin" -#define F4_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F4_TAG, __VA_ARGS__) -#define F4_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F4_TAG, __VA_ARGS__) -#define F4_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, F4_TAG, __VA_ARGS__) +#define F4_TAG "DroidDeckUpscaleFSR40" +#define F4_LOGI(...) dd_upscale_log(DD_LOG_INFO, F4_TAG, __VA_ARGS__) +#define F4_LOGW(...) dd_upscale_log(DD_LOG_WARN, F4_TAG, __VA_ARGS__) +#define F4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F4_TAG, __VA_ARGS__) #define BI_OS_W 1920u #define BI_OS_H 1080u diff --git a/tools/upscale/layer/fsr4_layer.c b/tools/upscale/layer/fsr4_layer.c index 2569e35231..46365b7bd6 100644 --- a/tools/upscale/layer/fsr4_layer.c +++ b/tools/upscale/layer/fsr4_layer.c @@ -1,4 +1,5 @@ -// Winlator Ludashi Vulkan Layer: VK_LAYER_WINLATOR_fsr4_npu +// DroidDeck in-game upscaler Vulkan layer: VK_LAYER_DROIDDECK_upscale +// Ported from VK_LAYER_WINLATOR_fsr4_npu (michaelisomer-cyber/Winlator-NeuralScale, GPL-3.0). // // Responsibilities: // 1. Transparently enables required Vulkan extensions & features on Adreno 840 / Turnip @@ -12,7 +13,7 @@ #define _GNU_SOURCE #include #include -#include +#include "dd_upscale_compat.h" #include #include #include @@ -33,14 +34,14 @@ typedef VkPhysicalDeviceComputeShaderDerivativesFeaturesNV VkPhysicalDeviceCompu VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV #endif -#define F4_TAG "WinlatorFSR4Layer" -#define F4_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F4_TAG, __VA_ARGS__) -#define F4_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F4_TAG, __VA_ARGS__) -#define F4_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, F4_TAG, __VA_ARGS__) +#define F4_TAG "DroidDeckUpscale" +#define F4_LOGI(...) dd_upscale_log(DD_LOG_INFO, F4_TAG, __VA_ARGS__) +#define F4_LOGW(...) dd_upscale_log(DD_LOG_WARN, F4_TAG, __VA_ARGS__) +#define F4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F4_TAG, __VA_ARGS__) #define LAYER_EXPORT __attribute__((visibility("default"))) -#define WL_LAYER_NAME "VK_LAYER_WINLATOR_fsr4_npu" -#define WL_LAYER_DESC "Winlator Ludashi FSR 4.1.1 Hexagon HTP NPU Upscaler Layer" +#define WL_LAYER_NAME "VK_LAYER_DROIDDECK_upscale" +#define WL_LAYER_DESC "DroidDeck in-game upscaler (FSR 4 / FSR 3.1 / XeSS / DLSS bridge, GPU and Hexagon NPU)" // ---- Khronos Loader-Layer Interface structs (self-contained, no vk_layer.h needed) ---- typedef enum { @@ -165,15 +166,6 @@ static char g_real_gpu_name[128] = "Unknown"; static volatile int g_rdr2_patched = 0; /* 0=not rdr2, 1=partial, 2=full */ static volatile int g_rdr2_scan_done = 0; -static int has_external_banana_pack(void) { - const char *dir = getenv("WINLATOR_FSR4_DIR"); - if (!dir || !*dir) dir = getenv("DM_FSR4_DIR"); - if (!dir || !*dir) dir = "/data/user/0/com.winlator.cmod/files/fsr4"; - char p[640]; - snprintf(p, sizeof p, "%s/1080/performance/pass-01-npu.spv", dir); - return access(p, R_OK) == 0; -} - static uint8_t *scan_bytes_mask(uint8_t *base, size_t len, const uint8_t *pat, const uint8_t *mask, size_t plen) { if (!base || len < plen || plen == 0) return NULL; size_t limit = len - plen; @@ -237,10 +229,10 @@ static int proc_is_rdr2(void) { // Optional OptiPatcher for RDR2.exe — DISABLED by default because RDR2's Arxan anti-tamper // crashes after the loading screen if RDR2.exe's .text pages are modified. Enable only via -// WINLATOR_FSR4_RDR2_PATCH=1 on Arxan-free builds. +// DROIDDECK_UPSCALE_RDR2_PATCH=1 on Arxan-free builds. static void try_patch_rdr2_exe(void) { if (__atomic_exchange_n(&g_rdr2_scan_done, 1, __ATOMIC_ACQ_REL)) return; - const char *en = getenv("WINLATOR_FSR4_RDR2_PATCH"); + const char *en = dd_upscale_env("RDR2_PATCH"); if (!en || en[0] != '1') return; if (!proc_is_rdr2()) return; @@ -463,12 +455,13 @@ static void read_live_ctrl(LiveCtrlState *out) { static LiveCtrlState cached = { 1, -1, 0, -1.0f }; static uint64_t last_check_ms = 0; if (cached.backend < 0) { - const char *env_b = getenv("WINLATOR_FSR4_BACKEND"); - if (!env_b || !*env_b) env_b = getenv("WINLATOR_FSR4_ENGINE"); - cached.backend = (env_b && *env_b) ? parse_backend_str(env_b) : WL_FSR_BACKEND_FSR4_0_NPU; - const char *env_sync = getenv("WINLATOR_FSR4_NPU_SYNC"); - cached.npu_sync = (env_sync && (!strcmp(env_sync, "sync") || !strcmp(env_sync, "1") || !strcmp(env_sync, "true"))) ? 1 : 0; - const char *env_sh = getenv("WINLATOR_FSR4_SHARPNESS"); + const char *env_b = dd_upscale_env("BACKEND"); + if (!env_b) env_b = dd_upscale_env("ENGINE"); + cached.backend = env_b ? parse_backend_str(env_b) : WL_FSR_BACKEND_FSR4_0_NPU; + // Async NPU unless NPU_SYNC=1 ("sync" and "true" kept for upstream launchers). + const char *env_sync = dd_upscale_env("NPU_SYNC"); + cached.npu_sync = (env_sync && (!strcmp(env_sync, "1") || !strcmp(env_sync, "sync") || !strcmp(env_sync, "true"))) ? 1 : 0; + const char *env_sh = dd_upscale_env("SHARPNESS"); cached.sharpness = (env_sh && *env_sh) ? (float)atof(env_sh) : 0.55f; if (cached.sharpness < 0.0f) cached.sharpness = 0.0f; if (cached.sharpness > 1.0f) cached.sharpness = 1.0f; @@ -476,8 +469,8 @@ static void read_live_ctrl(LiveCtrlState *out) { uint64_t now = layer_now_ms(); if (now - last_check_ms >= 200ULL) { last_check_ms = now; - const char *p = getenv("WINLATOR_FSR4_CTRL_FILE"); - if (p && *p) { + const char *p = dd_upscale_env("CTRL_FILE"); + if (p) { FILE *f = fopen(p, "r"); if (f) { char buf[160]; @@ -530,8 +523,8 @@ static void write_live_status(const WlFsr4Pipeline *pipe, const LiveCtrlState *c last_enabled = ctrl->enabled; last_backend = ctrl->backend; last_sync = ctrl->npu_sync; last_npu = npu; last_qm = qm; last_rw = rw; - const char *p = getenv("WINLATOR_FSR4_STATUS_FILE"); - if (!p || !*p) return; + const char *p = dd_upscale_env("STATUS_FILE"); + if (!p) return; const char *ahb_mode = "pending"; const char *npu_state = "standby"; wl_fsr4_pipe_diag(pipe, &ahb_mode, &npu_state); @@ -561,21 +554,54 @@ static void write_live_status(const WlFsr4Pipeline *pipe, const LiveCtrlState *c // ---- GPU & DLSS spoof helpers ---- static int spoof_dlss_enabled(void) { - const char *v = getenv("WINLATOR_FSR4_SPOOF_DLSS"); + const char *v = dd_upscale_env("SPOOF_DLSS"); return (v && v[0] == '1') || (g_rdr2_patched > 0); } +enum { GPU_SPOOF_NONE = 0, GPU_SPOOF_RTX = 1, GPU_SPOOF_RDNA4 = 2 }; + +// GPU_SPOOF holds words separated by ',', '+', ';' or blanks: +// rtx | rdna4 GPU reported in vendorID/deviceID/deviceName/deviceType/driverVersion +// 1 also report the matching driverID/driverName/driverInfo +// off|none|0 report the real GPU even when SPOOF_DLSS=1 +// Without rtx/rdna4/off, SPOOF_DLSS=1 reports rtx. driverID is never changed without "1". +static void gpu_spoof_config(int *out_id, int *out_driver) { + int id = GPU_SPOOF_NONE, driver = 0, explicit_off = 0; + const char *mode = dd_upscale_env("GPU_SPOOF"); + if (mode) { + char buf[64]; + snprintf(buf, sizeof buf, "%s", mode); + char *save = NULL; + for (char *tok = strtok_r(buf, ",+; \t", &save); tok; tok = strtok_r(NULL, ",+; \t", &save)) { + if (!strcmp(tok, "rtx")) id = GPU_SPOOF_RTX; + else if (!strcmp(tok, "rdna4")) id = GPU_SPOOF_RDNA4; + else if (!strcmp(tok, "1")) driver = 1; + else if (!strcmp(tok, "off") || !strcmp(tok, "none") || !strcmp(tok, "0")) explicit_off = 1; + } + } + if (id == GPU_SPOOF_NONE && !explicit_off) { + const char *v = dd_upscale_env("SPOOF_DLSS"); + if (v && v[0] == '1') id = GPU_SPOOF_RTX; + } + if (out_id) *out_id = id; + if (out_driver) *out_driver = (driver && id != GPU_SPOOF_NONE) ? 1 : 0; +} + +static const char *gpu_spoof_name(int id) { + return id == GPU_SPOOF_RTX ? "rtx" : (id == GPU_SPOOF_RDNA4 ? "rdna4" : "off"); +} + static void apply_gpu_spoof(VkPhysicalDeviceProperties *props) { if (!props) return; - const char *mode = getenv("WINLATOR_FSR4_GPU_SPOOF"); - if (!mode || !*mode || !strcmp(mode, "off") || !strcmp(mode, "none")) return; - if (!strcmp(mode, "rdna4")) { + int id = GPU_SPOOF_NONE; + gpu_spoof_config(&id, NULL); + if (id == GPU_SPOOF_RDNA4) { props->vendorID = 0x1002u; props->deviceID = 0x7550u; props->driverVersion = (2u << 22) | (0u << 12) | 310u; props->deviceType = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU; snprintf(props->deviceName, sizeof props->deviceName, "AMD Radeon RX 9070 XT"); - } else if (!strcmp(mode, "rtx")) { + } else if (id == GPU_SPOOF_RTX) { props->vendorID = 0x10DEu; props->deviceID = 0x1F08u; props->driverVersion = (570u << 22) | (0u << 14); /* NVIDIA 570.00 */ @@ -587,11 +613,10 @@ static void apply_gpu_spoof(VkPhysicalDeviceProperties *props) { static void apply_gpu_spoof2(VkPhysicalDeviceProperties2 *props2) { if (!props2) return; apply_gpu_spoof(&props2->properties); - const char *mode = getenv("WINLATOR_FSR4_GPU_SPOOF"); - if (!mode || !*mode || !strcmp(mode, "off") || !strcmp(mode, "none")) return; - int is_rtx = !strcmp(mode, "rtx"); - int is_rdna4 = !strcmp(mode, "rdna4"); - if (!is_rtx && !is_rdna4) return; + int id = GPU_SPOOF_NONE, driver = 0; + gpu_spoof_config(&id, &driver); + if (!driver) return; + int is_rtx = (id == GPU_SPOOF_RTX); for (VkBaseOutStructure *n = (VkBaseOutStructure *)props2->pNext; n; n = n->pNext) { if (n->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES) { VkPhysicalDeviceDriverProperties *dp = (VkPhysicalDeviceDriverProperties *)n; @@ -709,9 +734,10 @@ static VkResult VKAPI_CALL hook_vkCreateInstance(const VkInstanceCreateInfo *pCr } pthread_mutex_unlock(&g_mu); try_patch_rdr2_exe(); - F4_LOGI("vkCreateInstance attached (dlss_spoof=%d gpu_spoof=%s rdr2_patch=%d)", - spoof_dlss_enabled(), getenv("WINLATOR_FSR4_GPU_SPOOF") ? getenv("WINLATOR_FSR4_GPU_SPOOF") : "off", - (int)g_rdr2_patched); + int spoof_id = GPU_SPOOF_NONE, spoof_driver = 0; + gpu_spoof_config(&spoof_id, &spoof_driver); + F4_LOGI("vkCreateInstance attached (dlss_spoof=%d gpu_spoof=%s driver_spoof=%d rdr2_patch=%d)", + spoof_dlss_enabled(), gpu_spoof_name(spoof_id), spoof_driver, (int)g_rdr2_patched); return VK_SUCCESS; } @@ -728,10 +754,10 @@ static void VKAPI_CALL hook_vkDestroyInstance(VkInstance instance, const VkAlloc } static uint64_t configured_vram_override_bytes(void) { - const char *ov = getenv("WINLATOR_FSR4_VRAM_OVERRIDE"); + const char *ov = dd_upscale_env("VRAM_OVERRIDE"); if (!ov || strcmp(ov, "1") != 0) return 0ULL; - const char *v = getenv("WINLATOR_FSR4_VRAM_MB"); - if (!v || !*v) v = getenv("WRAPPER_VMEM_MAX_SIZE"); + const char *v = dd_upscale_env("VRAM_MB"); + if (!v) v = getenv("WRAPPER_VMEM_MAX_SIZE"); if (!v || !*v) return 0ULL; unsigned long long mb = strtoull(v, NULL, 10); if (mb < 512ULL || mb > 65536ULL) return 0ULL; @@ -878,7 +904,7 @@ static VkResult VKAPI_CALL hook_vkCreateDevice(VkPhysicalDevice pd, memset(&rp, 0, sizeof rp); ic->GetPhysicalDeviceProperties(pd, &rp); if (rp.deviceName[0]) { - snprintf(g_real_gpu_name, sizeof g_real_gpu_name, "%s", rp.deviceName); + snprintf(g_real_gpu_name, sizeof g_real_gpu_name, "%.*s", (int)(sizeof g_real_gpu_name - 1), rp.deviceName); } ts_period = rp.limits.timestampPeriod; } diff --git a/tools/upscale/layer/fsr4_pipeline.c b/tools/upscale/layer/fsr4_pipeline.c index 1cf2b96fa1..cb50ecabb3 100644 --- a/tools/upscale/layer/fsr4_pipeline.c +++ b/tools/upscale/layer/fsr4_pipeline.c @@ -12,7 +12,7 @@ #include "fsr3_gpu.h" #include "fsr4_qnn.h" -#include +#include "dd_upscale_compat.h" #include #include #include @@ -23,10 +23,10 @@ #include #include -#define F4_TAG "WinlatorFSR4NPU" -#define F4_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F4_TAG, __VA_ARGS__) -#define F4_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F4_TAG, __VA_ARGS__) -#define F4_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, F4_TAG, __VA_ARGS__) +#define F4_TAG "DroidDeckUpscalePipe" +#define F4_LOGI(...) dd_upscale_log(DD_LOG_INFO, F4_TAG, __VA_ARGS__) +#define F4_LOGW(...) dd_upscale_log(DD_LOG_WARN, F4_TAG, __VA_ARGS__) +#define F4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F4_TAG, __VA_ARGS__) enum { F4_UW = 1920u, @@ -163,14 +163,14 @@ struct WlFsr4Pipeline { static uint32_t round_up(uint32_t v, uint32_t m) { return (v + m - 1u) / m * m; } static uint32_t div_up(uint32_t v, uint32_t d) { return (v + d - 1u) / d; } -static int env_int(const char *name, int def) { - const char *v = getenv(name); - return (v && *v) ? atoi(v) : def; +static int env_int(const char *key, int def) { + const char *v = dd_upscale_env(key); + return v ? atoi(v) : def; } -static float env_float(const char *name, float def) { - const char *v = getenv(name); - return (v && *v) ? (float)atof(v) : def; +static float env_float(const char *key, float def) { + const char *v = dd_upscale_env(key); + return v ? (float)atof(v) : def; } static uint32_t pick_mem_type(const VkPhysicalDeviceMemoryProperties *mp, uint32_t bits, VkMemoryPropertyFlags want) { @@ -440,7 +440,7 @@ static void *npu_worker_main(void *arg) { __atomic_store_n(&p->npu_ready_slot, slot, __ATOMIC_RELEASE); __atomic_store_n(&p->npu_busy_slot, -1, __ATOMIC_RELEASE); - if (n == 1u || (n % 240u) == 0u || env_int("WINLATOR_FSR4_LOG", 0) >= 2) { + if (n == 1u || (n % 240u) == 0u || env_int("LOG", 0) >= 2) { F4_LOGI("HTP v81 dispatch #%llu preset=%s slot=%d htp=%.2f ms", (unsigned long long)n, preset == WL_FSR4_PRESET_ULTRAPERF ? "ultraperf" : "perf", slot, htp_ms); } @@ -563,18 +563,17 @@ static int f4_ensure_ready(WlFsr4Pipeline *p, int initial_preset) { return 0; } - const char *dir = getenv("WINLATOR_FSR4_DIR"); - if (!dir || !*dir) dir = getenv("DM_FSR4_DIR"); - if (!dir || !*dir) { - F4_LOGW("WINLATOR_FSR4_DIR is not set; using GPU blit fallback"); + const char *dir = dd_upscale_dir(); + if (!dir) { + F4_LOGW("DROIDDECK_UPSCALE_DIR is not set; using GPU blit fallback"); snprintf(p->last_fail_reason, sizeof p->last_fail_reason, "missing_assets"); p->state = -1; return 0; } snprintf(p->dir, sizeof p->dir, "%s", dir); - const char *pwr = getenv("WINLATOR_FSR4_POWER"); - if (!pwr || !*pwr) pwr = "turbo"; + const char *pwr = dd_upscale_env("POWER"); + if (!pwr) pwr = "turbo"; p->qnn = wl_fsr4_qnn_init(p->dir, initial_preset, pwr); if (!p->qnn) { @@ -822,16 +821,14 @@ WlFsr4Pipeline *wl_fsr4_pipe_create(const WlVkDispatch *vk) { return p; } +// NULL when no data dir is set: every backend create then fails and frames take the blit fallback. static const char *resolve_fsr4_dir(void) { - const char *dir = getenv("WINLATOR_FSR4_DIR"); - if (!dir || !*dir) dir = getenv("DM_FSR4_DIR"); - if (!dir || !*dir) dir = "/data/user/0/com.winlator.cmod/files/fsr4"; - return dir; + return dd_upscale_dir(); } static const char *resolve_power_mode(void) { - const char *pwr = getenv("WINLATOR_FSR4_POWER"); - return (pwr && *pwr) ? pwr : "turbo"; + const char *pwr = dd_upscale_env("POWER"); + return pwr ? pwr : "turbo"; } static const char *backend_display_name(int b) { @@ -938,11 +935,15 @@ void wl_fsr4_pipe_diag(const WlFsr4Pipeline *p, const char **out_ahb, const char ahb = p->vk.has_ext_ahb ? "zc_avail" : "staging_avail"; const char *dir = resolve_fsr4_dir(); char cache_p[640], wpk_p[640]; - snprintf(cache_p, sizeof cache_p, "%s/v81/fsr4_v07_i8_cache.bin", dir); - snprintf(wpk_p, sizeof wpk_p, "%s/fsr4_v07_i8.wpack", dir); - if (access(cache_p, R_OK) == 0) npu = "cached"; - else if (access(wpk_p, R_OK) == 0) npu = "ready_to_compile"; - else npu = "no_pack"; + if (!dir) { + npu = "no_pack"; + } else { + wl_fsr4_qnn_cache_path(dir, "fsr4_v07_i8_cache.bin", cache_p, sizeof cache_p); + snprintf(wpk_p, sizeof wpk_p, "%s/fsr4_v07_i8.wpack", dir); + if (access(cache_p, R_OK) == 0) npu = "cached"; + else if (access(wpk_p, R_OK) == 0) npu = "ready_to_compile"; + else npu = "no_pack"; + } } break; } @@ -1235,7 +1236,7 @@ int wl_fsr4_pipe_dispatch(WlFsr4Pipeline *p, VkCommandBuffer cb, // Pick preset (performance 2x or ultraperf 3x) int preset = WL_FSR4_PRESET_PERF; - const char *penv = getenv("WINLATOR_FSR4_PRESET"); + const char *penv = dd_upscale_env("PRESET"); if (frame->preset_hint == WLFSR4_PRESET_ULTRAPERF || frame->quality_mode == WLFSR4_QUALITY_ULTRA_PERF || (penv && !strcmp(penv, "ultraperf"))) { @@ -1383,10 +1384,10 @@ int wl_fsr4_pipe_dispatch(WlFsr4Pipeline *p, VkCommandBuffer cb, int first_imgs = !p->imgs_inited; int reset = first_imgs || (frame->flags & WLFSR4_FLAG_RESET) || (p->last_preset >= 0 && p->last_preset != preset) || dt_ms > 250.f; float pe = (isfinite(frame->pre_exposure) && frame->pre_exposure > 0.f) ? frame->pre_exposure : 1.f; - float jx = frame->jitter_x * env_float("WINLATOR_FSR4_JX", 1.0f); - float jy = frame->jitter_y * env_float("WINLATOR_FSR4_JY", 1.0f); - float mx = frame->mv_scale_x * env_float("WINLATOR_FSR4_MX", 1.0f) / (float)rw; - float my = frame->mv_scale_y * env_float("WINLATOR_FSR4_MY", 1.0f) / (float)rh; + float jx = frame->jitter_x * env_float("JX", 1.0f); + float jy = frame->jitter_y * env_float("JY", 1.0f); + float mx = frame->mv_scale_x * env_float("MX", 1.0f) / (float)rw; + float my = frame->mv_scale_y * env_float("MY", 1.0f) / (float)rh; f4_consts k; memset(&k, 0, sizeof k); diff --git a/tools/upscale/layer/fsr4_qnn.c b/tools/upscale/layer/fsr4_qnn.c index e6b64ca5b2..a035793401 100644 --- a/tools/upscale/layer/fsr4_qnn.c +++ b/tools/upscale/layer/fsr4_qnn.c @@ -1,12 +1,25 @@ -// Clean-room Qualcomm QNN HTP v81 runtime management and zero-copy AHardwareBuffer/dmabuf -// shared tensor binding for Winlator Ludashi FSR 4.1.1 NPU upscaling. +// Clean-room Qualcomm QNN HTP (v79/v81) runtime management and zero-copy AHardwareBuffer/dmabuf +// shared tensor binding for the DroidDeck upscaler layer (ported from Winlator-NeuralScale). // Adapted from BananaNative's verified SM8850 (Adreno 840 / Hexagon HTP v81) runtime. +// DD_UPSCALE_NO_ANDROID builds (glibc) compile only the stubs at the end: every NPU init fails +// with "npu_unavailable" and the callers keep their GPU paths. #define _GNU_SOURCE #include "fsr4_qnn.h" +#include "dd_upscale_compat.h" + +#include +#include + +#define F4_TAG "DroidDeckUpscaleNPU" +#define F4_LOGI(...) dd_upscale_log(DD_LOG_INFO, F4_TAG, __VA_ARGS__) +#define F4_LOGW(...) dd_upscale_log(DD_LOG_WARN, F4_TAG, __VA_ARGS__) +#define F4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F4_TAG, __VA_ARGS__) + +#ifndef DD_UPSCALE_NO_ANDROID #include #include -#include +#include #include #include #include @@ -16,14 +29,10 @@ #include #include #include +#include #include #include -#define F4_TAG "WinlatorFSR4NPU" -#define F4_LOGI(...) __android_log_print(ANDROID_LOG_INFO, F4_TAG, __VA_ARGS__) -#define F4_LOGW(...) __android_log_print(ANDROID_LOG_WARN, F4_TAG, __VA_ARGS__) -#define F4_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, F4_TAG, __VA_ARGS__) - typedef struct { int version; int numFds; @@ -43,6 +52,7 @@ typedef struct { int refs; char power_mode[32]; void *lib_cdsp, *lib_sys, *lib_htp, *lib_prep; + void *lib_stub[2]; const QnnSystemInterface_ImplV1_11_t *S; const QnnInterface_ImplV2_36_t *Q; Qnn_LogHandle_t logger; @@ -132,7 +142,7 @@ static void civac_range(const void *ptr, size_t bytes, size_t line) { } static int qnn_log_verbose(void) { - const char *e = getenv("WINLATOR_FSR4_LOG"); + const char *e = dd_upscale_env("LOG"); return e && atoi(e) >= 2; } @@ -148,6 +158,107 @@ static void qnn_log_cb(const char *fmt, uint32_t level, uint64_t ts, va_list arg else F4_LOGI("QNN: %s", msg); } +// ---- Hexagon HTP arch of this SoC: names the folder that holds compiled context caches ---- +// A context binary only loads on the arch it was finalized for, so caches live in //. +static char g_htp_arch[8]; +static pthread_mutex_t g_htp_arch_mu = PTHREAD_MUTEX_INITIALIZER; +static int g_htp_soc_checked; +static int g_htp_rt_up; // a QNN device exists, so libQnnHtp.so has mapped its stub +static int g_htp_stubs_preloaded_all; // both stubs mapped by us: /proc/self/maps says nothing + +static int htp_arch_valid(const char *a) { + size_t n = a ? strlen(a) : 0; + if (n < 2 || n > 4 || a[0] != 'v') return 0; + for (size_t i = 1; i < n; i++) if (!isdigit((unsigned char)a[i])) return 0; + return 1; +} + +static const char *htp_arch_from_soc(void) { + // SoCs whose HTP skel ships with the layer's data files (adsp/libQnnHtpV79Skel.so, V81Skel.so). + static const struct { const char *model_prefix, *platform, *arch; } k_socs[] = { + {"SM8750", "sun", "v79"}, // Snapdragon 8 Elite + {"SM8850", "canoe", "v81"}, // Snapdragon 8 Elite Gen 5 + }; + char v[PROP_VALUE_MAX]; + static const char *const model_props[] = {"ro.soc.model", "ro.vendor.qti.soc_model"}; + static const char *const platform_props[] = {"ro.vendor.qti.soc_name", "ro.board.platform"}; + for (size_t p = 0; p < sizeof model_props / sizeof model_props[0]; p++) { + if (__system_property_get(model_props[p], v) <= 0) continue; + for (size_t i = 0; i < sizeof k_socs / sizeof k_socs[0]; i++) + if (!strncasecmp(v, k_socs[i].model_prefix, strlen(k_socs[i].model_prefix))) return k_socs[i].arch; + } + for (size_t p = 0; p < sizeof platform_props / sizeof platform_props[0]; p++) { + if (__system_property_get(platform_props[p], v) <= 0) continue; + for (size_t i = 0; i < sizeof k_socs / sizeof k_socs[0]; i++) + if (!strcasecmp(v, k_socs[i].platform)) return k_socs[i].arch; + } + return NULL; +} + +// libQnnHtp.so maps the arch stub (libQnnHtpVNNStub.so) once a device exists. +static int htp_arch_from_maps(char *out, size_t out_sz) { + FILE *f = fopen("/proc/self/maps", "r"); + if (!f) return 0; + char line[1024]; + int found = 0; + while (!found && fgets(line, sizeof line, f)) { + const char *m = strstr(line, "libQnnHtpV"); + size_t skip = 10; + if (!m) { m = strstr(line, "libQairtHtpV"); skip = 12; } + if (!m) continue; + const char *d = m + skip; + size_t n = 0; + while (n < 3 && isdigit((unsigned char)d[n])) n++; + if (n >= 2 && !strncmp(d + n, "Stub.so", 7)) { + snprintf(out, out_sz, "v%.*s", (int)n, d); + found = 1; + } + } + fclose(f); + return found; +} + +static const char *htp_arch_from_skels(const char *fsr4_dir) { + if (!fsr4_dir) return NULL; + char p79[640], p81[640]; + snprintf(p79, sizeof p79, "%s/adsp/libQnnHtpV79Skel.so", fsr4_dir); + snprintf(p81, sizeof p81, "%s/adsp/libQnnHtpV81Skel.so", fsr4_dir); + int has79 = access(p79, R_OK) == 0, has81 = access(p81, R_OK) == 0; + if (has79 != has81) return has79 ? "v79" : "v81"; + return NULL; +} + +// Order: HTP_ARCH env, SoC properties, mapped stub (once a QNN device exists), the only skel in +// /adsp, else "htp". A hit from the first three is kept for the process. +static const char *htp_arch_for_dir(const char *fsr4_dir) { + pthread_mutex_lock(&g_htp_arch_mu); + if (!g_htp_arch[0] && !g_htp_soc_checked) { + g_htp_soc_checked = 1; + const char *env = dd_upscale_env("HTP_ARCH"); + const char *a = htp_arch_valid(env) ? env : htp_arch_from_soc(); + if (a) snprintf(g_htp_arch, sizeof g_htp_arch, "%s", a); + } + if (!g_htp_arch[0] && g_htp_rt_up && !g_htp_stubs_preloaded_all) { + char mapped[8]; + if (htp_arch_from_maps(mapped, sizeof mapped)) snprintf(g_htp_arch, sizeof g_htp_arch, "%s", mapped); + } + const char *out = g_htp_arch[0] ? g_htp_arch : NULL; + pthread_mutex_unlock(&g_htp_arch_mu); + if (out) return out; + const char *a = htp_arch_from_skels(fsr4_dir); + return a ? a : "htp"; +} + +int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz) { + if (!fsr4_dir || !*fsr4_dir || !name || !out || !out_sz) return 0; + int n = snprintf(out, out_sz, "%s/%s/%s", fsr4_dir, htp_arch_for_dir(fsr4_dir), name); + return n > 0 && (size_t)n < out_sz; +} + +static void cache_rel_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz) { + snprintf(out, out_sz, "%s/%s", htp_arch_for_dir(fsr4_dir), name); +} + static void ensure_adsp_path(const char *fsr4_dir) { char adsp[600]; snprintf(adsp, sizeof adsp, "%s/adsp", fsr4_dir); @@ -196,9 +307,9 @@ static int resolve_qnn_lib_path(const char *fsr4_dir, const char *soname, char * // 2. / snprintf(out, out_sz, "%s/%s", fsr4_dir, soname); if (access(out, R_OK) == 0) return 1; - // 3. / - const char *nld = getenv("WINLATOR_FSR4_NATIVELIB_DIR"); - if (nld && *nld) { + // 3. / + const char *nld = dd_upscale_env("NATIVELIB_DIR"); + if (nld) { snprintf(out, out_sz, "%s/%s", nld, soname); if (access(out, R_OK) == 0) return 1; } @@ -247,6 +358,28 @@ static void *dlopen_cdsprpc(void) { return h; } +// libQnnHtp.so dlopens libQnnHtpVStub.so by name. Loading the stub first from the same +// search list (DIR/jni/arm64-v8a, DIR, NATIVELIB_DIR, LD_LIBRARY_PATH) lets that lookup find it +// without LD_LIBRARY_PATH. Unknown arch: every stub that is present gets loaded. +static void preload_htp_stubs(qnn_rt *rt, const char *fsr4_dir) { + static const char *const k_arch[2] = {"v79", "v81"}; + static const char *const k_stubs[2] = {"libQnnHtpV79Stub.so", "libQnnHtpV81Stub.so"}; + const char *arch = htp_arch_for_dir(fsr4_dir); + int known = !strcmp(arch, k_arch[0]) || !strcmp(arch, k_arch[1]); + for (int i = 0; i < 2; i++) { + if (known && strcmp(arch, k_arch[i]) != 0) continue; + char full[640]; + if (!resolve_qnn_lib_path(fsr4_dir, k_stubs[i], full, sizeof full)) continue; + rt->lib_stub[i] = dlopen_qnn_lib_flags(fsr4_dir, k_stubs[i], RTLD_NOW | RTLD_GLOBAL); + if (!rt->lib_stub[i]) F4_LOGW("preload %s failed: %s", full, dlerror()); + } + if (!known && rt->lib_stub[0] && rt->lib_stub[1]) { + pthread_mutex_lock(&g_htp_arch_mu); + g_htp_stubs_preloaded_all = 1; + pthread_mutex_unlock(&g_htp_arch_mu); + } +} + static void request_unsigned_pd(qnn_rt *rt) { rt->lib_cdsp = dlopen_cdsprpc(); if (!rt->lib_cdsp) return; @@ -498,8 +631,13 @@ static void rt_teardown_locked(void) { if (rt->lib_prep) dlclose(rt->lib_prep); if (rt->lib_htp) dlclose(rt->lib_htp); if (rt->lib_sys) dlclose(rt->lib_sys); + for (int i = 0; i < 2; i++) if (rt->lib_stub[i]) dlclose(rt->lib_stub[i]); if (rt->lib_cdsp) dlclose(rt->lib_cdsp); memset(rt, 0, sizeof *rt); + pthread_mutex_lock(&g_htp_arch_mu); + g_htp_rt_up = 0; + g_htp_stubs_preloaded_all = 0; + pthread_mutex_unlock(&g_htp_arch_mu); } static int rt_acquire_locked(const char *fsr4_dir, const char *power_mode) { @@ -513,6 +651,7 @@ static int rt_acquire_locked(const char *fsr4_dir, const char *power_mode) { ensure_adsp_path(fsr4_dir); request_unsigned_pd(&g_rt); + preload_htp_stubs(&g_rt, fsr4_dir); g_rt.lib_sys = dlopen_qnn_lib(fsr4_dir, "libQnnSystem.so"); if (!g_rt.lib_sys) { @@ -592,11 +731,14 @@ static int rt_acquire_locked(const char *fsr4_dir, const char *power_mode) { } if (apply_power_profile(&g_rt, g_rt.power_mode) == 0) - F4_LOGI("HTP v81 runtime initialized (power=%s)", g_rt.power_mode); + F4_LOGI("HTP %s runtime initialized (power=%s)", htp_arch_for_dir(fsr4_dir), g_rt.power_mode); else - F4_LOGI("HTP v81 runtime initialized without perf vote"); + F4_LOGI("HTP %s runtime initialized without perf vote", htp_arch_for_dir(fsr4_dir)); g_rt.refs = 1; + pthread_mutex_lock(&g_htp_arch_mu); + g_htp_rt_up = 1; + pthread_mutex_unlock(&g_htp_arch_mu); return 1; } @@ -867,7 +1009,7 @@ static int graph_load_locked(qnn_graph *g, const char *dir, const char *file, co g->nslots = nslots; g->ready = 1; - F4_LOGI("loaded HTP v81 graph %s (%s)", file, gname_copy); + F4_LOGI("loaded HTP graph %s (%s)", file, gname_copy); return 1; } @@ -1288,10 +1430,14 @@ static int compile_wpack_attempt_locked(const char *fsr4_dir, const uint8_t *wpk if (bin_out) { rc = g_rt.Q->contextGetBinary(ctx, bin_out, bsz, &written); if (rc == QNN_SUCCESS_CODE && written > 0) { - char v81_dir[600], dst_path[640], tmp_path[660]; - snprintf(v81_dir, sizeof v81_dir, "%s/v81", fsr4_dir); - mkdir(v81_dir, 0755); + char arch_dir[600], dst_path[640], tmp_path[660]; snprintf(dst_path, sizeof dst_path, "%s/%s", fsr4_dir, cache_rel); + snprintf(arch_dir, sizeof arch_dir, "%s", dst_path); + char *slash = strrchr(arch_dir, '/'); + if (slash && slash > arch_dir + strlen(fsr4_dir)) { + *slash = '\0'; + mkdir(arch_dir, 0755); + } snprintf(tmp_path, sizeof tmp_path, "%s.tmp", dst_path); FILE *f = fopen(tmp_path, "wb"); if (f && fwrite(bin_out, 1, (size_t)written, f) == (size_t)written) { @@ -1336,11 +1482,11 @@ static int compile_wpack_to_cache_locked(const char *fsr4_dir, const uint8_t *wp } wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel, - const char *cache_rel, const char *graph_name, + const char *cache_name, const char *graph_name, const char *power_mode, uint32_t in_bytes, uint32_t out_bytes) { set_qnn_err("none"); - if (!fsr4_dir || !*fsr4_dir || !wpack_rel || !cache_rel) { set_qnn_err("qnn_nodir"); return NULL; } + if (!fsr4_dir || !*fsr4_dir || !wpack_rel || !cache_name) { set_qnn_err("qnn_nodir"); return NULL; } char wpk_path[640]; snprintf(wpk_path, sizeof wpk_path, "%s/%s", fsr4_dir, wpack_rel); size_t wpk_sz = 0; @@ -1383,6 +1529,8 @@ wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel, } q->has_rt = 1; + char cache_rel[96]; + cache_rel_path(q->dir, cache_name, cache_rel, sizeof cache_rel); int ok = graph_load_locked(&q->presets[0], q->dir, cache_rel, &q->buf, 2, in_offs, out_offs); if (!ok) { if (compile_wpack_to_cache_locked(q->dir, wpk, wpk_sz, cache_rel, graph_name)) { @@ -1397,7 +1545,7 @@ wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel, return NULL; } F4_LOGI("On-device QNN HTP graph '%s' ready (ahb=%zu B, dmabuf=%d)", - graph_name ? graph_name : cache_rel, ahb_bytes, q->buf.dmabuf_fd); + graph_name ? graph_name : cache_name, ahb_bytes, q->buf.dmabuf_fd); return q; } @@ -1464,7 +1612,6 @@ wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mo return NULL; } - const char *cache_rel = "v81/fsr4_v07_i8_cache.bin"; uint64_t in_offs[2] = { 0u, (uint64_t)WL_FSR4_BUILTIN_IN_BYTES }; uint64_t out_offs[2] = { 2u * (uint64_t)WL_FSR4_BUILTIN_IN_BYTES, 2u * (uint64_t)WL_FSR4_BUILTIN_IN_BYTES + (uint64_t)WL_FSR4_BUILTIN_OUT_BYTES }; @@ -1478,6 +1625,8 @@ wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mo } q->has_rt = 1; + char cache_rel[96]; + cache_rel_path(q->dir, "fsr4_v07_i8_cache.bin", cache_rel, sizeof cache_rel); int ok = graph_load_locked(&q->presets[0], q->dir, cache_rel, &q->buf, 2, in_offs, out_offs); if (!ok) { // Compile on-device via libQnnHtpPrepare.so and cache to disk @@ -1537,3 +1686,62 @@ void wl_fsr4_qnn_free(wl_fsr4_qnn *q) { qnn_ahb_free(&q->buf); free(q); } + +#else /* DD_UPSCALE_NO_ANDROID: no FastRPC, AHardwareBuffer or QNN on glibc */ + +static const char *const k_no_npu = "npu_unavailable"; + +const char *wl_fsr4_qnn_last_error(void) { return k_no_npu; } + +int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz) { + if (!fsr4_dir || !*fsr4_dir || !name || !out || !out_sz) return 0; + int n = snprintf(out, out_sz, "%s/htp/%s", fsr4_dir, name); + return n > 0 && (size_t)n < out_sz; +} + +wl_fsr4_qnn *wl_fsr4_qnn_init(const char *fsr4_dir, int preset, const char *power_mode) { + (void)fsr4_dir; (void)preset; (void)power_mode; + return NULL; +} + +wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mode, + uint8_t out_pass0_wb[WL_FSR4_PASS0_WB_BYTES]) { + (void)fsr4_dir; (void)power_mode; (void)out_pass0_wb; + return NULL; +} + +wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel, + const char *cache_name, const char *graph_name, + const char *power_mode, + uint32_t in_bytes, uint32_t out_bytes) { + (void)fsr4_dir; (void)wpack_rel; (void)cache_name; (void)graph_name; + (void)power_mode; (void)in_bytes; (void)out_bytes; + return NULL; +} + +int wl_fsr4_qnn_load_preset(wl_fsr4_qnn *q, int preset) { (void)q; (void)preset; return 0; } +void *wl_fsr4_qnn_ahb(const wl_fsr4_qnn *q) { (void)q; return NULL; } +void *wl_fsr4_qnn_mapped(const wl_fsr4_qnn *q) { (void)q; return NULL; } +int wl_fsr4_qnn_dmabuf_fd(const wl_fsr4_qnn *q) { (void)q; return -1; } + +int wl_fsr4_qnn_exec(wl_fsr4_qnn *q, int preset, int slot, double *out_ms) { + (void)q; (void)preset; (void)slot; + if (out_ms) *out_ms = 0.0; + return 0; +} + +int wl_fsr4_qnn_exec_builtin(wl_fsr4_qnn *q, int slot, double *out_ms) { + (void)q; (void)slot; + if (out_ms) *out_ms = 0.0; + return 0; +} + +int wl_fsr4_qnn_exec_custom(wl_fsr4_qnn *q, int slot, uint32_t in_bytes, uint32_t out_bytes, double *out_ms) { + (void)q; (void)slot; (void)in_bytes; (void)out_bytes; + if (out_ms) *out_ms = 0.0; + return 0; +} + +void wl_fsr4_qnn_free(wl_fsr4_qnn *q) { (void)q; } + +#endif /* DD_UPSCALE_NO_ANDROID */ diff --git a/tools/upscale/layer/fsr4_qnn.h b/tools/upscale/layer/fsr4_qnn.h index 2c8c36f180..fcacbb290b 100644 --- a/tools/upscale/layer/fsr4_qnn.h +++ b/tools/upscale/layer/fsr4_qnn.h @@ -1,5 +1,5 @@ -// Clean-room C declaration of the Qualcomm QNN HTP v81 interface subset and shared-buffer -// helpers for Winlator Ludashi FSR 4.1.1 NPU upscaling. +// Clean-room C declaration of the Qualcomm QNN HTP (v79/v81) interface subset and shared-buffer +// helpers for the DroidDeck upscaler layer (ported from Winlator-NeuralScale). // Struct layouts match the QAIRT 2.47+ C ABI so builds need zero external QNN headers. #pragma once @@ -39,8 +39,9 @@ typedef struct wl_fsr4_qnn wl_fsr4_qnn; wl_fsr4_qnn *wl_fsr4_qnn_init(const char *fsr4_dir, int preset, const char *power_mode); wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mode, uint8_t out_pass0_wb[WL_FSR4_PASS0_WB_BYTES]); +// cache_name is a file name only; the compiled context lives in //. wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel, - const char *cache_rel, const char *graph_name, + const char *cache_name, const char *graph_name, const char *power_mode, uint32_t in_bytes, uint32_t out_bytes); int wl_fsr4_qnn_load_preset(wl_fsr4_qnn *q, int preset); @@ -52,6 +53,8 @@ int wl_fsr4_qnn_exec_builtin(wl_fsr4_qnn *q, int slot, double *out_ms); int wl_fsr4_qnn_exec_custom(wl_fsr4_qnn *q, int slot, uint32_t in_bytes, uint32_t out_bytes, double *out_ms); const char *wl_fsr4_qnn_last_error(void); void wl_fsr4_qnn_free(wl_fsr4_qnn *q); +// Writes //; returns 0 when it does not fit or an argument is missing. +int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz); // ---- Clean-room QNN C ABI definitions (QAIRT 2.47+ / HTP v81) ---- diff --git a/tools/upscale/layer/scripts/pack_fsr412_lite_weights.py b/tools/upscale/layer/scripts/pack_fsr412_lite_weights.py index 959f8a764e..637d9f38f0 100644 --- a/tools/upscale/layer/scripts/pack_fsr412_lite_weights.py +++ b/tools/upscale/layer/scripts/pack_fsr412_lite_weights.py @@ -8,14 +8,16 @@ shaders (0002.comp, 0005.comp, 0007.comp) and genuine 27,392-byte weights.bin. Verifies numerical equivalence against a numpy reference matching the exact shader integer math! """ import re +import sys import struct import hashlib from pathlib import Path import numpy as np -VELA_LITE_DIR = Path(r"c:\Users\omeru\OneDrive\Desktop\print\refs\vela\provider\spirv-sources\lite\converted") -WEIGHTS_BIN = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr412_lite\weights.bin") -OUT_WPACK = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr412_lite\fsr412_lite_i8.wpack") +# Set from the command line: vela provider/spirv-sources/lite/converted, fsr412_lite/weights.bin, output. +VELA_LITE_DIR = None +WEIGHTS_BIN = None +OUT_WPACK = None WPK_MAGIC = 0x314B505734525346 # "FSR4WPK1" WPK_VERSION = 1 @@ -345,4 +347,7 @@ def build_pack(): if __name__ == "__main__": + if len(sys.argv) != 4: + sys.exit("usage: pack_fsr412_lite_weights.py VELA_LITE_CONVERTED_DIR WEIGHTS.bin OUT.wpack") + VELA_LITE_DIR, WEIGHTS_BIN, OUT_WPACK = (Path(a) for a in sys.argv[1:4]) build_pack() diff --git a/tools/upscale/layer/scripts/pack_fsr4_weights.py b/tools/upscale/layer/scripts/pack_fsr4_weights.py index 0b21e28869..2ee6769e95 100644 --- a/tools/upscale/layer/scripts/pack_fsr4_weights.py +++ b/tools/upscale/layer/scripts/pack_fsr4_weights.py @@ -7,13 +7,15 @@ Every op uses standard QNN qti.aisw NHWC / HWIO layouts, group=1 Conv2d, UFIXED_POINT_8 (offset=-128) weights/activations, SFIXED_POINT_32 biases, and 1x1 Conv2d + DepthToSpace(DCR, 2x2) for exact 2x2 stride-2 ConvTranspose. """ +import os import sys import struct import hashlib from pathlib import Path import numpy as np -FSR4_HEX_ROOT = Path(r"C:\Users\omeru\OneDrive\Desktop\print\fsr4-hexagon-master") +# Checkout of puzzled-pancake/fsr4-hexagon (provides model/sim/fsr4_sim.py). +FSR4_HEX_ROOT = Path(os.environ.get("FSR4_HEXAGON_ROOT", "fsr4-hexagon")) sys.path.insert(0, str(FSR4_HEX_ROOT / "model/sim")) import fsr4_sim as S @@ -333,6 +335,6 @@ def build_pack(out_path: Path, pass0_raw_path: Path): if __name__ == "__main__": - out_file = Path(r"C:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr4_v07_i8.wpack") - pass0_raw = Path(r"C:\Users\omeru\.gemini\antigravity\brain\d95b54c2-7fc5-4d0c-85a5-442132a5aeab\scratch\fsr4_seeds\pass0_wb.raw") - build_pack(out_file, pass0_raw) + if len(sys.argv) != 3: + sys.exit("usage: FSR4_HEXAGON_ROOT= pack_fsr4_weights.py OUT.wpack PASS0_WB.raw") + build_pack(Path(sys.argv[1]), Path(sys.argv[2]))